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