Fix two typos in documentation.
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file vss.c the virtual streaming system
8  *
9  * This contains the audio streaming code of para_server which is independent
10  * of the current audio format, audio file selector and of the activated
11  * senders.
12  */
13
14 #include "para.h"
15 #include "afh.h"
16 #include "server.h"
17 #include <sys/mman.h> /* mmap */
18 #include <sys/time.h> /* gettimeofday */
19 #include "server.cmdline.h"
20 #include "afs_common.h"
21 #include "vss.h"
22 #include "send.h"
23 #include "error.h"
24 #include "string.h"
25 #include "fd.h"
26
27 extern const char *status_item_list[];
28
29 static struct timeval announce_tv;
30 static struct timeval data_send_barrier;
31 static struct timeval eof_barrier;
32 static struct timeval autoplay_barrier;
33
34 extern struct misc_meta_data *mmd;
35 extern struct audio_file_selector selectors[];
36 extern struct sender senders[];
37
38 static int audio_file;
39 static char *map;
40
41 /* The mp3 audio format handler does not need any libs. */
42 void mp3_init(struct audio_format_handler *);
43
44 #ifdef HAVE_OGGVORBIS
45         void ogg_init(struct audio_format_handler *);
46 #endif
47 #ifdef HAVE_FAAD
48         void aac_afh_init(struct audio_format_handler *);
49 #endif
50
51 /**
52  * The list of supported  audio formats.
53  *
54  * We always define the full array of audio formats even if some audio formats
55  * were not compiled in. This is because for each audio file the number of its
56  * audio format is stored in the databse. We don't want that numbers to become
57  * stale just because the user installed a new version of paraslash that
58  * supports a different set of audio formats.
59  *
60  * It can still be easily detected whether an audio format is compiled in by
61  * checking if the init function pointer is not \p NULL.
62  */
63 static struct audio_format_handler afl[] = {
64         {
65                 .name = "mp3",
66                 .init = mp3_init,
67         },
68         {
69                 .name = "ogg",
70 #ifdef HAVE_OGGVORBIS
71                 .init = ogg_init,
72 #endif
73         },
74         {
75                 .name = "aac",
76 #ifdef HAVE_FAAD
77                 .init = aac_afh_init,
78 #endif
79         },
80         {
81                 .name = NULL,
82         }
83 };
84
85 static inline int next_audio_format(int format)
86 {
87         for (;;) {
88                 if (!afl[format].name)
89                         return format;
90                 format++;
91                 if (afl[format].init)
92                         return format;
93         }
94
95 }
96
97 /** Iterate over each supported audio format. */
98 #define FOR_EACH_AUDIO_FORMAT(i) for (i = 0; afl[i].name; i = next_audio_format(i))
99
100
101 /**
102  * check if vss status flag \a P (playing) is set
103  *
104  * \return greater than zero if playing, zero otherwise.
105  *
106  */
107 unsigned int vss_playing(void)
108 {
109         return mmd->new_vss_status_flags & VSS_PLAYING;
110 }
111
112 /**
113  * check if \a N (next) status flag is set
114  *
115  * \return greater than zero if set, zero if not.
116  *
117  */
118 unsigned int vss_next(void)
119 {
120         return mmd->new_vss_status_flags & VSS_NEXT;
121 }
122
123 /**
124  * check if a reposition request is pending
125  *
126  * \return greater than zero if true, zero otherwise.
127  *
128  */
129 unsigned int vss_repos(void)
130 {
131         return mmd->new_vss_status_flags & VSS_REPOS;
132 }
133
134 /**
135  * check if the vss is currently paused
136  *
137  * \return greater than zero if paused, zero otherwise.
138  *
139  */
140 unsigned int vss_paused(void)
141 {
142         return !(mmd->new_vss_status_flags & VSS_NEXT)
143                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
144 }
145
146 /**
147  * get the name of the given audio format
148  *
149  * \param i the audio format number
150  *
151  * This returns a pointer to statically allocated memory so it
152  * must not be freed by the caller.
153  */
154 const char *audio_format_name(int i)
155 {
156         return i >= 0?  afl[i].name : "(none)";
157 }
158
159 /**
160  * initialize the virtual streaming system
161  *
162  * Call the init functions of all supported audio format handlers and
163  * initialize all supported senders.
164  */
165 void vss_init(void)
166 {
167         int i;
168         char *hn = para_hostname(), *home = para_homedir();
169         long unsigned announce_time = conf.announce_time_arg > 0?
170                         conf.announce_time_arg : 300,
171                 autoplay_delay = conf.autoplay_delay_arg > 0?
172                         conf.autoplay_delay_arg : 0;
173
174         PARA_DEBUG_LOG("supported audio formats: %s\n",
175                 SUPPORTED_AUDIO_FORMATS);
176         for (i = 0; afl[i].name; i++) {
177                 PARA_NOTICE_LOG("initializing %s handler\n",
178                         afl[i].name);
179                 afl[i].init(&afl[i]);
180         }
181         ms2tv(announce_time, &announce_tv);
182         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&announce_tv));
183         for (i = 0; senders[i].name; i++) {
184                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
185                 senders[i].init(&senders[i]);
186         }
187         free(hn);
188         free(home);
189         if (conf.autoplay_given) {
190                 struct timeval now, tmp;
191                 mmd->vss_status_flags |= VSS_PLAYING;
192                 mmd->new_vss_status_flags |= VSS_PLAYING;
193                 gettimeofday(&now, NULL);
194                 ms2tv(autoplay_delay, &tmp);
195                 tv_add(&now, &tmp, &autoplay_barrier);
196         }
197 }
198
199 static int get_file_info(int i)
200 {
201         return  afl[i].get_file_info(map, mmd->size, &mmd->afi);
202 }
203
204 /**
205  * guess the audio format judging from filename
206  *
207  * \param name the filename
208  *
209  * \return This function returns -1 if it has no idea what kind of audio
210  * file this might be. Otherwise the (non-negative) number of the audio format
211  * is returned.
212  */
213 int guess_audio_format(const char *name)
214 {
215         int i,j, len = strlen(name);
216
217         FOR_EACH_AUDIO_FORMAT(i) {
218                 for (j = 0; afl[i].suffixes[j]; j++) {
219                         const char *p = afl[i].suffixes[j];
220                         int plen = strlen(p);
221                         if (len < plen + 1)
222                                 continue;
223                         if (name[len - plen - 1] != '.')
224                                 continue;
225                         if (strcasecmp(name + len - plen, p))
226                                 continue;
227 //                      PARA_DEBUG_LOG("might be %s\n", audio_format_name(i));
228                         return i;
229                 }
230         }
231         return -1;
232 }
233
234 static int get_audio_format(int omit)
235 {
236         int i;
237
238         FOR_EACH_AUDIO_FORMAT(i) {
239                 if (i == omit)
240                         continue;
241                 if (get_file_info(i) > 0)
242                         return i;
243         }
244         return -E_AUDIO_FORMAT;
245 }
246
247 /**
248  * Call get_file_info() to obtain an afhi structure.
249  *
250  * \param path The full path of the audio file.
251  * \param data Pointer to the contents of the (mapped) file.
252  * \param size The file size in bytes.
253  * \param afhi Result pointer.
254  *
255  * \return The number of the audio format on success, \p -E_AUDIO_FORMAT if no
256  * compiled in audio format handler is able to handler the file.
257  *
258  * This function tries to find an audio format handler that can interpret the
259  * file given by \a data and \a size.
260  *
261  * It first tries to determine the audio format from the filename given by \a
262  * path. If this doesn't work, all other audio format handlers are tried until
263  * one is found that can handle the file.
264  */
265 int compute_afhi(const char *path, char *data, size_t size,
266                 struct audio_format_info *afhi)
267 {
268         int ret, i, format = guess_audio_format(path);
269
270         if (format >= 0) {
271                 ret = afl[format].get_file_info(data, size, afhi);
272                 if (ret >= 0)
273                         return format;
274         }
275         FOR_EACH_AUDIO_FORMAT(i) {
276                 if (i == format) /* we already tried this one to no avail */
277                         continue;
278                 ret = afl[i].get_file_info(data, size, afhi);
279                 if (ret >= 0)
280                         return i;
281         }
282         return -E_AUDIO_FORMAT;
283 }
284
285 /*
286  * upddate shared mem
287  */
288 static int update_mmd(void)
289 {
290         int i;
291
292         i = guess_audio_format(mmd->filename);
293         if (i < 0 || get_file_info(i) < 0)
294                 i = get_audio_format(i);
295         if (i < 0)
296                 return i;
297         mmd->audio_format = i;
298         mmd->chunks_sent = 0;
299         mmd->current_chunk = 0;
300         mmd->offset = 0;
301         mmd->events++;
302         return 1;
303 }
304
305 static void vss_get_audio_file(void)
306 {
307         char **sl = selectors[mmd->selector_num].get_audio_file_list(10);
308         int i;
309         struct stat file_status;
310
311         if (!sl)
312                 goto err_out;
313         for (i = 0; sl[i]; i++) {
314                 struct timeval now;
315                 PARA_INFO_LOG("trying %s\n", sl[i]);
316                 if (strlen(sl[i]) >= _POSIX_PATH_MAX)
317                         continue;
318                 audio_file = open(sl[i], O_RDONLY);
319                 if (audio_file < 0)
320                         continue;
321                 if (fstat(audio_file, &file_status) == -1 ||
322                                 !file_status.st_size) {
323                         close(audio_file);
324                         continue;
325                 }
326                 mmd->size = file_status.st_size;
327                 mmd->mtime = file_status.st_mtime;
328                 map = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE,
329                         audio_file, 0);
330                 strcpy(mmd->filename, sl[i]);
331                 mmd->afi.header_len = 0; /* default: no header */
332                 if (update_mmd() < 0) { /* invalid file */
333                         close(audio_file);
334                         munmap(map, mmd->size);
335                         map = NULL;
336                         continue;
337                 }
338                 mmd->num_played++;
339                 if (selectors[mmd->selector_num].update_audio_file)
340                         selectors[mmd->selector_num].update_audio_file(sl[i]);
341                 PARA_NOTICE_LOG("next audio file: %s\n", mmd->filename);
342                 mmd->new_vss_status_flags &= (~VSS_NEXT);
343                 gettimeofday(&now, NULL);
344                 tv_add(&now, &announce_tv, &data_send_barrier);
345                 goto free;
346         }
347 err_out:
348         PARA_ERROR_LOG("%s", "no valid files found\n");
349         mmd->new_vss_status_flags = VSS_NEXT;
350 free:
351         if (sl) {
352                 for (i = 0; sl[i]; i++)
353                         free(sl[i]);
354                 free(sl);
355         }
356 }
357
358 static int chk_barrier(const char *bname, const struct timeval *now,
359                 const struct timeval *barrier, struct timeval *diff,
360                 int print_log)
361 {
362         long ms;
363
364         if (tv_diff(now, barrier, diff) > 0)
365                 return 1;
366         ms = tv2ms(diff);
367         if (print_log && ms)
368                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
369         return -1;
370 }
371
372 static void vss_next_chunk_time(struct timeval *due)
373 {
374         struct timeval tmp;
375
376         tv_scale(mmd->chunks_sent, &mmd->afi.chunk_tv, &tmp);
377         tv_add(&tmp, &mmd->stream_start, due);
378 }
379
380 /*
381  * != NULL: timeout for next chunk
382  * NULL: nothing to do
383  */
384 static struct timeval *vss_compute_timeout(void)
385 {
386         static struct timeval the_timeout;
387         struct timeval now, next_chunk;
388
389         if (vss_next() && mmd->audio_format >= 0) {
390                 /* only sleep a bit, nec*/
391                 the_timeout.tv_sec = 0;
392                 the_timeout.tv_usec = 100;
393                 return &the_timeout;
394         }
395         gettimeofday(&now, NULL);
396         if (chk_barrier("autoplay_delay", &now, &autoplay_barrier,
397                         &the_timeout, 1) < 0)
398                 return &the_timeout;
399         if (chk_barrier("eof", &now, &eof_barrier, &the_timeout, 1) < 0)
400                 return &the_timeout;
401         if (chk_barrier("data send", &now, &data_send_barrier,
402                         &the_timeout, 1) < 0)
403                 return &the_timeout;
404         if (mmd->audio_format < 0 || !vss_playing() || !map)
405                 return NULL;
406         vss_next_chunk_time(&next_chunk);
407         if (chk_barrier(afl[mmd->audio_format].name, &now, &next_chunk,
408                         &the_timeout, 0) < 0)
409                 return &the_timeout;
410         /* chunk is due or bof */
411         the_timeout.tv_sec = 0;
412         the_timeout.tv_usec = 0;
413         return &the_timeout;
414 }
415
416 static void vss_eof(void)
417 {
418         struct timeval now;
419         int i;
420         char *tmp;
421
422         if (!map) {
423                 for (i = 0; senders[i].name; i++)
424                         senders[i].shutdown_clients();
425                 return;
426         }
427         gettimeofday(&now, NULL);
428         tv_add(&mmd->afi.eof_tv, &now, &eof_barrier);
429         munmap(map, mmd->size);
430         map = NULL;
431         close(audio_file);
432         mmd->audio_format = -1;
433         mmd->chunks_sent = 0;
434         mmd->offset = 0;
435         mmd->afi.seconds_total = 0;
436         free(mmd->afi.chunk_table);
437         mmd->afi.chunk_table = NULL;
438         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_INFO1],
439                 status_item_list[SI_AUDIO_INFO2], status_item_list[SI_AUDIO_INFO3]);
440         strcpy(mmd->afi.info_string, tmp);
441         free(tmp);
442         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_DBINFO1],
443                 status_item_list[SI_DBINFO2], status_item_list[SI_DBINFO3]);
444         strcpy(mmd->selector_info, tmp);
445         free(tmp);
446         mmd->filename[0] = '\0';
447         mmd->size = 0;
448         mmd->events++;
449 }
450
451 /**
452  * Get the header of the current audio file.
453  *
454  * \param header_len the length of the header is stored here
455  *
456  * \return a pointer to a buffer containing the header, or NULL, if no audio
457  * file is selected or if the current audio format does not need special header
458  * treamtment.
459  *
460  */
461 char *vss_get_header(size_t *header_len)
462 {
463         if (mmd->audio_format < 0 || !map || !mmd->afi.header_len)
464                 return NULL;
465         *header_len = mmd->afi.header_len;
466         return map + mmd->afi.header_offset;
467 }
468
469 /**
470  * get the list of all supported audio formats
471  *
472  * \return a space separated list of all supported audio formats
473  * It is not allocated at runtime, i.e. there is no need to free
474  * the returned string in the caller.
475  */
476 const char *supported_audio_formats(void)
477 {
478         return SUPPORTED_AUDIO_FORMATS;
479 }
480
481 /**
482  * get the chunk time of the current audio file
483  *
484  * \return a pointer to a struct containing the chunk time, or NULL,
485  * if currently no audio file is selected.
486  */
487 struct timeval *vss_chunk_time(void)
488 {
489         if (mmd->audio_format < 0)
490                 return NULL;
491         return &mmd->afi.chunk_tv;
492 }
493
494 /**
495  * compute the timeout for para_server's main select-loop
496  *
497  * This function gets called from para_server to determine the timeout value
498  * for its main select loop.
499  *
500  * Before the timeout is computed, the current vss status flags are evaluated
501  * and acted upon by calling appropriate functions from the lower layers.
502  * Possible actions include
503  *
504  *      - request a new file list from the current audio file selector
505  *      - shutdown of all senders (stop/pause command)
506  *      - reposition the stream (ff/jmp command)
507  *
508  * \return A pointer to a struct timeval containing the timeout for the next
509  * chunk of data to be sent, or NULL if we're not sending right now.
510  */
511 struct timeval *vss_preselect(void)
512 {
513         struct audio_format_handler *af = NULL;
514         int i, format;
515         struct timeval *ret;
516 again:
517         format = mmd->audio_format;
518         if (format >= 0)
519                 af = afl + format;
520         else
521                 for (i = 0; senders[i].name; i++)
522                         senders[i].shutdown_clients();
523         if (vss_next() && af) {
524                 vss_eof();
525                 return vss_compute_timeout();
526         }
527         if (vss_paused() || vss_repos()) {
528                 for (i = 0; senders[i].name; i++)
529                         senders[i].shutdown_clients();
530                 if (af) {
531                         struct timeval now;
532                         gettimeofday(&now, NULL);
533                         if (!vss_paused() || mmd->chunks_sent)
534                                 tv_add(&mmd->afi.eof_tv, &now, &eof_barrier);
535                         if (vss_repos())
536                                 tv_add(&now, &announce_tv, &data_send_barrier);
537                         if (mmd->new_vss_status_flags & VSS_NOMORE)
538                                 mmd->new_vss_status_flags = VSS_NEXT;
539                 }
540                 mmd->chunks_sent = 0;
541         }
542         if (vss_repos()) {
543                 mmd->new_vss_status_flags &= ~(VSS_REPOS);
544                 mmd->current_chunk = mmd->repos_request;
545         }
546         ret = vss_compute_timeout();
547         if (!ret && !map && vss_playing() &&
548                         !(mmd->new_vss_status_flags & VSS_NOMORE)) {
549                 PARA_DEBUG_LOG("%s", "ready and playing, but no audio file\n");
550                 vss_get_audio_file();
551                 goto again;
552         }
553         return ret;
554 }
555
556 static void get_chunk(long unsigned chunk_num, char **buf, size_t *len)
557 {
558         size_t pos = mmd->afi.chunk_table[chunk_num];
559         *buf = map + pos;
560         *len = mmd->afi.chunk_table[chunk_num + 1] - pos;
561 }
562
563 /**
564  * Get the data of the given chunk.
565  *
566  * \param chunk_num The number of the desired chunk.
567  * \param buf Chunk data.
568  * \param len Chunk length in bytes.
569  *
570  * \return Positive on success, negative on errors.
571  */
572 int vss_get_chunk(long unsigned chunk_num, char **buf, size_t *len)
573 {
574         if (mmd->audio_format < 0 || !map || !vss_playing())
575                 return -E_CHUNK;
576         if (chunk_num >= mmd->afi.chunks_total)
577                 return -E_CHUNK;
578         get_chunk(chunk_num, buf, len);
579         return 1;
580 }
581
582 /**
583  * main sending function
584  *
585  * This function gets called from para_server as soon as the next chunk of
586  * data should be pushed out. It first calls the read_chunk() function of
587  * the current audio format handler to obtain a pointer to the data to be
588  * sent out as well as its length. This information is then passed to each
589  * supported sender's send() function which does the actual sending.
590  */
591 void vss_send_chunk(void)
592 {
593         int i;
594         struct audio_format_handler *af;
595         struct timeval now, due;
596
597         if (mmd->audio_format < 0 || !map || !vss_playing())
598                 return;
599         af = &afl[mmd->audio_format];
600         gettimeofday(&now, NULL);
601         vss_next_chunk_time(&due);
602         if (tv_diff(&due, &now, NULL) > 0)
603                 return;
604         if (chk_barrier("eof", &now, &eof_barrier, &due, 1) < 0)
605                 return;
606         if (chk_barrier("data send", &now, &data_send_barrier,
607                         &due, 1) < 0)
608                 return;
609         mmd->new_vss_status_flags &= ~VSS_REPOS;
610         if (mmd->current_chunk >= mmd->afi.chunks_total) { /* eof */
611                 mmd->new_vss_status_flags |= VSS_NEXT;
612                 return vss_eof();
613         }
614         /*
615          * We call the send function also in case of empty chunks as they
616          * might have still some data queued which can be sent in this case.
617          */
618         if (!mmd->chunks_sent) {
619                 struct timeval tmp;
620                 gettimeofday(&mmd->stream_start, NULL);
621                 tv_scale(mmd->current_chunk, &mmd->afi.chunk_tv, &tmp);
622                 mmd->offset = tv2ms(&tmp);
623                 mmd->events++;
624         }
625         for (i = 0; senders[i].name; i++) {
626                 char *buf;
627                 size_t len;
628                 get_chunk(mmd->current_chunk, &buf, &len);
629                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, len);
630         }
631         mmd->new_vss_status_flags |= VSS_PLAYING;
632         mmd->chunks_sent++;
633         mmd->current_chunk++;
634 }