chiark / gitweb /
issue #22 was fixed ages ago (revno 905, 914 mainly)
[disorder] / server / play.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2009 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file server/play.c
19  * @brief Playing tracks
20  *
21  * This file is rather badly organized.  Sorry.  It's better than it was...
22  */
23
24 #include "disorder-server.h"
25 #include <ao/ao.h>
26
27 #define SPEAKER "disorder-speaker"
28
29 /** @brief The current playing track or NULL */
30 struct queue_entry *playing;
31
32 /** @brief Set when paused */
33 int paused;
34
35 static void finished(ev_source *ev);
36 static int start_child(struct queue_entry *q, 
37                        const struct pbgc_params *params,
38                        void attribute((unused)) *bgdata);
39 static int prepare_child(struct queue_entry *q, 
40                          const struct pbgc_params *params,
41                          void attribute((unused)) *bgdata);
42 static void ensure_next_scratch(ev_source *ev);
43
44 /** @brief File descriptor of our end of the socket to the speaker */
45 static int speaker_fd = -1;
46
47 /** @brief Set when shutting down */
48 static int shutting_down;
49
50 /* Speaker ------------------------------------------------------------------ */
51
52 /** @brief Called when speaker process terminates
53  *
54  * Currently kills of DisOrder completely.  A future version could terminate
55  * the speaker when nothing was going on, or recover from failures, though any
56  * tracks with decoders already started would need to have them restarted.
57  */
58 static int speaker_terminated(ev_source attribute((unused)) *ev,
59                               pid_t attribute((unused)) pid,
60                               int attribute((unused)) status,
61                               const struct rusage attribute((unused)) *rusage,
62                               void attribute((unused)) *u) {
63   disorder_fatal(0, "speaker subprocess %s", wstat(status));
64 }
65
66 /** @brief Called when we get a message from the speaker process */
67 static int speaker_readable(ev_source *ev, int fd,
68                             void attribute((unused)) *u) {
69   struct speaker_message sm;
70   int ret = speaker_recv(fd, &sm);
71   
72   if(ret < 0) return 0;                 /* EAGAIN */
73   if(!ret) {                            /* EOF */
74     ev_fd_cancel(ev, ev_read, fd);
75     return 0;
76   }
77   switch(sm.type) {
78   case SM_PAUSED:
79     /* track ID is paused, DATA seconds played */
80     D(("SM_PAUSED %s %ld", sm.id, sm.data));
81     playing->sofar = sm.data;
82     break;
83   case SM_FINISHED:                     /* scratched the playing track */
84   case SM_STILLBORN:                    /* scratched too early */
85   case SM_UNKNOWN:                      /* scratched WAY too early */
86     if(playing && !strcmp(sm.id, playing->id))
87       finished(ev);
88     break;
89   case SM_PLAYING:
90     /* track ID is playing, DATA seconds played */
91     D(("SM_PLAYING %s %ld", sm.id, sm.data));
92     playing->sofar = sm.data;
93     break;
94   default:
95     disorder_error(0, "unknown speaker message type %d", sm.type);
96   }
97   return 0;
98 }
99
100 /** @brief Initialize the speaker process */
101 void speaker_setup(ev_source *ev) {
102   int sp[2];
103   pid_t pid;
104   struct speaker_message sm;
105
106   if(socketpair(PF_UNIX, SOCK_DGRAM, 0, sp) < 0)
107     disorder_fatal(errno, "error calling socketpair");
108   if(!(pid = xfork())) {
109     exitfn = _exit;
110     ev_signal_atfork(ev);
111     xdup2(sp[0], 0);
112     xdup2(sp[0], 1);
113     xclose(sp[0]);
114     xclose(sp[1]);
115     signal(SIGPIPE, SIG_DFL);
116 #if 0
117     execlp("valgrind", "valgrind", SPEAKER, "--config", configfile,
118            debugging ? "--debug" : "--no-debug",
119            log_default == &log_syslog ? "--syslog" : "--no-syslog",
120            (char *)0);
121 #else
122     execlp(SPEAKER, SPEAKER, "--config", configfile,
123            debugging ? "--debug" : "--no-debug",
124            log_default == &log_syslog ? "--syslog" : "--no-syslog",
125            (char *)0);
126 #endif
127     disorder_fatal(errno, "error invoking %s", SPEAKER);
128   }
129   ev_child(ev, pid, 0, speaker_terminated, 0);
130   speaker_fd = sp[1];
131   xclose(sp[0]);
132   cloexec(speaker_fd);
133   /* Wait for the speaker to be ready */
134   speaker_recv(speaker_fd, &sm);
135   nonblock(speaker_fd);
136   if(ev_fd(ev, ev_read, speaker_fd, speaker_readable, 0, "speaker read") < 0)
137     disorder_fatal(0, "error registering speaker socket fd");
138 }
139
140 /** @brief Tell the speaker to reload its configuration */
141 void speaker_reload(void) {
142   struct speaker_message sm;
143
144   memset(&sm, 0, sizeof sm);
145   sm.type = SM_RELOAD;
146   speaker_send(speaker_fd, &sm);
147 }
148
149 /* Track termination -------------------------------------------------------- */
150
151 /** @brief Called when the currently playing track finishes playing
152  * @param ev Event loop or NULL
153  *
154  * There are three places this is called from:
155  * 
156  * 1) speaker_readable(), when the speaker tells us the playing track finished.
157  * (Technically the speaker lies a little to arrange for gapless play.)
158  *
159  * 2) player_finished(), when the player for a non-raw track (i.e. one that
160  * does not use the speaker) finishes.
161  *
162  * 3) quitting(), after signalling the decoder or player but possible before it
163  * has actually terminated.  In this case @p ev is NULL, inhibiting any further
164  * attempt to play anything.
165  */
166 static void finished(ev_source *ev) {
167   D(("finished playing=%p", (void *)playing));
168   if(!playing)
169     return;
170   if(playing->state != playing_scratched)
171     notify_not_scratched(playing->track, playing->submitter);
172   switch(playing->state) {
173   case playing_ok:
174     eventlog("completed", playing->track, (char *)0);
175     break;
176   case playing_scratched:
177     eventlog("scratched", playing->track, playing->scratched, (char *)0);
178     break;
179   case playing_failed:
180     eventlog("failed", playing->track, wstat(playing->wstat), (char *)0);
181     break;
182   default:
183     break;
184   }
185   queue_played(playing);
186   recent_write();
187   playing = 0;
188   /* Try to play something else */
189   if(ev)
190     play(ev);
191 }
192
193 /** @brief Called when a player or decoder process terminates
194  *
195  * This is called when a decoder process terminates (which might actually be
196  * some time before the speaker reports it as finished) or when a non-raw
197  * (i.e. non-speaker) player terminates.  In the latter case it's imaginable
198  * that the OS has buffered the last few samples.
199  *
200  * NB.  The finished track might NOT be in the queue (yet) - it might be a
201  * pre-chosen scratch.
202  */
203 static int player_finished(ev_source *ev,
204                            pid_t pid,
205                            int status,
206                            const struct rusage attribute((unused)) *rusage,
207                            void *u) {
208   struct queue_entry *q = u;
209
210   D(("player_finished pid=%lu status=%#x",
211      (unsigned long)pid, (unsigned)status));
212   /* Record that this PID is dead.  If we killed the track we might know this
213    * already, but also it might have exited or crashed.  Either way we don't
214    * want to end up signalling it. */
215   q->pid = -1;
216   switch(q->state) {
217   case playing_unplayed:
218   case playing_random:
219     /* If this was a pre-prepared track then either it failed or we
220      * deliberately stopped it: it might have been removed from the queue, or
221      * moved down the queue, or the speaker might be on a break.  So we leave
222      * it state alone for future use.
223      */
224     break;
225   default:
226     /* We actually started playing this track. */
227     if(status) {
228       /* Don't override 'scratched' with 'failed'. */
229       if(q->state != playing_scratched)
230         q->state = playing_failed;
231     } else 
232       q->state = playing_ok;
233     break;
234   }
235   /* Regardless we always report and record the status and do cleanup for
236    * prefork calls. */
237   if(status)
238     disorder_error(0, "player for %s %s", q->track, wstat(status));
239   if(q->type & DISORDER_PLAYER_PREFORK)
240     play_cleanup(q->pl, q->data);
241   q->wstat = status;
242   /* If this actually was the current track, and does not use the speaker
243    * process, then it must have finished.  For raw-output players we will get a
244    * separate notification from the speaker process. */
245   if(q == playing
246      && (q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
247     finished(ev);
248   return 0;
249 }
250
251 /* Track initiation --------------------------------------------------------- */
252
253 /** @brief Find the player for @p q */
254 static const struct stringlist *find_player(const struct queue_entry *q) {
255   int n;
256   
257   for(n = 0; n < config->player.n; ++n)
258     if(fnmatch(config->player.s[n].s[0], q->track, 0) == 0)
259       break;
260   if(n >= config->player.n)
261     return NULL;
262   else
263     return &config->player.s[n];
264 }
265
266 /** @brief Start to play @p q
267  * @param ev Event loop
268  * @param q Track to play/prepare
269  * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
270  *
271  * This makes @p actually start playing.  It calls prepare() if necessary and
272  * either sends an @ref SM_PLAY command or invokes the player itself in a
273  * subprocess.
274  *
275  * It's up to the caller to set @ref playing and @c playing->state (this might
276  * be changed in the future).
277  */
278 static int start(ev_source *ev,
279                  struct queue_entry *q) {
280   const struct stringlist *player;
281   int rc;
282
283   D(("start %s", q->id));
284   /* Find the player plugin. */
285   if(!(player = find_player(q)) < 0)
286     return START_HARDFAIL;              /* No player */
287   if(!(q->pl = open_plugin(player->s[1], 0)))
288     return START_HARDFAIL;
289   q->type = play_get_type(q->pl);
290   /* Special handling for raw-format players */
291   if((q->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
292     /* Make sure that the track is prepared */
293     if((rc = prepare(ev, q)))
294       return rc;
295     /* Now we're sure it's prepared, start it playing */
296     /* TODO actually it might not be fully prepared yet - it's all happening in
297      * a subprocess.  See speaker.c for further discussion.  */
298     struct speaker_message sm[1];
299     memset(sm, 0, sizeof sm);
300     strcpy(sm->id, q->id);
301     sm->type = SM_PLAY;
302     speaker_send(speaker_fd, sm);
303     D(("sent SM_PLAY for %s", sm->id));
304     /* Our caller will set playing and playing->state = playing_started */
305     return START_OK;
306   } else {
307     rc = play_background(ev, player, q, start_child, NULL);
308     if(rc == START_OK)
309       ev_child(ev, q->pid, 0, player_finished, q);
310       /* Our caller will set playing and playing->state = playing_started */
311     return rc;
312   }
313 }
314
315 /** @brief Child-process half of start()
316  * @return Process exit code
317  *
318  * Called in subprocess to execute non-raw-format players (via plugin).
319  */
320 static int start_child(struct queue_entry *q, 
321                        const struct pbgc_params *params,
322                        void attribute((unused)) *bgdata) {
323   int n;
324
325   /* Wait for a device to clear.  This ugliness is now deprecated and will
326    * eventually be removed. */
327   if(params->waitdevice) {
328     ao_initialize();
329     if(*params->waitdevice) {
330       n = ao_driver_id(params->waitdevice);
331       if(n == -1)
332         disorder_fatal(0, "invalid libao driver: %s", params->waitdevice);
333     } else
334       n = ao_default_driver_id();
335     /* Make up a format. */
336     ao_sample_format format;
337     memset(&format, 0, sizeof format);
338     format.bits = 8;
339     format.rate = 44100;
340     format.channels = 1;
341     format.byte_format = AO_FMT_NATIVE;
342     int retries = 20;
343     struct timespec ts;
344     ts.tv_sec = 0;
345     ts.tv_nsec = 100000000;             /* 0.1s */
346     ao_device *device;
347     while((device = ao_open_live(n, &format, 0)) == 0 && retries-- > 0)
348       nanosleep(&ts, 0);
349     if(device)
350       ao_close(device);
351   }
352   /* Play the track */
353   play_track(q->pl,
354              params->argv, params->argc,
355              params->rawpath,
356              q->track);
357   return 0;
358 }
359
360 /** @brief Prepare a track for later play
361  * @return @ref START_OK, @ref START_HARDFAIL or @ref START_SOFTFAIL
362  *
363  * This can be called either when we want to play the track or slightly before
364  * so that some samples are decoded and available in a buffer.
365  *
366  * Only applies to raw-format (i.e. speaker-using) players; everything else
367  * gets @c START_OK.
368  */
369 int prepare(ev_source *ev,
370             struct queue_entry *q) {
371   const struct stringlist *player;
372
373   /* If there's a decoder (or player!) going we do nothing */
374   if(q->pid >= 0)
375     return START_OK;
376   /* If the track is already prepared, do nothing */
377   if(q->prepared)
378     return START_OK;
379   /* Find the player plugin */
380   if(!(player = find_player(q)) < 0) 
381     return START_HARDFAIL;              /* No player */
382   q->pl = open_plugin(player->s[1], 0);
383   q->type = play_get_type(q->pl);
384   if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
385     return START_OK;                    /* Not a raw player */
386   const int rc = play_background(ev, player, q, prepare_child, NULL);
387   if(rc == START_OK) {
388     ev_child(ev, q->pid, 0, player_finished, q);
389     q->prepared = 1;
390   }
391   return rc;
392 }
393
394 /** @brief Child-process half of prepare()
395  * @return Process exit code
396  *
397  * Called in subprocess to execute the decoder for a raw-format player.
398  *
399  * @todo We currently run the normalizer from here in a double-fork.  This is
400  * unsatisfactory for many reasons: we can't prevent it outliving the main
401  * server and we don't adequately report its exit status.
402  */
403 static int prepare_child(struct queue_entry *q, 
404                          const struct pbgc_params *params,
405                          void attribute((unused)) *bgdata) {
406   /* np will be the pipe to disorder-normalize */
407   int np[2];
408   if(socketpair(PF_UNIX, SOCK_STREAM, 0, np) < 0)
409     disorder_fatal(errno, "error calling socketpair");
410   /* Beware of the Leopard!  On OS X 10.5.x, the order of the shutdown
411    * calls here DOES MATTER.  If you do the SHUT_WR first then the SHUT_RD
412    * fails with "Socket is not connected".  I think this is a bug but
413    * provided implementors either don't care about the order or all agree
414    * about the order, choosing the reliable order is an adequate
415    * workaround.  */
416   xshutdown(np[1], SHUT_RD);    /* decoder writes to np[1] */
417   xshutdown(np[0], SHUT_WR);    /* normalize reads from np[0] */
418   blocking(np[0]);
419   blocking(np[1]);
420   /* Start disorder-normalize.  We double-fork so that nothing has to wait
421    * for disorder-normalize. */
422   pid_t npid;
423   if(!(npid = xfork())) {
424     /* Grandchild of disorderd */
425     if(!xfork()) {
426       /* Great-grandchild of disorderd */
427       /* Connect to the speaker process */
428       struct sockaddr_un addr;
429       memset(&addr, 0, sizeof addr);
430       addr.sun_family = AF_UNIX;
431       snprintf(addr.sun_path, sizeof addr.sun_path,
432                "%s/speaker/socket", config->home);
433       int sfd = xsocket(PF_UNIX, SOCK_STREAM, 0);
434       if(connect(sfd, (const struct sockaddr *)&addr, sizeof addr) < 0)
435         disorder_fatal(errno, "connecting to %s", addr.sun_path);
436       /* Send the ID, with a NATIVE-ENDIAN 32 bit length */
437       uint32_t l = strlen(q->id);
438       if(write(sfd, &l, sizeof l) < 0
439          || write(sfd, q->id, l) < 0)
440         disorder_fatal(errno, "writing to %s", addr.sun_path);
441       /* Await the ack */
442       if (read(sfd, &l, 1) < 0) 
443         disorder_fatal(errno, "reading ack from %s", addr.sun_path);
444       /* Plumbing */
445       xdup2(np[0], 0);
446       xdup2(sfd, 1);
447       xclose(np[0]);
448       xclose(np[1]);
449       xclose(sfd);
450       /* TODO stderr shouldn't be redirected for disorder-normalize
451        * (but it should be for play_track() */
452       execlp("disorder-normalize", "disorder-normalize",
453              log_default == &log_syslog ? "--syslog" : "--no-syslog",
454              "--config", configfile,
455              (char *)0);
456       disorder_fatal(errno, "executing disorder-normalize");
457       /* End of the great-grandchild of disorderd */
458     }
459     /* Back in the grandchild of disorderd */
460     _exit(0);
461     /* End of the grandchild of disorderd */
462   }
463   /* Back in the child of disorderd */
464   /* Wait for the grandchild of disordered to finish */
465   int n;
466   while(waitpid(npid, &n, 0) < 0 && errno == EINTR)
467     ;
468   /* Pass the file descriptor to the driver in an environment
469    * variable. */
470   char buffer[64];
471   snprintf(buffer, sizeof buffer, "DISORDER_RAW_FD=%d", np[1]);
472   if(putenv(buffer) < 0)
473     disorder_fatal(errno, "error calling putenv");
474   /* Close all the FDs we don't need */
475   xclose(np[0]);
476   /* Start the decoder itself */
477   play_track(q->pl,
478              params->argv, params->argc,
479              params->rawpath,
480              q->track);
481   return 0;
482 }
483
484 /** @brief Abandon a queue entry
485  *
486  * Called from c_remove() (but NOT when scratching a track).  Only does
487  * anything to raw-format tracks.  Terminates the background decoder and tells
488  * the speaker process to cancel the track.
489  */
490 void abandon(ev_source attribute((unused)) *ev,
491              struct queue_entry *q) {
492   struct speaker_message sm;
493
494   if(q->pid < 0)
495     return;                             /* Not prepared. */
496   if((q->type & DISORDER_PLAYER_TYPEMASK) != DISORDER_PLAYER_RAW)
497     return;                             /* Not a raw player. */
498   /* Terminate the player. */
499   kill(-q->pid, config->signal);
500   /* Cancel the track. */
501   memset(&sm, 0, sizeof sm);
502   sm.type = SM_CANCEL;
503   strcpy(sm.id, q->id);
504   speaker_send(speaker_fd, &sm);
505 }
506
507 /* Random tracks ------------------------------------------------------------ */
508
509 /** @brief Called with a new random track
510  * @param ev Event loop
511  * @param track Track name
512  */
513 static void chosen_random_track(ev_source *ev,
514                                 const char *track) {
515   struct queue_entry *q;
516
517   if(!track)
518     return;
519   /* Add the track to the queue */
520   q = queue_add(track, 0, WHERE_END, NULL, origin_random);
521   D(("picked %p (%s) at random", (void *)q, q->track));
522   queue_write();
523   /* Maybe a track can now be played */
524   play(ev);
525 }
526
527 /** @brief Maybe add a randomly chosen track
528  * @param ev Event loop
529  *
530  * Picking can take some time so the track will only be added after this
531  * function has returned.
532  */
533 void add_random_track(ev_source *ev) {
534   struct queue_entry *q;
535   long qlen = 0;
536
537   /* If random play is not enabled then do nothing. */
538   if(shutting_down || !random_is_enabled())
539     return;
540   /* Count how big the queue is */
541   for(q = qhead.next; q != &qhead; q = q->next)
542     ++qlen;
543   /* If it's smaller than the desired size then add a track */
544   if(qlen < config->queue_pad)
545     trackdb_request_random(ev, chosen_random_track);
546 }
547
548 /* Track initiation (part 2) ------------------------------------------------ */
549
550 /** @brief Attempt to play something
551  *
552  * This is called from numerous locations - whenever it might conceivably have
553  * become possible to play something.
554  */
555 void play(ev_source *ev) {
556   struct queue_entry *q;
557   int random_enabled = random_is_enabled();
558
559   D(("play playing=%p", (void *)playing));
560   /* If we're shutting down, or there's something playing, or playing is not
561    * enabled, give up now */
562   if(shutting_down || playing || !playing_is_enabled()) return;
563   /* See if there's anything to play */
564   if(qhead.next == &qhead) {
565     /* Queue is empty.  We could just wait around since there are periodic
566      * attempts to add a random track anyway.  However they are rarer than
567      * attempts to force a track so we initiate one now. */
568     add_random_track(ev);
569     /* chosen_random_track() will call play() when a new random track has been
570      * added to the queue. */
571     return;
572   }
573   /* There must be at least one track in the queue. */
574   q = qhead.next;
575   /* If random play is disabled but the track is a non-adopted random one
576    * then don't play it.  play() will be called again when random play is
577    * re-enabled. */
578   if(!random_enabled && q->origin == origin_random)
579     return;
580   D(("taken %p (%s) from queue", (void *)q, q->track));
581   /* Try to start playing. */
582   switch(start(ev, q)) {
583   case START_HARDFAIL:
584     if(q == qhead.next) {
585       queue_remove(q, 0);               /* Abandon this track. */
586       queue_played(q);
587       recent_write();
588     }
589     /* Oh well, try the next one */
590     play(ev);
591     break;
592   case START_SOFTFAIL:
593     /* We'll try the same track again shortly. */
594     break;
595   case START_OK:
596     /* Remove from the queue */
597     if(q == qhead.next) {
598       queue_remove(q, 0);
599       queue_write();
600     }
601     /* It's become the playing track */
602     playing = q;
603     xtime(&playing->played);
604     playing->state = playing_started;
605     notify_play(playing->track, playing->submitter);
606     eventlog("playing", playing->track,
607              playing->submitter ? playing->submitter : (const char *)0,
608              (const char *)0);
609     /* Maybe add a random track. */
610     add_random_track(ev);
611     /* If there is another track in the queue prepare it now.  This could
612      * potentially be a just-added random track. */
613     if(qhead.next != &qhead)
614       prepare(ev, qhead.next);
615     /* Make sure there is a prepared scratch */
616     ensure_next_scratch(ev);
617     break;
618   }
619 }
620
621 /* Miscelleneous ------------------------------------------------------------ */
622
623 /** @brief Return true if play is enabled */
624 int playing_is_enabled(void) {
625   const char *s = trackdb_get_global("playing");
626
627   return !s || !strcmp(s, "yes");
628 }
629
630 /** @brief Enable play */
631 void enable_playing(const char *who, ev_source *ev) {
632   trackdb_set_global("playing", "yes", who);
633   /* Add a random track if necessary. */
634   add_random_track(ev);
635   play(ev);
636 }
637
638 /** @brief Disable play */
639 void disable_playing(const char *who) {
640   trackdb_set_global("playing", "no", who);
641 }
642
643 /** @brief Return true if random play is enabled */
644 int random_is_enabled(void) {
645   const char *s = trackdb_get_global("random-play");
646
647   return !s || !strcmp(s, "yes");
648 }
649
650 /** @brief Enable random play */
651 void enable_random(const char *who, ev_source *ev) {
652   trackdb_set_global("random-play", "yes", who);
653   add_random_track(ev);
654   play(ev);
655 }
656
657 /** @brief Disable random play */
658 void disable_random(const char *who) {
659   trackdb_set_global("random-play", "no", who);
660 }
661
662 /* Scratching --------------------------------------------------------------- */
663
664 /** @brief Track to play next time something is scratched */
665 static struct queue_entry *next_scratch;
666
667 /** @brief Ensure there isa prepared scratch */
668 static void ensure_next_scratch(ev_source *ev) {
669   if(next_scratch)                      /* There's one already */
670     return;
671   if(!config->scratch.n)                /* There are no scratches */
672     return;
673   int r = rand() * (double)config->scratch.n / (RAND_MAX + 1.0);
674   next_scratch = queue_add(config->scratch.s[r], NULL,
675                            WHERE_NOWHERE, NULL, origin_scratch);
676   if(ev)
677     prepare(ev, next_scratch);
678 }
679
680 /** @brief Scratch a track
681  * @param who User responsible (or NULL)
682  * @param id Track ID (or NULL for current)
683  */
684 void scratch(const char *who, const char *id) {
685   struct speaker_message sm;
686
687   D(("scratch playing=%p state=%d id=%s playing->id=%s",
688      (void *)playing,
689      playing ? playing->state : 0,
690      id ? id : "(none)",
691      playing ? playing->id : "(none)"));
692   /* There must be a playing track; it must be in a scratchable state; if a
693    * specific ID was mentioned it must be that track. */
694   if(playing
695      && (playing->state == playing_started
696          || playing->state == playing_paused)
697      && (!id
698          || !strcmp(id, playing->id))) {
699     /* Update state (for the benefit of the 'recent' list) */
700     playing->state = playing_scratched;
701     playing->scratched = who ? xstrdup(who) : 0;
702     /* Find the player and kill the whole process group */
703     if(playing->pid >= 0) {
704       D(("kill -%d -%lu", config->signal, (unsigned long)playing->pid));
705       kill(-playing->pid, config->signal);
706     }
707     /* Tell the speaker, if we think it'll care */
708     if((playing->type & DISORDER_PLAYER_TYPEMASK) == DISORDER_PLAYER_RAW) {
709       memset(&sm, 0, sizeof sm);
710       sm.type = SM_CANCEL;
711       strcpy(sm.id, playing->id);
712       speaker_send(speaker_fd, &sm);
713       D(("sending SM_CANCEL for %s", playing->id));
714     }
715     /* Try to make sure there is a scratch */
716     ensure_next_scratch(NULL);
717     /* Insert it at the head of the queue */
718     if(next_scratch){
719       next_scratch->submitter = who;
720       queue_insert_entry(&qhead, next_scratch);
721       eventlog_raw("queue", queue_marshall(next_scratch), (const char *)0);
722       next_scratch = NULL;
723     }
724     notify_scratch(playing->track, playing->submitter, who,
725                    xtime(0) - playing->played);
726   }
727 }
728
729 /* Server termination ------------------------------------------------------- */
730
731 /** @brief Called from quit() to tear down everything belonging to this file */
732 void quitting(ev_source *ev) {
733   struct queue_entry *q;
734
735   /* Don't start anything new */
736   shutting_down = 1;
737   /* Shut down the current player */
738   if(playing) {
739     if(playing->pid >= 0)
740       kill(-playing->pid, config->signal);
741     playing->state = playing_quitting;
742     finished(0);
743   }
744   /* Zap any background decoders that are going */
745   for(q = qhead.next; q != &qhead; q = q->next)
746     if(q->pid >= 0) {
747       D(("kill -%d %lu", config->signal, (unsigned long)q->pid));
748       kill(-q->pid, config->signal);
749     }
750   /* Don't need the speaker any more */
751   ev_fd_cancel(ev, ev_read, speaker_fd);
752   xclose(speaker_fd);
753 }
754
755 /* Pause and resume --------------------------------------------------------- */
756
757 /** @brief Pause the playing track */
758 int pause_playing(const char *who) {
759   struct speaker_message sm;
760   long played;
761   
762   /* Can't pause if already paused or if nothing playing. */
763   if(!playing || paused) return 0;
764   switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
765   case DISORDER_PLAYER_STANDALONE:
766     if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
767     default:
768       disorder_error(0,  "cannot pause because player is not powerful enough");
769       return -1;
770     }
771     if(play_pause(playing->pl, &played, playing->data)) {
772       disorder_error(0, "player indicates it cannot pause");
773       return -1;
774     }
775     xtime(&playing->lastpaused);
776     playing->uptopause = played;
777     playing->lastresumed = 0;
778     break;
779   case DISORDER_PLAYER_RAW:
780     memset(&sm, 0, sizeof sm);
781     sm.type = SM_PAUSE;
782     speaker_send(speaker_fd, &sm);
783     break;
784   }
785   if(who)
786     disorder_info("paused by %s", who);
787   notify_pause(playing->track, who);
788   paused = 1;
789   if(playing->state == playing_started)
790     playing->state = playing_paused;
791   eventlog("state", "pause", (char *)0);
792   return 0;
793 }
794
795 /** @brief Resume playing after a pause */
796 void resume_playing(const char *who) {
797   struct speaker_message sm;
798
799   if(!paused) return;
800   paused = 0;
801   if(!playing) return;
802   switch(playing->type & DISORDER_PLAYER_TYPEMASK) {
803   case DISORDER_PLAYER_STANDALONE:
804     if(!(playing->type & DISORDER_PLAYER_PAUSES)) {
805     default:
806       /* Shouldn't happen */
807       return;
808     }
809     play_resume(playing->pl, playing->data);
810     xtime(&playing->lastresumed);
811     break;
812   case DISORDER_PLAYER_RAW:
813     memset(&sm, 0, sizeof sm);
814     sm.type = SM_RESUME;
815     speaker_send(speaker_fd, &sm);
816     break;
817   }
818   if(who) disorder_info("resumed by %s", who);
819   notify_resume(playing->track, who);
820   if(playing->state == playing_paused)
821     playing->state = playing_started;
822   eventlog("state", "resume", (char *)0);
823 }
824
825 /*
826 Local Variables:
827 c-basic-offset:2
828 comment-column:40
829 fill-column:79
830 indent-tabs-mode:nil
831 End:
832 */