rifftrax.pl 9.3 KB

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