rifftrax.pl 11 KB

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