]> git.tuebingen.mpg.de Git - paraslash.git/blob - vss.c
audio_format_name(): Add an assert().
[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         assert(i >= 0 && i < ARRAY_SIZE(afl));
157         return afl[i].name;
158 }
159
160 /**
161  * initialize the virtual streaming system
162  *
163  * Call the init functions of all supported audio format handlers and
164  * initialize all supported senders.
165  */
166 void vss_init(void)
167 {
168         int i;
169         char *hn = para_hostname(), *home = para_homedir();
170         long unsigned announce_time = conf.announce_time_arg > 0?
171                         conf.announce_time_arg : 300,
172                 autoplay_delay = conf.autoplay_delay_arg > 0?
173                         conf.autoplay_delay_arg : 0;
174
175         PARA_DEBUG_LOG("supported audio formats: %s\n",
176                 SUPPORTED_AUDIO_FORMATS);
177         FOR_EACH_AUDIO_FORMAT(i) {
178                 PARA_NOTICE_LOG("initializing %s handler\n",
179                         afl[i].name);
180                 afl[i].init(&afl[i]);
181         }
182         ms2tv(announce_time, &announce_tv);
183         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&announce_tv));
184         for (i = 0; senders[i].name; i++) {
185                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
186                 senders[i].init(&senders[i]);
187         }
188         free(hn);
189         free(home);
190         if (conf.autoplay_given) {
191                 struct timeval now, tmp;
192                 mmd->vss_status_flags |= VSS_PLAYING;
193                 mmd->new_vss_status_flags |= VSS_PLAYING;
194                 gettimeofday(&now, NULL);
195                 ms2tv(autoplay_delay, &tmp);
196                 tv_add(&now, &tmp, &autoplay_barrier);
197         }
198 }
199
200 static int get_file_info(int i)
201 {
202         return  afl[i].get_file_info(map, mmd->size, &mmd->afi);
203 }
204
205 /**
206  * guess the audio format judging from filename
207  *
208  * \param name the filename
209  *
210  * \return This function returns -1 if it has no idea what kind of audio
211  * file this might be. Otherwise the (non-negative) number of the audio format
212  * is returned.
213  */
214 int guess_audio_format(const char *name)
215 {
216         int i,j, len = strlen(name);
217
218         FOR_EACH_AUDIO_FORMAT(i) {
219                 for (j = 0; afl[i].suffixes[j]; j++) {
220                         const char *p = afl[i].suffixes[j];
221                         int plen = strlen(p);
222                         if (len < plen + 1)
223                                 continue;
224                         if (name[len - plen - 1] != '.')
225                                 continue;
226                         if (strcasecmp(name + len - plen, p))
227                                 continue;
228 //                      PARA_DEBUG_LOG("might be %s\n", audio_format_name(i));
229                         return i;
230                 }
231         }
232         return -1;
233 }
234
235 static int get_audio_format(int omit)
236 {
237         int i;
238
239         FOR_EACH_AUDIO_FORMAT(i) {
240                 if (i == omit)
241                         continue;
242                 if (get_file_info(i) > 0)
243                         return i;
244         }
245         return -E_AUDIO_FORMAT;
246 }
247
248 /**
249  * Call get_file_info() to obtain an afhi structure.
250  *
251  * \param path The full path of the audio file.
252  * \param data Pointer to the contents of the (mapped) file.
253  * \param size The file size in bytes.
254  * \param afhi Result pointer.
255  *
256  * \return The number of the audio format on success, \p -E_AUDIO_FORMAT if no
257  * compiled in audio format handler is able to handler the file.
258  *
259  * This function tries to find an audio format handler that can interpret the
260  * file given by \a data and \a size.
261  *
262  * It first tries to determine the audio format from the filename given by \a
263  * path. If this doesn't work, all other audio format handlers are tried until
264  * one is found that can handle the file.
265  */
266 int compute_afhi(const char *path, char *data, size_t size,
267                 struct audio_format_info *afhi)
268 {
269         int ret, i, format = guess_audio_format(path);
270
271         if (format >= 0) {
272                 ret = afl[format].get_file_info(data, size, afhi);
273                 if (ret >= 0)
274                         return format;
275         }
276         FOR_EACH_AUDIO_FORMAT(i) {
277                 if (i == format) /* we already tried this one to no avail */
278                         continue;
279                 ret = afl[i].get_file_info(data, size, afhi);
280                 if (ret >= 0)
281                         return i;
282                 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
283         }
284         return -E_AUDIO_FORMAT;
285 }
286
287 /*
288  * upddate shared mem
289  */
290 static int update_mmd(void)
291 {
292         int i;
293
294         i = guess_audio_format(mmd->filename);
295         if (i < 0 || get_file_info(i) < 0)
296                 i = get_audio_format(i);
297         if (i < 0)
298                 return i;
299         mmd->audio_format = i;
300         mmd->chunks_sent = 0;
301         mmd->current_chunk = 0;
302         mmd->offset = 0;
303         mmd->events++;
304         return 1;
305 }
306
307 static void vss_get_audio_file(void)
308 {
309         char **sl = selectors[mmd->selector_num].get_audio_file_list(10);
310         int i;
311         struct stat file_status;
312
313         if (!sl)
314                 goto err_out;
315         for (i = 0; sl[i]; i++) {
316                 struct timeval now;
317                 PARA_INFO_LOG("trying %s\n", sl[i]);
318                 if (strlen(sl[i]) >= _POSIX_PATH_MAX)
319                         continue;
320                 audio_file = open(sl[i], O_RDONLY);
321                 if (audio_file < 0)
322                         continue;
323                 if (fstat(audio_file, &file_status) == -1 ||
324                                 !file_status.st_size) {
325                         close(audio_file);
326                         continue;
327                 }
328                 mmd->size = file_status.st_size;
329                 mmd->mtime = file_status.st_mtime;
330                 map = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE,
331                         audio_file, 0);
332                 strcpy(mmd->filename, sl[i]);
333                 mmd->afi.header_len = 0; /* default: no header */
334                 if (update_mmd() < 0) { /* invalid file */
335                         close(audio_file);
336                         munmap(map, mmd->size);
337                         map = NULL;
338                         continue;
339                 }
340                 mmd->num_played++;
341                 if (selectors[mmd->selector_num].update_audio_file)
342                         selectors[mmd->selector_num].update_audio_file(sl[i]);
343                 PARA_NOTICE_LOG("next audio file: %s\n", mmd->filename);
344                 mmd->new_vss_status_flags &= (~VSS_NEXT);
345                 gettimeofday(&now, NULL);
346                 tv_add(&now, &announce_tv, &data_send_barrier);
347                 goto free;
348         }
349 err_out:
350         PARA_ERROR_LOG("%s", "no valid files found\n");
351         mmd->new_vss_status_flags = VSS_NEXT;
352 free:
353         if (sl) {
354                 for (i = 0; sl[i]; i++)
355                         free(sl[i]);
356                 free(sl);
357         }
358 }
359
360 static int chk_barrier(const char *bname, const struct timeval *now,
361                 const struct timeval *barrier, struct timeval *diff,
362                 int print_log)
363 {
364         long ms;
365
366         if (tv_diff(now, barrier, diff) > 0)
367                 return 1;
368         ms = tv2ms(diff);
369         if (print_log && ms)
370                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
371         return -1;
372 }
373
374 static void vss_next_chunk_time(struct timeval *due)
375 {
376         struct timeval tmp;
377
378         tv_scale(mmd->chunks_sent, &mmd->afi.chunk_tv, &tmp);
379         tv_add(&tmp, &mmd->stream_start, due);
380 }
381
382 /*
383  * != NULL: timeout for next chunk
384  * NULL: nothing to do
385  */
386 static struct timeval *vss_compute_timeout(void)
387 {
388         static struct timeval the_timeout;
389         struct timeval now, next_chunk;
390
391         if (vss_next() && mmd->audio_format >= 0) {
392                 /* only sleep a bit, nec*/
393                 the_timeout.tv_sec = 0;
394                 the_timeout.tv_usec = 100;
395                 return &the_timeout;
396         }
397         gettimeofday(&now, NULL);
398         if (chk_barrier("autoplay_delay", &now, &autoplay_barrier,
399                         &the_timeout, 1) < 0)
400                 return &the_timeout;
401         if (chk_barrier("eof", &now, &eof_barrier, &the_timeout, 1) < 0)
402                 return &the_timeout;
403         if (chk_barrier("data send", &now, &data_send_barrier,
404                         &the_timeout, 1) < 0)
405                 return &the_timeout;
406         if (mmd->audio_format < 0 || !vss_playing() || !map)
407                 return NULL;
408         vss_next_chunk_time(&next_chunk);
409         if (chk_barrier(afl[mmd->audio_format].name, &now, &next_chunk,
410                         &the_timeout, 0) < 0)
411                 return &the_timeout;
412         /* chunk is due or bof */
413         the_timeout.tv_sec = 0;
414         the_timeout.tv_usec = 0;
415         return &the_timeout;
416 }
417
418 static void vss_eof(void)
419 {
420         struct timeval now;
421         int i;
422         char *tmp;
423
424         if (!map) {
425                 for (i = 0; senders[i].name; i++)
426                         senders[i].shutdown_clients();
427                 return;
428         }
429         gettimeofday(&now, NULL);
430         tv_add(&mmd->afi.eof_tv, &now, &eof_barrier);
431         munmap(map, mmd->size);
432         map = NULL;
433         close(audio_file);
434         mmd->audio_format = -1;
435         mmd->chunks_sent = 0;
436         mmd->offset = 0;
437         mmd->afi.seconds_total = 0;
438         free(mmd->afi.chunk_table);
439         mmd->afi.chunk_table = NULL;
440         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_INFO1],
441                 status_item_list[SI_AUDIO_INFO2], status_item_list[SI_AUDIO_INFO3]);
442         strcpy(mmd->afi.info_string, tmp);
443         free(tmp);
444         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_DBINFO1],
445                 status_item_list[SI_DBINFO2], status_item_list[SI_DBINFO3]);
446         strcpy(mmd->selector_info, tmp);
447         free(tmp);
448         mmd->filename[0] = '\0';
449         mmd->size = 0;
450         mmd->events++;
451 }
452
453 /**
454  * Get the header of the current audio file.
455  *
456  * \param header_len the length of the header is stored here
457  *
458  * \return a pointer to a buffer containing the header, or NULL, if no audio
459  * file is selected or if the current audio format does not need special header
460  * treamtment.
461  *
462  */
463 char *vss_get_header(size_t *header_len)
464 {
465         if (mmd->audio_format < 0 || !map || !mmd->afi.header_len)
466                 return NULL;
467         *header_len = mmd->afi.header_len;
468         return map + mmd->afi.header_offset;
469 }
470
471 /**
472  * get the list of all supported audio formats
473  *
474  * \return a space separated list of all supported audio formats
475  * It is not allocated at runtime, i.e. there is no need to free
476  * the returned string in the caller.
477  */
478 const char *supported_audio_formats(void)
479 {
480         return SUPPORTED_AUDIO_FORMATS;
481 }
482
483 /**
484  * get the chunk time of the current audio file
485  *
486  * \return a pointer to a struct containing the chunk time, or NULL,
487  * if currently no audio file is selected.
488  */
489 struct timeval *vss_chunk_time(void)
490 {
491         if (mmd->audio_format < 0)
492                 return NULL;
493         return &mmd->afi.chunk_tv;
494 }
495
496 /**
497  * compute the timeout for para_server's main select-loop
498  *
499  * This function gets called from para_server to determine the timeout value
500  * for its main select loop.
501  *
502  * Before the timeout is computed, the current vss status flags are evaluated
503  * and acted upon by calling appropriate functions from the lower layers.
504  * Possible actions include
505  *
506  *      - request a new file list from the current audio file selector
507  *      - shutdown of all senders (stop/pause command)
508  *      - reposition the stream (ff/jmp command)
509  *
510  * \return A pointer to a struct timeval containing the timeout for the next
511  * chunk of data to be sent, or NULL if we're not sending right now.
512  */
513 struct timeval *vss_preselect(void)
514 {
515         struct audio_format_handler *af = NULL;
516         int i, format;
517         struct timeval *ret;
518 again:
519         format = mmd->audio_format;
520         if (format >= 0)
521                 af = afl + format;
522         else
523                 for (i = 0; senders[i].name; i++)
524                         senders[i].shutdown_clients();
525         if (vss_next() && af) {
526                 vss_eof();
527                 return vss_compute_timeout();
528         }
529         if (vss_paused() || vss_repos()) {
530                 for (i = 0; senders[i].name; i++)
531                         senders[i].shutdown_clients();
532                 if (af) {
533                         struct timeval now;
534                         gettimeofday(&now, NULL);
535                         if (!vss_paused() || mmd->chunks_sent)
536                                 tv_add(&mmd->afi.eof_tv, &now, &eof_barrier);
537                         if (vss_repos())
538                                 tv_add(&now, &announce_tv, &data_send_barrier);
539                         if (mmd->new_vss_status_flags & VSS_NOMORE)
540                                 mmd->new_vss_status_flags = VSS_NEXT;
541                 }
542                 mmd->chunks_sent = 0;
543         }
544         if (vss_repos()) {
545                 mmd->new_vss_status_flags &= ~(VSS_REPOS);
546                 mmd->current_chunk = mmd->repos_request;
547         }
548         ret = vss_compute_timeout();
549         if (!ret && !map && vss_playing() &&
550                         !(mmd->new_vss_status_flags & VSS_NOMORE)) {
551                 PARA_DEBUG_LOG("%s", "ready and playing, but no audio file\n");
552                 vss_get_audio_file();
553                 goto again;
554         }
555         return ret;
556 }
557
558 static void get_chunk(long unsigned chunk_num, char **buf, size_t *len)
559 {
560         size_t pos = mmd->afi.chunk_table[chunk_num];
561         *buf = map + pos;
562         *len = mmd->afi.chunk_table[chunk_num + 1] - pos;
563 }
564
565 /**
566  * Get the data of the given chunk.
567  *
568  * \param chunk_num The number of the desired chunk.
569  * \param buf Chunk data.
570  * \param len Chunk length in bytes.
571  *
572  * \return Positive on success, negative on errors.
573  */
574 int vss_get_chunk(long unsigned chunk_num, char **buf, size_t *len)
575 {
576         if (mmd->audio_format < 0 || !map || !vss_playing())
577                 return -E_CHUNK;
578         if (chunk_num >= mmd->afi.chunks_total)
579                 return -E_CHUNK;
580         get_chunk(chunk_num, buf, len);
581         return 1;
582 }
583
584 /**
585  * main sending function
586  *
587  * This function gets called from para_server as soon as the next chunk of
588  * data should be pushed out. It first calls the read_chunk() function of
589  * the current audio format handler to obtain a pointer to the data to be
590  * sent out as well as its length. This information is then passed to each
591  * supported sender's send() function which does the actual sending.
592  */
593 void vss_send_chunk(void)
594 {
595         int i;
596         struct audio_format_handler *af;
597         struct timeval now, due;
598
599         if (mmd->audio_format < 0 || !map || !vss_playing())
600                 return;
601         af = &afl[mmd->audio_format];
602         gettimeofday(&now, NULL);
603         vss_next_chunk_time(&due);
604         if (tv_diff(&due, &now, NULL) > 0)
605                 return;
606         if (chk_barrier("eof", &now, &eof_barrier, &due, 1) < 0)
607                 return;
608         if (chk_barrier("data send", &now, &data_send_barrier,
609                         &due, 1) < 0)
610                 return;
611         mmd->new_vss_status_flags &= ~VSS_REPOS;
612         if (mmd->current_chunk >= mmd->afi.chunks_total) { /* eof */
613                 mmd->new_vss_status_flags |= VSS_NEXT;
614                 return vss_eof();
615         }
616         /*
617          * We call the send function also in case of empty chunks as they
618          * might have still some data queued which can be sent in this case.
619          */
620         if (!mmd->chunks_sent) {
621                 struct timeval tmp;
622                 gettimeofday(&mmd->stream_start, NULL);
623                 tv_scale(mmd->current_chunk, &mmd->afi.chunk_tv, &tmp);
624                 mmd->offset = tv2ms(&tmp);
625                 mmd->events++;
626         }
627         for (i = 0; senders[i].name; i++) {
628                 char *buf;
629                 size_t len;
630                 get_chunk(mmd->current_chunk, &buf, &len);
631                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, len);
632         }
633         mmd->new_vss_status_flags |= VSS_PLAYING;
634         mmd->chunks_sent++;
635         mmd->current_chunk++;
636 }