rave.pl 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 = ('tell application "QuickTime Player"');
  175. push(@cmd, 'repeat while (count items of every document) < 1');
  176. push(@cmd, 'delay 0.05');
  177. push(@cmd, 'end repeat');
  178. push(@cmd, 'get document 1');
  179. push(@cmd, 'end tell');
  180. my $doc = runApplescript(join("\n", @cmd));
  181. # Put Plex back in front
  182. runApplescript('tell application "Plex" to activate');
  183. # Clean up and return the document name for later use
  184. $doc =~ s/^\s*document //;
  185. $doc =~ s/\s+$//;
  186. $doc =~ s/\"/\\\"/g;
  187. $doc = '"' . $doc . '"';
  188. return $doc;
  189. }
  190. sub playAudio($) {
  191. my ($doc) = @_;
  192. if ($DEBUG) {
  193. print STDERR 'Playing QT document: ' . $doc . "\n";
  194. }
  195. my @cmd = ('tell application "QuickTime Player"');
  196. push(@cmd, 'play document ' . $doc);
  197. push(@cmd, 'repeat while playing of document ' . $doc . ' = true');
  198. push(@cmd, 'delay 0.05');
  199. push(@cmd, 'end repeat');
  200. push(@cmd, 'end tell');
  201. runApplescript(join("\n", @cmd));
  202. }
  203. sub closeAudio($) {
  204. my ($doc) = @_;
  205. if ($DEBUG) {
  206. print STDERR 'Closing QT document: ' . $doc . "\n";
  207. }
  208. runApplescript('tell application "QuickTime Player" to close document ' . $doc);
  209. runApplescript('tell application "Plex" to activate');
  210. }
  211. sub stopAudio() {
  212. if ($DEBUG) {
  213. print STDERR "Stopping all QT audio\n";
  214. }
  215. runApplescript('tell application "QuickTime Player" to close every document');
  216. runApplescript('tell application "Plex" to activate');
  217. }
  218. sub playOnce($) {
  219. my ($file) = @_;
  220. my $doc = loadAudio($file);
  221. playAudio($doc);
  222. closeAudio($doc);
  223. }
  224. # ======================================
  225. # Effects routines
  226. # ======================================
  227. sub red_alert($$) {
  228. my ($exists, $effect) = @_;
  229. if ($DEBUG) {
  230. print STDERR "red_alert()\n";
  231. }
  232. my $file = $MEDIA_PATH . '/DMX/Red Alert.mp3';
  233. my $ramp = 450;
  234. my $sleep = $ramp;
  235. # Pre-load the audio file for better timing
  236. my $audio = loadAudio($file);
  237. # Bring the B & G channels down to 0
  238. my @other = ();
  239. push(@other, { 'channel' => 13, 'value' => 0, 'time' => 0 });
  240. push(@other, { 'channel' => 15, 'value' => 0, 'time' => 0 });
  241. foreach my $data (@other) {
  242. DMX::dim($data);
  243. }
  244. # Set the high/low values for the ramp
  245. my %high = ('channel' => 14, 'value' => 255, 'time' => $ramp);
  246. my %low = %high;
  247. $low{'value'} = 64;
  248. # Three blasts
  249. for (my $i = 0 ; $i < 3 ; $i++) {
  250. DMX::dim(\%high);
  251. playAudio($audio);
  252. DMX::dim(\%low);
  253. usleep($sleep * 1000);
  254. }
  255. # Close the audio file
  256. closeAudio($audio);
  257. # Follow through on the loop
  258. return 0;
  259. }
  260. sub rave_init($$) {
  261. my ($exists, $effect) = @_;
  262. if ($DEBUG) {
  263. print STDERR "rave_init()\n";
  264. }
  265. if (!defined($effect->{'file'}) || !-r $effect->{'file'}) {
  266. die('Invalid RAVE audio file: ' . $effect->{'file'} . "\n");
  267. }
  268. # Config
  269. my $SIL_DELAY = 1.3;
  270. my $AMP_SHORT = 5;
  271. my $AMP_LONG = $AMP_SHORT + 5;
  272. # Initiate the RAVE state
  273. touch($RAVE_FILE);
  274. # Setup our loop handler
  275. if ($effect->{'next'}) {
  276. $EFFECT = $effect->{'next'};
  277. }
  278. # Save data for future runs
  279. my %data = ();
  280. $PID_DATA = \%data;
  281. # Initialize the channels hash
  282. my %chans = ();
  283. foreach my $chan (@CHANNELS) {
  284. $chans{$chan} = 0;
  285. }
  286. $data{'channels'} = \%chans;
  287. $data{'num_channels'} = scalar(keys(%chans));
  288. $data{'live_channels'} = 0;
  289. # Reduce the amp delay if the amp is already on
  290. my $amp_wait = $AMP_LONG;
  291. if ($exists->{'AMPLIFIER'}) {
  292. $amp_wait = $AMP_SHORT;
  293. }
  294. # Dim while we wait
  295. my @data_set = ();
  296. foreach my $chan (@CHANNELS) {
  297. push(@data_set, { 'channel' => $chan, 'value' => 0, 'time' => $amp_wait / 2 * 1000 });
  298. }
  299. DMX::applyDataset(\@data_set, 'RAVE', $OUTPUT_FILE);
  300. # Wait for the amp to power up
  301. if ($DEBUG) {
  302. print STDERR 'Waiting ' . $amp_wait . " seconds for the amp to boot\n";
  303. }
  304. sleep($amp_wait - $SIL_DELAY);
  305. # Play a short burst of silence to get all the audio in-sync
  306. playOnce($SILENCE);
  307. # Pre-load the audio file for better timing
  308. my $audio = loadAudio($effect->{'file'});
  309. # Play the sound in a child (i.e. in the background)
  310. $PID = fork();
  311. if (defined($PID) && $PID == 0) {
  312. playAudio($audio);
  313. closeAudio($audio);
  314. exit(0);
  315. }
  316. # Record our start time
  317. $data{'start'} = Time::HiRes::time();
  318. # Do not pass GO, do not collect $200
  319. return 1;
  320. }
  321. sub lsr_loop() {
  322. if ($DEBUG) {
  323. print STDERR "lsr_loop()\n";
  324. }
  325. # Config
  326. my $max_dur = 375;
  327. my $max_val = 255;
  328. my $reserve = 0.75;
  329. my $ramp_dur = 10.20;
  330. my $hit_pos = 43.15;
  331. my $hit_dur = 100;
  332. my $fade_pos = 43.65;
  333. my $fade_dur = 2000;
  334. # How long have we been playing
  335. my $elapsed = Time::HiRes::time() - $PID_DATA->{'start'};
  336. if ($DEBUG) {
  337. print STDERR 'Elapsed: ' . $elapsed . "\n";
  338. }
  339. # Ramp up the number of channels in our effect
  340. if ($elapsed < $ramp_dur) {
  341. my $ratio = $PID_DATA->{'live_channels'} / ($PID_DATA->{'num_channels'} * (1 - $reserve));
  342. if ($PID_DATA->{'live_channels'} < 1 || $ratio < $elapsed / $ramp_dur) {
  343. my @keys = keys(%{ $PID_DATA->{'channels'} });
  344. my $index = int(rand($PID_DATA->{'num_channels'}));
  345. while ($PID_DATA->{'channels'}->{ $keys[$index] } > 0) {
  346. $index = int(rand($PID_DATA->{'num_channels'}));
  347. }
  348. $PID_DATA->{'channels'}->{ $keys[$index] } = 1;
  349. $PID_DATA->{'live_channels'}++;
  350. }
  351. } else {
  352. if ($PID_DATA->{'live_channels'} < $PID_DATA->{'num_channels'}) {
  353. foreach my $chan (keys(%{ $PID_DATA->{'channels'} })) {
  354. $PID_DATA->{'channels'}->{$chan} = 1;
  355. }
  356. $PID_DATA->{'live_channels'} = $PID_DATA->{'num_channels'};
  357. }
  358. }
  359. # Prepare data for each channel
  360. my @data_set = ();
  361. my $wait = $max_dur;
  362. foreach my $chan (keys(%{ $PID_DATA->{'channels'} })) {
  363. my $val = 0;
  364. my $dur = 0;
  365. # Random data on enabled channels until the fade
  366. if ($elapsed < $hit_pos) {
  367. if ($PID_DATA->{'channels'}->{$chan} > 0) {
  368. $dur = int(rand($max_dur));
  369. $val = int(rand($max_val));
  370. }
  371. } elsif ($elapsed < $fade_pos) {
  372. $val = $max_val;
  373. $dur = $hit_dur;
  374. $wait = ($fade_pos - $hit_pos) * 1000;
  375. } else {
  376. $val = 0;
  377. $dur = $fade_dur;
  378. $wait = $dur;
  379. }
  380. push(@data_set, { 'channel' => $chan, 'value' => $val, 'time' => $dur });
  381. }
  382. # Push the data set
  383. DMX::applyDataset(\@data_set, 'RAVE', $OUTPUT_FILE);
  384. # Wait for the fade interval
  385. usleep($wait * 1000);
  386. }