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