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