rifftrax.pl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 = 5;
  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 $OUTPUT_FILE = $DATA_DIR . 'RIFF';
  33. my $STATE_SOCK = $OUTPUT_FILE . '.socket';
  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. {
  160. if ($DEBUG) {
  161. print STDERR 'Matched RIFF: ' . $title . ' => ' . $RIFFS{$title}->{'file'} . "\n";
  162. }
  163. $riff = $title;
  164. # Warm fuzzies
  165. DMX::say('RiffTrax initiated');
  166. # Load and start the audio file
  167. Audio::load('RIFF', $RIFFS{$riff}->{'file'});
  168. playRiff();
  169. # Set volume when we load -- riffs should be louder than normal system sounds
  170. Audio::systemVolume($VOLUME_RIFF);
  171. Audio::volume('RIFF', 1.0);
  172. # Reduce the delay while playing so we sync faster
  173. $delay = 1;
  174. # Enable LEADIN if we're near the beginning of the movie
  175. if ($RIFFS{$riff}->{'offset'} > $LEADIN_TIME && $videoTime < $LEADIN_TIME) {
  176. playPausePlex();
  177. $leadin = 1;
  178. }
  179. }
  180. }
  181. # If the RIFF has changed, save the state to disk
  182. if ($riff ne $riffLast) {
  183. my $new = '<none>';
  184. if ($riff) {
  185. $new = $RIFFS{$riff}->{'name'};
  186. }
  187. my $old = $new;
  188. if ($riffLast) {
  189. $old = $RIFFS{$riffLast}->{'name'};
  190. }
  191. if ($DEBUG) {
  192. print STDERR 'New RIFF: ' . $old . ' => ' . $new . "\n";
  193. }
  194. my ($fh, $tmp) = tempfile($OUTPUT_FILE . '.XXXXXXXX', 'UNLINK' => 0);
  195. print $fh $new . "\n";
  196. close($fh);
  197. rename($tmp, $OUTPUT_FILE);
  198. }
  199. # Skip further processing if we don't have valid state data from Plex
  200. if (!exists($exists{'PLAYING'})) {
  201. next;
  202. }
  203. # Play/pause to match the video or LEADIN state
  204. if ($riff) {
  205. if ($leadin) {
  206. if (!$playing) {
  207. playRiff();
  208. }
  209. } elsif (!$exists{'PLAYING'} && $playing) {
  210. pauseRiff();
  211. } elsif ($exists{'PLAYING'} && !$playing) {
  212. playRiff();
  213. }
  214. }
  215. # Skip further processing if we don't have valid sync data from Plex
  216. if (!$videoTime) {
  217. next;
  218. }
  219. # Sync at most once per second
  220. if ($riff && $lastSync < time()) {
  221. if ($DEBUG) {
  222. print STDERR "Syncing\n";
  223. }
  224. $lastSync = time();
  225. # Get the riff playback state
  226. my $rate = getRiffRate();
  227. my $riffTime = Audio::position('RIFF', undef());
  228. # Update our local playing state tracker
  229. # The rate is always 0 when paused (Audio::playing uses this same methodology)
  230. if ($rate > 0) {
  231. $playing = 1;
  232. } else {
  233. $playing = 0;
  234. }
  235. # Calculate the adjusted riff time and the error between the riff and video times
  236. my $riffAdjTime = $riffTime - $RIFFS{$riff}->{'offset'};
  237. my $error = $videoTime - $riffAdjTime;
  238. my $errorAbs = abs($error);
  239. # Debug
  240. if ($DEBUG) {
  241. print STDERR "\tRate: " . $rate . "\n";
  242. print STDERR "\tOffset: " . $RIFFS{$riff}->{'offset'} . "\n";
  243. print STDERR "\tRiff time: " . $riffTime . "\n";
  244. print STDERR "\tVideo time: " . $videoTime . "\n";
  245. print STDERR "\tAdjusted riff time: " . $riffAdjTime . "\n";
  246. print STDERR "\tError: " . $error . "\n";
  247. print STDERR "\tLeadin: " . $leadin . "\n";
  248. }
  249. # If LEADIN is still active
  250. if ($leadin) {
  251. # Deactivate LEADIN if the movie advances outside the LEADIN_TIME window
  252. if ($videoTime > $LEADIN_TIME) {
  253. $leadin = 0;
  254. if ($DEBUG) {
  255. print STDERR "LEADIN canceled due to video time\n";
  256. }
  257. }
  258. # Start the movie when we reach the sync point
  259. if ($RIFFS{$riff}->{'offset'} <= $riffTime) {
  260. if (!$exists{'PLAYING'}) {
  261. playPausePlex();
  262. }
  263. $leadin = 0;
  264. if ($DEBUG) {
  265. print STDERR "LEADIN canceled due to synchronization\n";
  266. }
  267. }
  268. # Skip normal syncing until LEADIN is cleared
  269. if ($leadin) {
  270. next;
  271. }
  272. }
  273. # Adjust the riff rate/position if we're off by 0.5 seconds or more
  274. if ($errorAbs > 0.5) {
  275. # Calculate the new position, including an ACTION_DELAY adjustment to compensate for time elapsed in this process
  276. my $newPos = $riffTime + $error + $ACTION_DELAY;
  277. if ($newPos < 0) {
  278. pauseRiff();
  279. } else {
  280. # Jump if we're off by more than a few seconds
  281. if ($errorAbs > $JUMP_THRESHOLD) {
  282. if ($DEBUG) {
  283. print STDERR 'Jumping to: ' . $newPos . "\n";
  284. }
  285. Audio::position('RIFF', $newPos);
  286. $error = 0;
  287. $errorAbs = 0;
  288. }
  289. # Set the rate when we adjust, unless we're paused
  290. if ($playing) {
  291. my $rateDiff = $errorAbs / $JUMP_THRESHOLD;
  292. my $newRate = 1.0;
  293. if ($error < 0) {
  294. $newRate -= $rateDiff;
  295. } else {
  296. $newRate += $rateDiff;
  297. }
  298. if ($DEBUG) {
  299. print STDERR 'Setting rate to: ' . $newRate . "\n";
  300. }
  301. setRiffRate($newRate);
  302. }
  303. }
  304. } else {
  305. # Reset the rate to standard if we're inside sync the window
  306. if ($rate != 1.0) {
  307. setRiffRate(1.0);
  308. }
  309. }
  310. }
  311. }
  312. sub playRiff() {
  313. if ($DEBUG) {
  314. print STDERR "playRiff()\n";
  315. }
  316. $playing = 1;
  317. Audio::background('RIFF');
  318. }
  319. sub pauseRiff() {
  320. if ($DEBUG) {
  321. print STDERR "pauseRiff()\n";
  322. }
  323. $playing = 0;
  324. Audio::pause('RIFF');
  325. }
  326. sub getRiffRate() {
  327. if ($DEBUG) {
  328. print STDERR "getRiffRate()\n";
  329. }
  330. my $rate = 0;
  331. if ($playing) {
  332. $rate = Audio::rate('RIFF', undef());
  333. }
  334. return $rate;
  335. }
  336. sub setRiffRate($) {
  337. my ($rate) = @_;
  338. if ($DEBUG) {
  339. print STDERR 'setRiffRate(): ' . $rate . "\n";
  340. }
  341. if ($playing) {
  342. Audio::rate('RIFF', $rate);
  343. }
  344. }
  345. sub parseConfig($$) {
  346. my ($conf_path, $riffs) = @_;
  347. if ($DEBUG) {
  348. print STDERR "parseConfig()\n";
  349. }
  350. opendir(CONF, $conf_path)
  351. or die('Unable to open config directory: ' . $! . "\n");
  352. foreach my $file (readdir(CONF)) {
  353. # Skip silly files
  354. if ($file =~ /^\._/) {
  355. next;
  356. }
  357. if ($file =~ /\.riff$/) {
  358. my $path = $conf_path . '/' . $file;
  359. # Slurp the contents
  360. my $text = '';
  361. if (!open(my $fh, $path)) {
  362. warn('Unable to open ' . $path . "\n");
  363. next;
  364. } else {
  365. local $/;
  366. $text = <$fh>;
  367. close($fh);
  368. }
  369. # Parse out the data we care about
  370. my %data = ();
  371. if ($text =~ /^\s*Name:[ \t]*(\S.*\S)\s*$/mi) {
  372. $data{'name'} = $1;
  373. }
  374. if ($text =~ /^\s*Year:[ \t]*(\d{4})\s*$/mi) {
  375. $data{'year'} = $1;
  376. }
  377. if ($text =~ /^\s*File:[ \t]*(\S.*\S)\s*$/mi) {
  378. $data{'file'} = $1;
  379. }
  380. if ($text =~ /^\s*Offset:[ \t]*([\-\+]?\d+(?:\.\d+)?)\s*$/mi) {
  381. $data{'offset'} = $1 * 1.0;
  382. }
  383. # Ensure we have a valid record
  384. if (!$data{'name'}) {
  385. warn('Invalid riff file: ' . $file . "\n");
  386. next;
  387. }
  388. # Try to find a related file
  389. if (!$data{'file'}) {
  390. $data{'file'} = $file;
  391. $data{'file'} =~ s/\.riff$/\.mp3/i;
  392. $data{'file'} = $conf_path . '/' . $data{'file'};
  393. }
  394. # Ensure the path is valid
  395. if (!-r $data{'file'}) {
  396. warn('Invalid MP3 file in riff ' . $file . ' => ' . $data{'file'} . "\n");
  397. next;
  398. }
  399. # Debug
  400. if ($DEBUG) {
  401. print STDERR 'Added RiffTrax: ' . $data{'name'} . "\n\tFile: " . $data{'file'} . "\n\tOffset: " . $data{'offset'} . "\n";
  402. }
  403. # Push the data up the chain
  404. $riffs->{ $data{'name'} } = \%data;
  405. }
  406. }
  407. closedir(CONF);
  408. # Record the last update time
  409. $riffs->{'_LAST_CONFIG_UPDATE'} = time();
  410. }
  411. # The UDP listener would be more portable, but I already know how to do this
  412. # The PMS playback API would work too, but this script currently knows nothing of the PMS
  413. sub playPausePlex() {
  414. Audio::runApplescript('tell application "System Events" to key code 49');
  415. }