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