rifftrax.pl 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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::drop('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::addLoad('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 > 0) {
  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
  175. # This assumes our local state is valid. We double-check that state tracking if the sync error is large enough to trigger a jump
  176. if ($riff) {
  177. if ($state eq 'PAUSE' && $playing) {
  178. pauseRiff();
  179. } elsif ($state eq 'PLAY' && !$playing) {
  180. playRiff();
  181. }
  182. }
  183. # Sync at most once per second
  184. if ($riff && $lastSync < time()) {
  185. if ($DEBUG) {
  186. print STDERR "Syncing\n";
  187. }
  188. $lastSync = time();
  189. # Get the video and riff playback positions
  190. my $rate = getRiffRate();
  191. my $riffTime = Audio::position('RIFF', undef());
  192. my $videoTime = $exists{'PLAYING_POSITION'};
  193. # Update our local playing state tracker
  194. # The rate is always 0 when paused (Audio::playing uses this same methodology)
  195. if ($rate > 0) {
  196. $playing = 1;
  197. } else {
  198. $playing = 0;
  199. }
  200. # Convert the timestamp to seconds
  201. my @parts = split(/\:/, $videoTime);
  202. $videoTime = 0;
  203. if (scalar(@parts) == 3) {
  204. $videoTime = ($parts[0] * 3600) + ($parts[1] * 60) + $parts[2];
  205. } elsif (scalar(@parts) == 2) {
  206. $videoTime = ($parts[0] * 60) + $parts[1];
  207. } else {
  208. $videoTime = $parts[0];
  209. }
  210. # Calculate the adjusted riff time and the error between the riff and video times
  211. my $riffAdjTime = $riffTime - $RIFFS{$riff}->{'offset'};
  212. my $error = $videoTime - $riffAdjTime;
  213. my $errorAbs = abs($error);
  214. # Debug
  215. if ($DEBUG) {
  216. print STDERR "\tRate: " . $rate . "\n";
  217. print STDERR "\tOffset: " . $RIFFS{$riff}->{'offset'} . "\n";
  218. print STDERR "\tRiff time: " . $riffTime . "\n";
  219. print STDERR "\tVideo time: " . $videoTime . "\n";
  220. print STDERR "\tAdjusted riff time: " . $riffAdjTime . "\n";
  221. print STDERR "\tError: " . $error . "\n";
  222. }
  223. # Adjust the riff position if we're off by 0.5 seconds or more
  224. if ($errorAbs > 0.5) {
  225. # Calculate the new position, including an ACTION_DELAY adjustment to compensate for time elapsed in this process
  226. my $newPos = $riffTime + $error + $ACTION_DELAY;
  227. if ($newPos < 0) {
  228. pauseRiff();
  229. } else {
  230. # Jump if we're off by more than a few seconds
  231. if ($errorAbs > $JUMP_THRESHOLD) {
  232. if ($DEBUG) {
  233. print STDERR 'Jumping to: ' . $newPos . "\n";
  234. }
  235. Audio::position('RIFF', $newPos);
  236. $error = 0;
  237. $errorAbs = 0;
  238. }
  239. # Set the rate when we adjust, unless we're paused
  240. if ($playing) {
  241. my $rateDiff = $errorAbs / $JUMP_THRESHOLD;
  242. my $newRate = 1.0;
  243. if ($error < 0) {
  244. $newRate -= $rateDiff;
  245. } else {
  246. $newRate += $rateDiff;
  247. }
  248. if ($DEBUG) {
  249. print STDERR 'Setting rate to: ' . $newRate . "\n";
  250. }
  251. setRiffRate($newRate);
  252. }
  253. # Play/pause as needed, before we adjust
  254. # The state-change detection should handle most of this
  255. # But double-check while adjusting in case things get out-of-sync
  256. if (exists($exists{'PLAYING'})) {
  257. if ($exists{'PLAYING'} && !$playing) {
  258. playRiff();
  259. } elsif (!$exists{'PLAYING'} && $playing) {
  260. pauseRiff();
  261. }
  262. }
  263. }
  264. } else {
  265. # Reset the rate to standard if we're inside sync the window
  266. if ($rate != 1.0) {
  267. setRiffRate(1.0);
  268. }
  269. }
  270. }
  271. }
  272. sub playRiff() {
  273. if ($DEBUG) {
  274. print STDERR "playRiff()\n";
  275. }
  276. $playing = 1;
  277. Audio::background('RIFF');
  278. }
  279. sub pauseRiff() {
  280. if ($DEBUG) {
  281. print STDERR "pauseRiff()\n";
  282. }
  283. $playing = 0;
  284. Audio::pause('RIFF');
  285. }
  286. sub getRiffRate() {
  287. if ($DEBUG) {
  288. print STDERR "getRiffRate()\n";
  289. }
  290. my $rate = 0;
  291. if ($playing) {
  292. $rate = Audio::rate('RIFF', undef());
  293. }
  294. return $rate;
  295. }
  296. sub setRiffRate($) {
  297. my ($rate) = @_;
  298. if ($DEBUG) {
  299. print STDERR 'setRiffRate(): ' . $rate . "\n";
  300. }
  301. if ($playing) {
  302. Audio::rate('RIFF', $rate);
  303. }
  304. }
  305. sub parseConfig($$) {
  306. my ($conf_path, $riffs) = @_;
  307. if ($DEBUG) {
  308. print STDERR "parseConfig()\n";
  309. }
  310. opendir(CONF, $conf_path)
  311. or die('Unable to open config directory: ' . $! . "\n");
  312. foreach my $file (readdir(CONF)) {
  313. # Skip silly files
  314. if ($file =~ /^\._/) {
  315. next;
  316. }
  317. if ($file =~ /\.riff$/) {
  318. my $path = $conf_path . '/' . $file;
  319. # Slurp the contents
  320. my $text = '';
  321. if (!open(my $fh, $path)) {
  322. warn('Unable to open ' . $path . "\n");
  323. next;
  324. } else {
  325. local $/;
  326. $text = <$fh>;
  327. close($fh);
  328. }
  329. # Parse out the data we care about
  330. my %data = ();
  331. if ($text =~ /^\s*Name:\s*(\S.*\S)\s*$/mi) {
  332. $data{'name'} = $1;
  333. }
  334. if ($text =~ /^\s*Year:\s*(\d{4})\s*$/mi) {
  335. $data{'year'} = $1;
  336. }
  337. if ($text =~ /^\s*File:\s*(\S.*\S)\s*$/mi) {
  338. $data{'file'} = $1;
  339. }
  340. if ($text =~ /^\s*Offset:\s*([\-\+]?\d+(?:\.\d+)?)\s*$/mi) {
  341. $data{'offset'} = $1;
  342. }
  343. # Ensure we have a valid record
  344. if (!$data{'name'}) {
  345. warn('Invalid riff file: ' . $file . "\n");
  346. next;
  347. }
  348. # Try to find a related file
  349. if (!$data{'file'}) {
  350. $data{'file'} = $file;
  351. $data{'file'} =~ s/\.riff$/\.mp3/i;
  352. $data{'file'} = $conf_path . '/' . $data{'file'};
  353. }
  354. # Ensure the path is valid
  355. if (!-r $data{'file'}) {
  356. warn('Invalid MP3 file in riff ' . $file . ' => ' . $data{'file'} . "\n");
  357. next;
  358. }
  359. # Debug
  360. if ($DEBUG) {
  361. print STDERR 'Added RiffTrax: ' . $data{'name'} . "\n\tFile: " . $data{'file'} . "\n\tOffset: " . $data{'offset'} . "\n";
  362. }
  363. # Push the data up the chain
  364. $riffs->{ $data{'name'} } = \%data;
  365. }
  366. }
  367. closedir(CONF);
  368. # Record the last update time
  369. $riffs->{'_LAST_CONFIG_UPDATE'} = time();
  370. }