rave.pl 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use POSIX;
  5. use File::Touch;
  6. use File::Basename;
  7. use Time::HiRes qw( usleep sleep time );
  8. use IPC::System::Simple qw( system capture );
  9. # Local modules
  10. use Cwd qw(abs_path);
  11. use File::Basename qw(dirname);
  12. use lib dirname(abs_path($0));
  13. use DMX;
  14. # Effect Prototypes
  15. sub red_alert($$);
  16. sub rave_init($$);
  17. sub lsr_loop();
  18. # User config
  19. my $MEDIA_PATH = `~/bin/video/mediaPath`;
  20. my $SILENCE = $MEDIA_PATH . '/DMX/Silence.wav';
  21. my @CHANNELS = (1, 2, 4, 5, 6, 7, 8, 9, 13, 14, 15);
  22. my %EFFECTS = (
  23. 'RED_ALERT' => { 'cmd' => \&red_alert },
  24. 'LSR' => { 'cmd' => \&rave_init, 'file' => $MEDIA_PATH . '/DMX/Rave.mp3', 'next' => \&lsr_loop },
  25. );
  26. # Utility prototypes
  27. sub loadAudio($);
  28. sub playAudio($);
  29. sub closeAudio($);
  30. sub stopAudio();
  31. sub playOnce($);
  32. # App config
  33. my $DATA_DIR = DMX::dataDir();
  34. my $OUTPUT_FILE = $DATA_DIR . 'RAVE_CMD';
  35. my $STATE_SOCK = $OUTPUT_FILE . '.socket';
  36. my $RAVE_FILE = $DATA_DIR . 'RAVE';
  37. my $EFFECT_FILE = $DATA_DIR . 'EFFECT';
  38. my $PUSH_TIMEOUT = 20;
  39. my $PULL_TIMEOUT = $PUSH_TIMEOUT * 3;
  40. my $DELAY = $PULL_TIMEOUT / 2;
  41. # Debug
  42. my $DEBUG = 0;
  43. if ($ENV{'DEBUG'}) {
  44. $DEBUG = 1;
  45. }
  46. # Sockets
  47. DMX::stateSocket($STATE_SOCK);
  48. DMX::stateSubscribe($STATE_SOCK);
  49. # State
  50. my %exists = ();
  51. my $pullLast = time();
  52. my $update = 0;
  53. my $PID = undef();
  54. my $EFFECT = undef();
  55. my $PID_DATA = undef();
  56. # Always clear the RAVE and EFFECT files
  57. if (-e $RAVE_FILE) {
  58. unlink($RAVE_FILE);
  59. }
  60. if (-e $EFFECT_FILE) {
  61. unlink($EFFECT_FILE);
  62. }
  63. # Loop forever
  64. while (1) {
  65. # State is transient during a RAVE
  66. my $newState = 'OFF';
  67. # Reduce the select delay when we're processing background effects
  68. # We don't want to hang waiting for event updates while we're running the show
  69. my $delay = $DELAY;
  70. if (defined($PID)) {
  71. $delay = 0.001;
  72. }
  73. # Wait for state updates
  74. {
  75. my %existsTmp = ();
  76. my $cmdState = DMX::readState($delay, \%existsTmp, undef(), undef());
  77. if (defined($cmdState)) {
  78. $newState = $cmdState;
  79. $pullLast = time();
  80. }
  81. # Only record valid exists hashes
  82. if (scalar(keys(%existsTmp)) > 0) {
  83. %exists = %existsTmp;
  84. }
  85. }
  86. # Die if we don't see regular updates
  87. if (time() - $pullLast > $PULL_TIMEOUT) {
  88. die('No update on state socket in past ' . $PULL_TIMEOUT . " seconds. Exiting...\n");
  89. }
  90. # Handle "STOP" commands
  91. if ($newState eq 'STOP') {
  92. if (defined($PID)) {
  93. if ($DEBUG) {
  94. print STDERR "Ending background processing\n";
  95. }
  96. stopAudio();
  97. kill(SIGTERM, $PID);
  98. }
  99. $update = 1;
  100. }
  101. # Reap zombie children
  102. if (defined($PID)) {
  103. my $kid = waitpid($PID, WNOHANG);
  104. if ($kid > 0) {
  105. if ($DEBUG) {
  106. print STDERR 'Reaped child: ' . $PID . "\n";
  107. }
  108. # Forget our local bypass state
  109. $PID = undef();
  110. $EFFECT = undef();
  111. $PID_DATA = undef();
  112. # Clear the RAVE and EFFECT flags
  113. if (-e $RAVE_FILE) {
  114. unlink($RAVE_FILE);
  115. }
  116. if (-e $EFFECT_FILE) {
  117. unlink($EFFECT_FILE);
  118. }
  119. }
  120. }
  121. # Continue special processing
  122. if (defined($EFFECT)) {
  123. $EFFECT->();
  124. next;
  125. }
  126. # Handle effects by name
  127. if (defined($EFFECTS{$newState})) {
  128. # Initiate the EFFECT state
  129. touch($EFFECT_FILE);
  130. # Dispatch the effect
  131. $EFFECTS{$newState}{'cmd'}(\%exists, $EFFECTS{$newState});
  132. # Clear the EFFECT state if there is no background process
  133. if (!defined($PID)) {
  134. if (-e $EFFECT_FILE) {
  135. unlink($EFFECT_FILE);
  136. }
  137. }
  138. next;
  139. }
  140. # Clear the RAVE and EFFECT flags, just in case
  141. if (-e $RAVE_FILE) {
  142. unlink($RAVE_FILE);
  143. die("Unexpected RAVE file\n");
  144. }
  145. if (-e $EFFECT_FILE) {
  146. unlink($EFFECT_FILE);
  147. die("Unexpected EFFECT file\n");
  148. }
  149. }
  150. # ======================================
  151. # Utility routines
  152. # ======================================
  153. sub runApplescript($) {
  154. my ($script) = @_;
  155. if ($DEBUG) {
  156. print STDERR 'Running AppleScript: ' . $script . "\n";
  157. }
  158. my $retval = capture('osascript', '-e', $script);
  159. if ($DEBUG) {
  160. print STDERR "\tAppleScript result: " . $retval . "\n";
  161. }
  162. return $retval;
  163. }
  164. sub loadAudio($) {
  165. my ($file) = @_;
  166. if ($DEBUG) {
  167. print STDERR 'Opening QT file: ' . $file . "\n";
  168. }
  169. # Cleanup, to ensure "document 1" is what we want
  170. stopAudio();
  171. # Open with open, requesting QT as the app
  172. system('open', '-a', 'QuickTime Player', $file);
  173. # Get the document name
  174. my @cmd = ('repeat while application "QuickTime Player" is not running');
  175. push(@cmd, 'delay 0.05');
  176. push(@cmd, 'end repeat');
  177. push(@cmd, 'tell application "QuickTime Player"');
  178. push(@cmd, 'repeat while (count items of every document) < 1');
  179. push(@cmd, 'delay 0.05');
  180. push(@cmd, 'end repeat');
  181. push(@cmd, 'get document 1');
  182. push(@cmd, 'end tell');
  183. my $doc = runApplescript(join("\n", @cmd));
  184. # Put Plex back in front
  185. runApplescript('tell application "Plex" to activate');
  186. # Clean up and return the document name for later use
  187. $doc =~ s/^\s*document //;
  188. $doc =~ s/\s+$//;
  189. $doc =~ s/\"/\\\"/g;
  190. $doc = '"' . $doc . '"';
  191. return $doc;
  192. }
  193. sub playAudio($) {
  194. my ($doc) = @_;
  195. if ($DEBUG) {
  196. print STDERR 'Playing QT document: ' . $doc . "\n";
  197. }
  198. my @cmd = ('tell application "QuickTime Player"');
  199. push(@cmd, 'play document ' . $doc);
  200. push(@cmd, 'repeat while playing of document ' . $doc . ' = true');
  201. push(@cmd, 'delay 0.05');
  202. push(@cmd, 'end repeat');
  203. push(@cmd, 'end tell');
  204. runApplescript(join("\n", @cmd));
  205. }
  206. sub closeAudio($) {
  207. my ($doc) = @_;
  208. if ($DEBUG) {
  209. print STDERR 'Closing QT document: ' . $doc . "\n";
  210. }
  211. runApplescript('tell application "QuickTime Player" to close document ' . $doc);
  212. runApplescript('tell application "Plex" to activate');
  213. }
  214. sub stopAudio() {
  215. if ($DEBUG) {
  216. print STDERR "Stopping all QT audio\n";
  217. }
  218. runApplescript('tell application "QuickTime Player" to close every document');
  219. runApplescript('tell application "Plex" to activate');
  220. }
  221. sub playOnce($) {
  222. my ($file) = @_;
  223. my $doc = loadAudio($file);
  224. playAudio($doc);
  225. closeAudio($doc);
  226. }
  227. # ======================================
  228. # Effects routines
  229. # ======================================
  230. sub red_alert($$) {
  231. my ($exists, $effect) = @_;
  232. if ($DEBUG) {
  233. print STDERR "red_alert()\n";
  234. }
  235. my $file = $MEDIA_PATH . '/DMX/Red Alert.mp3';
  236. my $ramp = 450;
  237. my $sleep = $ramp;
  238. # Pre-load the audio file for better timing
  239. my $audio = loadAudio($file);
  240. # Bring the B & G channels down to 0
  241. my @other = ();
  242. push(@other, { 'channel' => 13, 'value' => 0, 'time' => 0 });
  243. push(@other, { 'channel' => 15, 'value' => 0, 'time' => 0 });
  244. foreach my $data (@other) {
  245. DMX::dim($data);
  246. }
  247. # Set the high/low values for the ramp
  248. my %high = ('channel' => 14, 'value' => 255, 'time' => $ramp);
  249. my %low = %high;
  250. $low{'value'} = 64;
  251. # Three blasts
  252. for (my $i = 0 ; $i < 3 ; $i++) {
  253. DMX::dim(\%high);
  254. playAudio($audio);
  255. DMX::dim(\%low);
  256. usleep($sleep * 1000);
  257. }
  258. # Close the audio file
  259. closeAudio($audio);
  260. # Follow through on the loop
  261. return 0;
  262. }
  263. sub rave_init($$) {
  264. my ($exists, $effect) = @_;
  265. if ($DEBUG) {
  266. print STDERR "rave_init()\n";
  267. }
  268. if (!defined($effect->{'file'}) || !-r $effect->{'file'}) {
  269. die('Invalid RAVE audio file: ' . $effect->{'file'} . "\n");
  270. }
  271. # Config
  272. my $SIL_DELAY = 1.3;
  273. my $AMP_SHORT = 5;
  274. my $AMP_LONG = $AMP_SHORT + 5;
  275. # Initiate the RAVE state
  276. touch($RAVE_FILE);
  277. # Setup our loop handler
  278. if ($effect->{'next'}) {
  279. $EFFECT = $effect->{'next'};
  280. }
  281. # Save data for future runs
  282. my %data = ();
  283. $PID_DATA = \%data;
  284. # Initialize the channels hash
  285. my %chans = ();
  286. foreach my $chan (@CHANNELS) {
  287. $chans{$chan} = 0;
  288. }
  289. $data{'channels'} = \%chans;
  290. $data{'num_channels'} = scalar(keys(%chans));
  291. $data{'live_channels'} = 0;
  292. # Reduce the amp delay if the amp is already on
  293. my $amp_wait = $AMP_LONG;
  294. if ($exists->{'AMPLIFIER'}) {
  295. $amp_wait = $AMP_SHORT;
  296. }
  297. # Dim while we wait
  298. my @data_set = ();
  299. foreach my $chan (@CHANNELS) {
  300. push(@data_set, { 'channel' => $chan, 'value' => 0, 'time' => $amp_wait / 2 * 1000 });
  301. }
  302. DMX::applyDataset(\@data_set, 'RAVE', $OUTPUT_FILE);
  303. # Wait for the amp to power up
  304. if ($DEBUG) {
  305. print STDERR 'Waiting ' . $amp_wait . " seconds for the amp to boot\n";
  306. }
  307. sleep($amp_wait - $SIL_DELAY);
  308. # Play a short burst of silence to get all the audio in-sync
  309. playOnce($SILENCE);
  310. # Pre-load the audio file for better timing
  311. my $audio = loadAudio($effect->{'file'});
  312. # Play the sound in a child (i.e. in the background)
  313. $PID = fork();
  314. if (defined($PID) && $PID == 0) {
  315. playAudio($audio);
  316. closeAudio($audio);
  317. exit(0);
  318. }
  319. # Record our start time
  320. $data{'start'} = Time::HiRes::time();
  321. # Do not pass GO, do not collect $200
  322. return 1;
  323. }
  324. sub lsr_loop() {
  325. if ($DEBUG) {
  326. print STDERR "lsr_loop()\n";
  327. }
  328. # Config
  329. my $max_dur = 375;
  330. my $max_val = 255;
  331. my $reserve = 0.75;
  332. my $ramp_dur = 10.20;
  333. my $hit_pos = 43.15;
  334. my $hit_dur = 100;
  335. my $fade_pos = 43.65;
  336. my $fade_dur = 2000;
  337. # How long have we been playing
  338. my $elapsed = Time::HiRes::time() - $PID_DATA->{'start'};
  339. if ($DEBUG) {
  340. print STDERR 'Elapsed: ' . $elapsed . "\n";
  341. }
  342. # Ramp up the number of channels in our effect
  343. if ($elapsed < $ramp_dur) {
  344. my $ratio = $PID_DATA->{'live_channels'} / ($PID_DATA->{'num_channels'} * (1 - $reserve));
  345. if ($PID_DATA->{'live_channels'} < 1 || $ratio < $elapsed / $ramp_dur) {
  346. my @keys = keys(%{ $PID_DATA->{'channels'} });
  347. my $index = int(rand($PID_DATA->{'num_channels'}));
  348. while ($PID_DATA->{'channels'}->{ $keys[$index] } > 0) {
  349. $index = int(rand($PID_DATA->{'num_channels'}));
  350. }
  351. $PID_DATA->{'channels'}->{ $keys[$index] } = 1;
  352. $PID_DATA->{'live_channels'}++;
  353. }
  354. } else {
  355. if ($PID_DATA->{'live_channels'} < $PID_DATA->{'num_channels'}) {
  356. foreach my $chan (keys(%{ $PID_DATA->{'channels'} })) {
  357. $PID_DATA->{'channels'}->{$chan} = 1;
  358. }
  359. $PID_DATA->{'live_channels'} = $PID_DATA->{'num_channels'};
  360. }
  361. }
  362. # Prepare data for each channel
  363. my @data_set = ();
  364. my $wait = $max_dur;
  365. foreach my $chan (keys(%{ $PID_DATA->{'channels'} })) {
  366. my $val = 0;
  367. my $dur = 0;
  368. # Random data on enabled channels until the fade
  369. if ($elapsed < $hit_pos) {
  370. if ($PID_DATA->{'channels'}->{$chan} > 0) {
  371. $dur = int(rand($max_dur));
  372. $val = int(rand($max_val));
  373. }
  374. } elsif ($elapsed < $fade_pos) {
  375. $val = $max_val;
  376. $dur = $hit_dur;
  377. $wait = ($fade_pos - $hit_pos) * 1000;
  378. } else {
  379. $val = 0;
  380. $dur = $fade_dur;
  381. $wait = $dur;
  382. }
  383. push(@data_set, { 'channel' => $chan, 'value' => $val, 'time' => $dur });
  384. }
  385. # Push the data set
  386. DMX::applyDataset(\@data_set, 'RAVE', $OUTPUT_FILE);
  387. # Wait for the fade interval
  388. usleep($wait * 1000);
  389. }