rifftrax.pl 10 KB

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