rifftrax.pl 12 KB

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