rifftrax.pl 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 $RIFF_PATH = $MEDIA_PATH . '/iTunes/iTunes Music/RiffTrax';
  17. my $ACTION_DELAY = 0.1;
  18. my $JUMP_THRESHOLD = 5;
  19. # App config
  20. my $DATA_DIR = DMX::dataDir();
  21. my $OUTPUT_FILE = $DATA_DIR . 'RIFF';
  22. my $STATE_SOCK = $OUTPUT_FILE . '.socket';
  23. my $PULL_TIMEOUT = 60;
  24. my $DELAY = $PULL_TIMEOUT / 2;
  25. my %RIFFS = ();
  26. # Debug
  27. my $DEBUG = 0;
  28. if ($ENV{'DEBUG'}) {
  29. $DEBUG = 1;
  30. }
  31. # Read the config
  32. opendir(CONF, $CONFIG_PATH)
  33. or die('Unable to open config directory: ' . $! . "\n");
  34. foreach my $file (readdir(CONF)) {
  35. # Skip silly files
  36. if ($file =~ /^\._/) {
  37. next;
  38. }
  39. if ($file =~ /\.riff$/) {
  40. my $path = $CONFIG_PATH . '/' . $file;
  41. # Slurp the contents
  42. my $text = '';
  43. if (!open(my $fh, $path)) {
  44. warn('Unable to open ' . $path . "\n");
  45. } else {
  46. local $/;
  47. $text = <$fh>;
  48. close($fh);
  49. }
  50. # Parse out the data we care about
  51. my %data = ();
  52. if ($text =~ /^\s*Name:\s*(\S.*\S)\s*$/mi) {
  53. $data{'name'} = $1;
  54. }
  55. if ($text =~ /^\s*File:\s*(\S.*\S)\s*$/mi) {
  56. $data{'file'} = $1;
  57. }
  58. if ($text =~ /^\s*Offset:\s*([\-\+]?\d+(?:\.\d+)?)\s*$/mi) {
  59. $data{'offset'} = $1;
  60. }
  61. if ($text =~ /^\s*Rate:\s*(\d+(?:\.\d+)?)\s*$/mi) {
  62. $data{'rate'} = $1;
  63. }
  64. # Ensure we have a valid record
  65. if (!$data{'name'} || !$data{'file'}) {
  66. die('Invalid riff file: ' . $file . ' => ' . $data{'name'} . "\n");
  67. }
  68. # Construct an absolute path
  69. if ($data{'file'} =~ /^\//) {
  70. $data{'path'} = $data{'file'};
  71. } else {
  72. $data{'path'} = $RIFF_PATH . '/' . $data{'file'};
  73. }
  74. # Ensure the path is valid
  75. if (!-r $data{'path'}) {
  76. die('Invalid riff path: ' . $file . ' => ' . $data{'path'} . "\n");
  77. }
  78. # Debug
  79. if ($DEBUG) {
  80. print STDERR 'Added RiffTrax: ' . $data{'name'} . "\n\tFile: " . $data{'file'} . "\n\tOffset: " . $data{'offset'} . "\n\tRate: " . $data{'rate'} . "\n";
  81. }
  82. # Push the data up the chain
  83. $RIFFS{ $data{'name'} } = \%data;
  84. }
  85. }
  86. closedir(CONF);
  87. # Sockets
  88. DMX::stateSocket($STATE_SOCK);
  89. DMX::stateSubscribe($STATE_SOCK);
  90. # State
  91. my $state = 'OFF';
  92. my $stateLast = $state;
  93. my $riff = -1;
  94. my $riffLast = $riff;
  95. my $url = '';
  96. my $urlLast = $url;
  97. my $nudge = 0;
  98. my %exists = ();
  99. my %last = ();
  100. my $pullLast = time();
  101. # Loop forever
  102. while (1) {
  103. # Save the last RIFF and state
  104. $stateLast = $state;
  105. $riffLast = $riff;
  106. %last = %exists;
  107. # Force a change if our riff is clearly invalid (first loop, reset, etc.)
  108. if ($riff < 0) {
  109. $riff = 0;
  110. }
  111. # Wait for state updates
  112. my $cmdState = DMX::readState($DELAY, \%exists, undef(), undef());
  113. if (defined($cmdState)) {
  114. $state = $cmdState;
  115. $pullLast = time();
  116. }
  117. # Die if we don't see regular updates
  118. if (time() - $pullLast > $PULL_TIMEOUT) {
  119. die('No update on state socket in past ' . $PULL_TIMEOUT . " seconds. Exiting...\n");
  120. }
  121. # Record nudges
  122. if ($state eq 'NUDGE_FORWARD') {
  123. $nudge -= 0.1;
  124. next;
  125. } elsif ($state eq 'NUDGE_BACK') {
  126. $nudge += 0.1;
  127. next;
  128. }
  129. # Save the last URL, so we can find changes
  130. # Do not delete the last URL if no new one is provided
  131. if ($exists{'PLAYING_URL'}) {
  132. $urlLast = $url;
  133. $url = $exists{'PLAYING_URL'};
  134. }
  135. # Update our state when the PLAYING_URL changes
  136. if ($url ne $urlLast) {
  137. # If a RIFF was active, clear it
  138. if ($riff) {
  139. if ($DEBUG) {
  140. print STDERR "RIFF complete\n";
  141. }
  142. Audio::drop('RIFF');
  143. $riff = 0;
  144. $nudge = 0;
  145. DMX::say('RiffTrax complete');
  146. }
  147. # Activate a new RIFF, if applicable
  148. if ($exists{'PLAYING_TITLE'} && exists($RIFFS{ $exists{'PLAYING_TITLE'} })) {
  149. $riff = $exists{'PLAYING_TITLE'};
  150. if ($DEBUG) {
  151. print STDERR 'Matched RIFF: ' . $riff . ' => ' . $RIFFS{$riff}->{'file'} . "\n";
  152. }
  153. Audio::addLoad('RIFF', $RIFFS{$riff}->{'path'});
  154. Audio::background('RIFF');
  155. Audio::rate('RIFF', $RIFFS{$riff}->{'rate'});
  156. DMX::say('RiffTrax initiated');
  157. }
  158. }
  159. # If the RIFF has changed, save the state to disk
  160. if ($riff ne $riffLast) {
  161. my $new = '<none>';
  162. if ($riff) {
  163. $new = $RIFFS{$riff}->{'name'};
  164. }
  165. my $old = $new;
  166. if ($riffLast > 0) {
  167. $old = $RIFFS{$riffLast}->{'name'};
  168. }
  169. if ($DEBUG) {
  170. print STDERR 'New RIFF: ' . $old . ' => ' . $new . "\n";
  171. }
  172. my ($fh, $tmp) = tempfile($OUTPUT_FILE . '.XXXXXXXX', 'UNLINK' => 0);
  173. print $fh $new . "\n";
  174. close($fh);
  175. rename($tmp, $OUTPUT_FILE);
  176. }
  177. # Sync
  178. if ($riff) {
  179. if ($DEBUG) {
  180. print STDERR "Syncing\n";
  181. }
  182. # Play/pause to match the video
  183. if ($stateLast ne $state) {
  184. if ($state eq 'PAUSE') {
  185. Audio::pause('RIFF');
  186. } elsif ($state eq 'PLAY') {
  187. Audio::background('RIFF');
  188. }
  189. }
  190. # Get the video and riff playback positions
  191. my $rate = Audio::rate('RIFF', undef());
  192. my $riffTime = Audio::position('RIFF', undef());
  193. my $videoTime = $exists{'PLAYING_POSITION'};
  194. # Convert to seconds
  195. my @parts = split(/\:/, $videoTime);
  196. $videoTime = 0;
  197. if (scalar(@parts) == 3) {
  198. $videoTime = ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];
  199. } elsif (scalar(@parts) == 2) {
  200. $videoTime = ($parts[0] * 60) + $parts[1];
  201. } else {
  202. $videoTime = $parts[0];
  203. }
  204. # Calculate the adjusted riff time and the error between the riff and video times
  205. my $riffAdjTime = ($riffTime * $RIFFS{$riff}->{'rate'}) - $RIFFS{$riff}->{'offset'} + $nudge;
  206. my $error = $videoTime - $riffAdjTime;
  207. my $errorAbs = abs($error);
  208. # Debug
  209. if ($DEBUG) {
  210. print STDERR "\tRate: " . $RIFFS{$riff}->{'rate'} . "\n";
  211. print STDERR "\tAdjusted Rate: " . $rate . "\n";
  212. print STDERR "\tNudge: " . $nudge . "\n";
  213. print STDERR "\tOffset: " . $RIFFS{$riff}->{'offset'} . "\n";
  214. print STDERR "\tRiff time: " . $riffTime . "\n";
  215. print STDERR "\tVideo time: " . $videoTime . "\n";
  216. print STDERR "\tAdjusted riff time: " . $riffAdjTime . "\n";
  217. print STDERR "\tError: " . $error . "\n";
  218. }
  219. # Adjust the riff position if we're off by 0.5 seconds or more
  220. if ($errorAbs > 0.5) {
  221. # Calculate the new position, including an ACTION_DELAY adjustment to compensate for time elapsed in this process
  222. my $newPos = $riffTime + $error + $ACTION_DELAY;
  223. if ($newPos < 0) {
  224. Audio::pause('RIFF');
  225. } else {
  226. # See if we're playing
  227. my $playing = Audio::playing('RIFF');
  228. # Jump if we're off by more than a few seconds
  229. if ($errorAbs > $JUMP_THRESHOLD) {
  230. if ($DEBUG) {
  231. print STDERR 'Jumping to: ' . $newPos . "\n";
  232. }
  233. Audio::position('RIFF', $newPos);
  234. $nudge = 0;
  235. $error = 0;
  236. $errorAbs = 0;
  237. }
  238. # Set the rate when we adjust, unless we're paused
  239. if ($playing) {
  240. my $rateDiff = $errorAbs / $JUMP_THRESHOLD;
  241. if ($error < 0) {
  242. $rateDiff *= -1;
  243. }
  244. my $newRate = $RIFFS{$riff}->{'rate'} + $rateDiff;
  245. if ($DEBUG) {
  246. print STDERR 'Setting rate to: ' . $newRate . "\n";
  247. }
  248. Audio::rate('RIFF', $newRate);
  249. }
  250. # Play/pause as needed, before we adjust
  251. # The state-change detection should handle most of this
  252. # But double-check while adjusting in case things get out-of-sync
  253. if (exists($exists{'PLAYING'})) {
  254. if ($exists{'PLAYING'} && !$playing) {
  255. Audio::background('RIFF');
  256. } elsif (!$exists{'PLAYING'} && $playing) {
  257. Audio::pause('RIFF');
  258. }
  259. }
  260. }
  261. } else {
  262. # Reset the rate to standard if we're inside sync the window
  263. if ($rate != $RIFFS{$riff}->{'rate'}) {
  264. Audio::rate('RIFF', $RIFFS{$riff}->{'rate'});
  265. }
  266. }
  267. }
  268. }