rifftrax.pl 9.6 KB

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