rifftrax.pl 12 KB

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