rifftrax.pl 9.6 KB

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