rifftrax.pl 8.0 KB

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