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