rifftrax.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use File::Temp qw( tempfile );
  5. use Scalar::Util qw( refaddr );
  6. use Time::HiRes qw( usleep sleep time );
  7. use IPC::System::Simple qw( system capture );
  8. # Local modules
  9. use Cwd qw(abs_path);
  10. use File::Basename qw(dirname);
  11. use lib dirname(abs_path($0));
  12. use DMX;
  13. use Audio;
  14. # Config
  15. my $MEDIA_PATH = `~/bin/video/mediaPath`;
  16. my $CONFIG_PATH = $MEDIA_PATH . '/DMX/RiffTrax';
  17. my $ACTION_DELAY = 0.1;
  18. my $JUMP_THRESHOLD = 5;
  19. my $LEADIN_TIME = 8;
  20. my $VOLUME_RIFF = 65;
  21. my $VOLUME_STD = 40;
  22. my $VOL_STEP = 1 / 20;
  23. my $CONFIG_DELAY = 300;
  24. # Prototypes
  25. sub playRiff();
  26. sub pauseRiff();
  27. sub getRiffRate();
  28. sub setRiffRate($);
  29. sub parseConfig($$);
  30. sub playPausePlex();
  31. # App config
  32. my $DATA_DIR = DMX::dataDir();
  33. my $STATE_SOCK = 'RIFF';
  34. my $OUTPUT_FILE = $DATA_DIR . $STATE_SOCK;
  35. my $PULL_TIMEOUT = 60;
  36. my $DELAY = $PULL_TIMEOUT / 3;
  37. my %RIFFS = ();
  38. my %ATTRS = (
  39. 'name' => { 'dmx' => 'PLAYING_TITLE', 'regex' => qr/^\s*Name:[ \t]*(\S.*\S)\s*$/mi },
  40. 'year' => { 'dmx' => 'PLAYING_YEAR', 'regex' => qr/^\s*Year:[ \t]*(\d{4})\s*$/mi },
  41. 'series' => { 'dmx' => 'PLAYING_SERIES', 'regex' => qr/^\s*Series:[ \t]*(\S.*\S)\s*$/mi },
  42. 'season' => { 'dmx' => 'PLAYING_SEASON', 'regex' => qr/^\s*Season:[ \t]*(\d+)\s*$/mi },
  43. 'episode' => { 'dmx' => 'PLAYING_EPISODE', 'regex' => qr/^\s*Episode:[ \t]*(\d+)\s*$/mi },
  44. 'file' => { 'regex' => qr/^\s*File:[ \t]*(\S.*\S)\s*$/mi },
  45. 'offset' => { 'regex' => qr/^\s*Offset:[ \t]*([\-\+]?\d+(?:\.\d+)?)\s*$/mi },
  46. );
  47. # Debug
  48. my $DEBUG = 0;
  49. if ($ENV{'DEBUG'}) {
  50. $DEBUG = 1;
  51. }
  52. # Sockets
  53. DMX::stateSocket($STATE_SOCK);
  54. DMX::stateSubscribe($STATE_SOCK);
  55. # State
  56. my $state = 'OFF';
  57. my $stateLast = $state;
  58. my $riff = '';
  59. my $riffLast = $riff;
  60. my $title = '';
  61. my $titleLast = $title;
  62. my %exists = ();
  63. my %last = ();
  64. my $pullLast = time();
  65. my $lastSync = time();
  66. my $playing = 0;
  67. my $delay = $DELAY;
  68. my $leadin = 0;
  69. # Read the config
  70. parseConfig($CONFIG_PATH, \%RIFFS);
  71. # Loop forever
  72. while (1) {
  73. # Save the last RIFF and state
  74. $stateLast = $state;
  75. $riffLast = $riff;
  76. %last = %exists;
  77. # Reconnect if we're playing and haven't seen an update for $JUMP_THRESHOLD seconds
  78. # During leadin this leads to a number of reconnects, but that's preferable to missing a disconnect
  79. if ($playing && time() - $pullLast > $JUMP_THRESHOLD) {
  80. print STDERR "Attempting to reconnect state socket...\n";
  81. DMX::stateSubscribe($STATE_SOCK);
  82. }
  83. # Wait for state updates
  84. my $cmdState = DMX::readState($delay, \%exists, undef(), undef());
  85. if (defined($cmdState)) {
  86. $state = $cmdState;
  87. # Don't count HUP as a valid update
  88. if ($state ne 'HUP') {
  89. $pullLast = time();
  90. }
  91. }
  92. # Die if we don't see regular updates
  93. if (time() - $pullLast > $PULL_TIMEOUT) {
  94. die('No update on state socket in past ' . $PULL_TIMEOUT . " seconds. Exiting...\n");
  95. }
  96. # Re-read the config on-demand
  97. if ($state eq 'HUP') {
  98. parseConfig($CONFIG_PATH, \%RIFFS);
  99. # Skip further processing this loop -- the exists hash is useless
  100. next;
  101. }
  102. # Re-read the config periodically (unless we are currently playing)
  103. if (!$riff && time() > $RIFFS{'_LAST_CONFIG_UPDATE'} + $CONFIG_DELAY) {
  104. parseConfig($CONFIG_PATH, \%RIFFS);
  105. }
  106. # Handle volume changes
  107. if ($riff) {
  108. if ($state eq 'VOL+' || $state eq 'VOL-') {
  109. # Calculate a relative volume
  110. my $vol = Audio::volume('RIFF', undef());
  111. if ($state eq 'VOL+') {
  112. $vol += $VOL_STEP;
  113. } else {
  114. $vol -= $VOL_STEP;
  115. }
  116. # Limit the range to 0.0 - 1.0
  117. if ($vol < 0) {
  118. $vol = 0;
  119. }
  120. if ($vol > 1) {
  121. $vol = 1;
  122. }
  123. # Set the document volume
  124. Audio::volume('RIFF', $vol);
  125. # Skip further processing this loop -- the exists hash is useless
  126. next;
  127. }
  128. }
  129. # Save the last URL, so we can find changes
  130. # Do not delete the last URL if no new one is provided
  131. if (exists($exists{'PLAYING_TITLE'})) {
  132. $titleLast = $title;
  133. $title = $exists{'PLAYING_TITLE'};
  134. }
  135. # Convert the video timestamp to seconds
  136. my $videoTime = 0;
  137. if ($exists{'PLAYING_POSITION'}) {
  138. my @parts = split(/\:/, $exists{'PLAYING_POSITION'});
  139. $videoTime = 0;
  140. if (scalar(@parts) == 3) {
  141. $videoTime = ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];
  142. } elsif (scalar(@parts) == 2) {
  143. $videoTime = ($parts[0] * 60) + $parts[1];
  144. } else {
  145. $videoTime = $parts[0];
  146. }
  147. }
  148. # Update our state when the PLAYING_TITLE changes
  149. if ($title ne $titleLast) {
  150. # If a RIFF was active, clear it
  151. if ($riff) {
  152. if ($DEBUG) {
  153. print STDERR "RIFF complete\n";
  154. }
  155. # Increase the delay while nothing is happening
  156. $delay = $DELAY;
  157. # Reset the volume when we unload -- normal system sounds should be quieter than riffs
  158. Audio::systemVolume($VOLUME_STD);
  159. # Close the audio file
  160. Audio::unload('RIFF');
  161. $riff = undef();
  162. $leadin = 0;
  163. # Warm fuzzies
  164. DMX::say('RiffTrax complete');
  165. }
  166. # Activate a new RIFF, if applicable
  167. # Always match on title, validate year if provided
  168. if ($RIFFS{$title}) {
  169. if ($DEBUG) {
  170. print STDERR 'Matched RIFF title: ' . $title . "\n";
  171. }
  172. # Find the best available match among media with identical titles
  173. my $match = undef();
  174. {
  175. my $matchAttrCount = 0;
  176. foreach my $data (@{ $RIFFS{$title} }) {
  177. my $valid = 1;
  178. my $attrCount = 0;
  179. if ($DEBUG) {
  180. print STDERR '';
  181. }
  182. foreach my $attr (keys(%ATTRS)) {
  183. if (!exists($data->{$attr}) || !exists($ATTRS{$attr}{'dmx'})) {
  184. next;
  185. }
  186. if ($data->{$attr} eq $exists{ $ATTRS{$attr}{'dmx'} }) {
  187. if ($DEBUG) {
  188. print STDERR "\t\tMatched attr: " . $attr . ' => ' . $data->{$attr} . "\n";
  189. }
  190. $attrCount++;
  191. } else {
  192. if ($DEBUG) {
  193. print STDERR "\t\tFailed match for attr: " . $attr . ' => ' . $data->{$attr} . "\n";
  194. }
  195. $valid = 0;
  196. last;
  197. }
  198. }
  199. # Record the match if it's better than previous matches
  200. if ($valid && $attrCount > $matchAttrCount) {
  201. $match = $data;
  202. $matchAttrCount = $attrCount;
  203. }
  204. }
  205. }
  206. # Match exists -- activate
  207. if ($match) {
  208. $riff = $match;
  209. # Warm fuzzies
  210. DMX::say('RiffTrax initiated');
  211. # Load and start the audio file
  212. Audio::load('RIFF', $riff->{'file'});
  213. playRiff();
  214. # Set volume when we load -- riffs should be louder than normal system sounds
  215. Audio::systemVolume($VOLUME_RIFF);
  216. Audio::volume('RIFF', 1.0);
  217. # Reduce the delay while playing so we sync faster
  218. $delay = 1;
  219. # Enable LEADIN if we're near the beginning of the movie
  220. if ($riff->{'offset'} > $LEADIN_TIME && $videoTime < $LEADIN_TIME) {
  221. playPausePlex();
  222. $leadin = 1;
  223. }
  224. }
  225. }
  226. }
  227. # If the RIFF has changed, save the state to disk
  228. if ( (defined($riff) != defined($riffLast))
  229. || (defined($riff) && ref($riff) && defined($riffLast) && ref($riffLast) && refaddr($riff) == refaddr($riffLast)))
  230. {
  231. my $new = '<none>';
  232. if ($riff) {
  233. $new = $riff->{'name'};
  234. }
  235. my $old = $new;
  236. if ($riffLast) {
  237. $old = $riffLast->{'name'};
  238. }
  239. if ($DEBUG) {
  240. print STDERR 'New RIFF: ' . $old . ' => ' . $new . "\n";
  241. }
  242. my ($fh, $tmp) = tempfile($OUTPUT_FILE . '.XXXXXXXX', 'UNLINK' => 0);
  243. print $fh $new . "\n";
  244. close($fh);
  245. rename($tmp, $OUTPUT_FILE);
  246. }
  247. # Skip further processing if we don't have valid state data from Plex
  248. if (!exists($exists{'PLAYING'})) {
  249. next;
  250. }
  251. # Play/pause to match the video or LEADIN state
  252. if ($riff) {
  253. if ($leadin) {
  254. if (!$playing) {
  255. playRiff();
  256. }
  257. } elsif (!$exists{'PLAYING'} && $playing) {
  258. pauseRiff();
  259. } elsif ($exists{'PLAYING'} && !$playing) {
  260. playRiff();
  261. }
  262. }
  263. # Skip further processing if we don't have valid sync data from Plex
  264. if (!$videoTime) {
  265. next;
  266. }
  267. # Sync at most once per second
  268. if ($riff && $lastSync < time()) {
  269. if ($DEBUG) {
  270. print STDERR "Syncing\n";
  271. }
  272. $lastSync = time();
  273. # Get the riff playback state
  274. my $rate = getRiffRate();
  275. my $riffTime = Audio::position('RIFF', undef());
  276. # Update our local playing state tracker
  277. # The rate is always 0 when paused (Audio::playing uses this same methodology)
  278. if ($rate > 0) {
  279. $playing = 1;
  280. } else {
  281. $playing = 0;
  282. }
  283. # Calculate the adjusted riff time and the error between the riff and video times
  284. my $riffAdjTime = $riffTime - $riff->{'offset'};
  285. my $error = $videoTime - $riffAdjTime;
  286. my $errorAbs = abs($error);
  287. # Debug
  288. if ($DEBUG) {
  289. print STDERR "\tRate: " . $rate . "\n";
  290. print STDERR "\tOffset: " . $riff->{'offset'} . "\n";
  291. print STDERR "\tRiff time: " . $riffTime . "\n";
  292. print STDERR "\tVideo time: " . $videoTime . "\n";
  293. print STDERR "\tAdjusted riff time: " . $riffAdjTime . "\n";
  294. print STDERR "\tError: " . $error . "\n";
  295. print STDERR "\tLeadin: " . $leadin . "\n";
  296. }
  297. # If LEADIN is still active
  298. if ($leadin) {
  299. # Deactivate LEADIN if the movie advances outside the LEADIN_TIME window
  300. if ($videoTime > $LEADIN_TIME) {
  301. $leadin = 0;
  302. if ($DEBUG) {
  303. print STDERR "LEADIN canceled due to video time\n";
  304. }
  305. }
  306. # Start the movie when we reach the sync point
  307. if ($riff->{'offset'} <= $riffTime) {
  308. if (!$exists{'PLAYING'}) {
  309. playPausePlex();
  310. }
  311. $leadin = 0;
  312. if ($DEBUG) {
  313. print STDERR "LEADIN canceled due to synchronization\n";
  314. }
  315. }
  316. # Skip normal syncing until LEADIN is cleared
  317. if ($leadin) {
  318. next;
  319. }
  320. }
  321. # Adjust the riff rate/position if we're off by 0.5 seconds or more
  322. if ($errorAbs > 0.5) {
  323. # Calculate the new position, including an ACTION_DELAY adjustment to compensate for time elapsed in this process
  324. my $newPos = $riffTime + $error + $ACTION_DELAY;
  325. if ($newPos < 0) {
  326. pauseRiff();
  327. } else {
  328. # Jump if we're off by more than a few seconds
  329. if ($errorAbs > $JUMP_THRESHOLD) {
  330. if ($DEBUG) {
  331. print STDERR 'Jumping to: ' . $newPos . "\n";
  332. }
  333. Audio::position('RIFF', $newPos);
  334. $error = 0;
  335. $errorAbs = 0;
  336. }
  337. # Set the rate when we adjust, unless we're paused
  338. if ($playing) {
  339. my $rateDiff = $errorAbs / $JUMP_THRESHOLD;
  340. my $newRate = 1.0;
  341. if ($error < 0) {
  342. $newRate -= $rateDiff;
  343. } else {
  344. $newRate += $rateDiff;
  345. }
  346. if ($DEBUG) {
  347. print STDERR 'Setting rate to: ' . $newRate . "\n";
  348. }
  349. setRiffRate($newRate);
  350. }
  351. }
  352. } else {
  353. # Reset the rate to standard if we're inside sync the window
  354. if ($rate != 1.0) {
  355. setRiffRate(1.0);
  356. }
  357. }
  358. }
  359. }
  360. sub playRiff() {
  361. if ($DEBUG) {
  362. print STDERR "playRiff()\n";
  363. }
  364. $playing = 1;
  365. Audio::background('RIFF');
  366. }
  367. sub pauseRiff() {
  368. if ($DEBUG) {
  369. print STDERR "pauseRiff()\n";
  370. }
  371. $playing = 0;
  372. Audio::pause('RIFF');
  373. }
  374. sub getRiffRate() {
  375. if ($DEBUG) {
  376. print STDERR "getRiffRate()\n";
  377. }
  378. my $rate = 0;
  379. if ($playing) {
  380. $rate = Audio::rate('RIFF', undef());
  381. }
  382. return $rate;
  383. }
  384. sub setRiffRate($) {
  385. my ($rate) = @_;
  386. if ($DEBUG) {
  387. print STDERR 'setRiffRate(): ' . $rate . "\n";
  388. }
  389. if ($playing) {
  390. Audio::rate('RIFF', $rate);
  391. }
  392. }
  393. sub parseConfig($$) {
  394. my ($conf_path, $riffs) = @_;
  395. if ($DEBUG) {
  396. print STDERR "parseConfig()\n";
  397. }
  398. opendir(CONF, $conf_path)
  399. or die('Unable to open config directory: ' . $! . "\n");
  400. foreach my $file (readdir(CONF)) {
  401. # Skip silly files
  402. if ($file =~ /^\._/) {
  403. next;
  404. }
  405. if ($file =~ /\.riff$/) {
  406. my $path = $conf_path . '/' . $file;
  407. # Slurp the contents
  408. my $text = '';
  409. if (!open(my $fh, $path)) {
  410. warn('Unable to open ' . $path . "\n");
  411. next;
  412. } else {
  413. local $/;
  414. $text = <$fh>;
  415. close($fh);
  416. }
  417. # Parse out the data we care about
  418. my %data = ();
  419. foreach my $attr (keys(%ATTRS)) {
  420. if (!exists($ATTRS{$attr}{'regex'})) {
  421. next;
  422. }
  423. if ($text =~ $ATTRS{$attr}{'regex'}) {
  424. $data{$attr} = $1;
  425. }
  426. }
  427. # Ensure we have a valid record
  428. if (!$data{'name'}) {
  429. warn('Invalid riff file: ' . $file . "\n");
  430. next;
  431. }
  432. # Try to find a related file
  433. if (!$data{'file'}) {
  434. $data{'file'} = $file;
  435. $data{'file'} =~ s/\.riff$/\.mp3/i;
  436. $data{'file'} = $conf_path . '/' . $data{'file'};
  437. }
  438. # Ensure the path is valid
  439. if (!-r $data{'file'}) {
  440. warn('Invalid MP3 file in riff ' . $file . ' => ' . $data{'file'} . "\n");
  441. next;
  442. }
  443. # Debug
  444. if ($DEBUG) {
  445. print STDERR 'Added RiffTrax: ' . $file . "\n";
  446. foreach my $attr (keys(%ATTRS)) {
  447. if ($data{$attr}) {
  448. print STDERR "\t" . $attr . ': ' . $data{$attr} . "\n";
  449. }
  450. }
  451. }
  452. # Push the data up the chain
  453. if (!exists($riffs->{ $data{'name'} })) {
  454. my @tmp = ();
  455. $riffs->{ $data{'name'} } = \@tmp;
  456. }
  457. push(@{ $riffs->{ $data{'name'} } }, \%data);
  458. }
  459. }
  460. closedir(CONF);
  461. # Record the last update time
  462. $riffs->{'_LAST_CONFIG_UPDATE'} = time();
  463. }
  464. # The UDP listener would be more portable, but I already know how to do this
  465. # The PMS playback API would work too, but this script currently knows nothing of the PMS
  466. sub playPausePlex() {
  467. my @cmd = ('tell application "Plex" to activate', 'tell application "System Events" to key code 49');
  468. Audio::runApplescript(join("\n", @cmd));
  469. }