rifftrax.pl 13 KB

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