aacdec: Do not fail on emtpy buffers.
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2009 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 <dirent.h>
15
16 #include "para.h"
17 #include "error.h"
18 #include "string.h"
19 #include "afh.h"
20 #include "afs.h"
21 #include "server.h"
22 #include "net.h"
23 #include "server.cmdline.h"
24 #include "vss.h"
25 #include "list.h"
26 #include "send.h"
27 #include "ipc.h"
28 #include "fd.h"
29 #include "sched.h"
30
31 extern struct misc_meta_data *mmd;
32
33 extern void dccp_send_init(struct sender *);
34 extern void http_send_init(struct sender *);
35 extern void udp_send_init(struct sender *);
36
37 /** The list of supported senders. */
38 struct sender senders[] = {
39         {
40                 .name = "http",
41                 .init = http_send_init,
42         },
43         {
44                 .name = "dccp",
45                 .init = dccp_send_init,
46         },
47         {
48                 .name = "udp",
49                 .init = udp_send_init,
50         },
51         {
52                 .name = NULL,
53         }
54 };
55
56 /** The possible states of the afs socket. */
57 enum afs_socket_status {
58         /** Socket is inactive. */
59         AFS_SOCKET_READY,
60         /** Socket fd was included in the write fd set for select(). */
61         AFS_SOCKET_CHECK_FOR_WRITE,
62         /** vss wrote a request to the socket and waits for reply from afs. */
63         AFS_SOCKET_AFD_PENDING
64 };
65
66 /** The task structure for the virtual streaming system. */
67 struct vss_task {
68         /** Copied from the -announce_time command line option. */
69         struct timeval announce_tv;
70         /** End of the announcing interval. */
71         struct timeval data_send_barrier;
72         /** End of the EOF interval. */
73         struct timeval eof_barrier;
74         /** Only used if --autoplay_delay was given. */
75         struct timeval autoplay_barrier;
76         /** Used for afs-server communication. */
77         int afs_socket;
78         /** The current state of \a afs_socket. */
79         enum afs_socket_status afsss;
80         /** The memory mapped audio file. */
81         char *map;
82         /** Used by the scheduler. */
83         struct task task;
84         /** Pointer to the header of the mapped audio file. */
85         const char *header_buf;
86         /** Length of the audio file header. */
87         size_t header_len;
88 };
89
90 /**
91  * Check if vss status flag \a P (playing) is set.
92  *
93  * \return Greater than zero if playing, zero otherwise.
94  *
95  */
96 unsigned int vss_playing(void)
97 {
98         return mmd->new_vss_status_flags & VSS_PLAYING;
99 }
100
101 /**
102  * Check if the \a N (next) status flag is set.
103  *
104  * \return Greater than zero if set, zero if not.
105  *
106  */
107 unsigned int vss_next(void)
108 {
109         return mmd->new_vss_status_flags & VSS_NEXT;
110 }
111
112 /**
113  * Check if a reposition request is pending.
114  *
115  * \return Greater than zero if true, zero otherwise.
116  *
117  */
118 unsigned int vss_repos(void)
119 {
120         return mmd->new_vss_status_flags & VSS_REPOS;
121 }
122
123 /**
124  * Check if the vss is currently paused.
125  *
126  * \return Greater than zero if paused, zero otherwise.
127  *
128  */
129 unsigned int vss_paused(void)
130 {
131         return !(mmd->new_vss_status_flags & VSS_NEXT)
132                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
133 }
134
135 /**
136  * Check if the vss is currently stopped.
137  *
138  * \return Greater than zero if paused, zero otherwise.
139  *
140  */
141 unsigned int vss_stopped(void)
142 {
143         return (mmd->new_vss_status_flags & VSS_NEXT)
144                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
145 }
146
147 static int chk_barrier(const char *bname, const struct timeval *barrier,
148                 struct timeval *diff, int print_log)
149 {
150         long ms;
151
152         if (tv_diff(now, barrier, diff) > 0)
153                 return 1;
154         ms = tv2ms(diff);
155         if (print_log && ms)
156                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
157         return -1;
158 }
159
160 /*
161  * != NULL: timeout for next chunk
162  * NULL: nothing to do
163  */
164 static struct timeval *vss_compute_timeout(struct vss_task *vsst)
165 {
166         static struct timeval the_timeout;
167         struct timeval next_chunk;
168
169         if (vss_next() && vsst->map) {
170                 /* only sleep a bit, nec*/
171                 the_timeout.tv_sec = 0;
172                 the_timeout.tv_usec = 100;
173                 return &the_timeout;
174         }
175         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
176                         &the_timeout, 1) < 0)
177                 return &the_timeout;
178         if (chk_barrier("eof", &vsst->eof_barrier, &the_timeout, 1) < 0)
179                 return &the_timeout;
180         if (chk_barrier("data send", &vsst->data_send_barrier,
181                         &the_timeout, 1) < 0)
182                 return &the_timeout;
183         if (!vss_playing() || !vsst->map)
184                 return NULL;
185         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
186                 &mmd->stream_start, &next_chunk);
187         if (chk_barrier("chunk", &next_chunk, &the_timeout, 0) < 0)
188                 return &the_timeout;
189         /* chunk is due or bof */
190         the_timeout.tv_sec = 0;
191         the_timeout.tv_usec = 0;
192         return &the_timeout;
193 }
194
195 static void vss_eof(struct vss_task *vsst)
196 {
197         mmd->stream_start = *now;
198         if (!vsst->map)
199                 return;
200         if (mmd->new_vss_status_flags & VSS_NOMORE)
201                 mmd->new_vss_status_flags = VSS_NEXT;
202         tv_add(&mmd->afd.afhi.eof_tv, now, &vsst->eof_barrier);
203         para_munmap(vsst->map, mmd->size);
204         vsst->map = NULL;
205         mmd->chunks_sent = 0;
206         mmd->offset = 0;
207         mmd->afd.afhi.seconds_total = 0;
208         mmd->afd.afhi.chunk_tv.tv_sec = 0;
209         mmd->afd.afhi.chunk_tv.tv_usec = 0;
210         free(mmd->afd.afhi.chunk_table);
211         mmd->afd.afhi.chunk_table = NULL;
212         free(mmd->afd.afhi.info_string);
213         mmd->afd.afhi.info_string = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_FILE_INFO],
214                 status_item_list[SI_TAGINFO1], status_item_list[SI_TAGINFO2]);
215         make_empty_status_items(mmd->afd.verbose_ls_output);
216         mmd->mtime = 0;
217         mmd->size = 0;
218         mmd->events++;
219 }
220
221 /**
222  * Get the list of all supported audio formats.
223  *
224  * \return Aa space separated list of all supported audio formats
225  * It is not allocated at runtime, i.e. there is no need to free
226  * the returned string in the caller.
227  */
228 const char *supported_audio_formats(void)
229 {
230         return SUPPORTED_AUDIO_FORMATS;
231 }
232
233 /**
234  * Get the chunk time of the current audio file.
235  *
236  * \return A pointer to a struct containing the chunk time, or NULL,
237  * if currently no audio file is selected.
238  */
239 struct timeval *vss_chunk_time(void)
240 {
241         if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
242                         mmd->afd.afhi.chunk_tv.tv_usec == 0)
243                 return NULL;
244         return &mmd->afd.afhi.chunk_tv;
245 }
246
247 static int need_to_request_new_audio_file(struct vss_task *vsst)
248 {
249         struct timeval diff;
250
251         if (vsst->map) /* have audio file */
252                 return 0;
253         if (!vss_playing()) /* don't need one */
254                 return 0;
255         if (mmd->new_vss_status_flags & VSS_NOMORE)
256                 return 0;
257         if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
258                 return 0;
259         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
260                         &diff, 1) < 0)
261                 return 0;
262         return 1;
263 }
264
265 /**
266  * Compute the timeout for para_server's main select-loop.
267  *
268  * This function gets called from para_server to determine the timeout value
269  * for its main select loop.
270  *
271  * \param s Pointer to the server scheduler.
272  * \param t Pointer to the vss task structure.
273  *
274  * Before the timeout is computed, the current vss status flags are evaluated
275  * and acted upon by calling appropriate functions from the lower layers.
276  * Possible actions include
277  *
278  *      - request a new audio file from afs,
279  *      - shutdown of all senders (stop/pause command),
280  *      - reposition the stream (ff/jmp command).
281  */
282 static void vss_pre_select(struct sched *s, struct task *t)
283 {
284         int i;
285         struct timeval *tv, diff;
286         struct vss_task *vsst = container_of(t, struct vss_task, task);
287
288         if (!vsst->map || vss_next() || vss_paused() || vss_repos())
289                 for (i = 0; senders[i].name; i++)
290                         senders[i].shutdown_clients();
291         if (vss_next())
292                 vss_eof(vsst);
293         else if (vss_paused()) {
294                 if (mmd->chunks_sent)
295                         tv_add(&mmd->afd.afhi.eof_tv, now, &vsst->eof_barrier);
296                 mmd->chunks_sent = 0;
297         } else if (vss_repos()) {
298                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
299                 tv_add(&mmd->afd.afhi.eof_tv, now, &vsst->eof_barrier);
300                 mmd->chunks_sent = 0;
301                 mmd->current_chunk = mmd->repos_request;
302                 mmd->new_vss_status_flags &= ~VSS_REPOS;
303         }
304         if (need_to_request_new_audio_file(vsst)) {
305                 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
306                 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
307                 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
308         } else
309                 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
310         for (i = 0; senders[i].name; i++) {
311                 if (!senders[i].pre_select)
312                         continue;
313                 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
314         }
315         tv = vss_compute_timeout(vsst);
316         if (tv && tv_diff(tv, &s->timeout, &diff) < 0)
317                 s->timeout = *tv;
318 }
319
320 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
321 {
322         char control[255], buf[8];
323         struct msghdr msg = {.msg_iov = NULL};
324         struct cmsghdr *cmsg;
325         struct iovec iov;
326         int ret = 0;
327
328         *fd = -1;
329         iov.iov_base = buf;
330         iov.iov_len = sizeof(buf);
331         msg.msg_iov = &iov;
332         msg.msg_iovlen = 1;
333         msg.msg_control = control;
334         msg.msg_controllen = sizeof(control);
335         memset(buf, 0, sizeof(buf));
336         ret = recvmsg(afs_socket, &msg, 0);
337         if (ret < 0)
338                 return -ERRNO_TO_PARA_ERROR(errno);
339         if (iov.iov_len != sizeof(buf))
340                 return -E_AFS_SHORT_READ;
341         *code = *(uint32_t*)buf;
342         *data =  *(uint32_t*)(buf + 4);
343         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
344                 if (cmsg->cmsg_level != SOL_SOCKET
345                         || cmsg->cmsg_type != SCM_RIGHTS)
346                 continue;
347                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
348                 continue;
349                 *fd = *(int *)CMSG_DATA(cmsg);
350         }
351         return 1;
352 }
353
354 static void recv_afs_result(struct vss_task *vsst)
355 {
356         int ret, passed_fd, shmid;
357         uint32_t afs_code = 0, afs_data = 0;
358         struct stat statbuf;
359
360         vsst->afsss = AFS_SOCKET_READY;
361         mmd->afd.afhi.chunk_table = NULL;
362         ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
363         if (ret < 0)
364                 goto err;
365         PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
366                 afs_data);
367         ret = -E_NOFD;
368         if (afs_code != NEXT_AUDIO_FILE)
369                 goto err;
370         if (passed_fd < 0)
371                 goto err;
372         shmid = afs_data;
373         ret = load_afd(shmid, &mmd->afd);
374         if (ret < 0)
375                 goto err;
376         shm_destroy(shmid);
377         ret = fstat(passed_fd, &statbuf);
378         if (ret < 0) {
379                 PARA_ERROR_LOG("fstat error:\n");
380                 ret = -ERRNO_TO_PARA_ERROR(errno);
381                 goto err;
382         }
383         mmd->size = statbuf.st_size;
384         mmd->mtime = statbuf.st_mtime;
385         ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
386                 0, &vsst->map);
387         if (ret < 0)
388                 goto err;
389         close(passed_fd);
390         mmd->chunks_sent = 0;
391         mmd->current_chunk = 0;
392         mmd->offset = 0;
393         mmd->events++;
394         mmd->num_played++;
395         mmd->new_vss_status_flags &= (~VSS_NEXT);
396         afh_get_header(&mmd->afd.afhi, vsst->map, &vsst->header_buf,
397                 &vsst->header_len);
398         return;
399 err:
400         free(mmd->afd.afhi.chunk_table);
401         if (passed_fd >= 0)
402                 close(passed_fd);
403         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
404         mmd->new_vss_status_flags = VSS_NEXT;
405 }
406
407 /**
408  * Main sending function.
409  *
410  * This function gets called from para_server as soon as the next chunk of data
411  * should be pushed out. It obtains a pointer to the data to be sent out as
412  * well as its length from mmd->afd.afhi. This information is then passed to
413  * each supported sender's send() function which is supposed to send out the data
414  * to all connected clients.
415  */
416 static void vss_send_chunk(struct vss_task *vsst)
417 {
418         int i;
419         struct timeval due;
420         const char *buf;
421         size_t len;
422
423         if (!vsst->map || !vss_playing())
424                 return;
425         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
426                 &mmd->stream_start, &due);
427         if (tv_diff(&due, now, NULL) > 0)
428                 return;
429         if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
430                 return;
431         if (chk_barrier("data send", &vsst->data_send_barrier,
432                         &due, 1) < 0)
433                 return;
434         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
435                 mmd->new_vss_status_flags |= VSS_NEXT;
436                 return;
437         }
438         /*
439          * We call the send function also in case of empty chunks as they
440          * might have still some data queued which can be sent in this case.
441          */
442         if (!mmd->chunks_sent) {
443                 struct timeval tmp;
444                 mmd->stream_start = *now;
445                 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &tmp);
446                 mmd->offset = tv2ms(&tmp);
447                 mmd->events++;
448         }
449         afh_get_chunk(mmd->current_chunk, &mmd->afd.afhi, vsst->map, &buf, &len);
450         for (i = 0; senders[i].name; i++)
451                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, len,
452                         vsst->header_buf, vsst->header_len);
453         mmd->new_vss_status_flags |= VSS_PLAYING;
454         mmd->chunks_sent++;
455         mmd->current_chunk++;
456 }
457
458 static void vss_post_select(struct sched *s, struct task *t)
459 {
460         int ret, i;
461         struct vss_task *vsst = container_of(t, struct vss_task, task);
462
463         if (mmd->sender_cmd_data.cmd_num >= 0) {
464                 int num = mmd->sender_cmd_data.cmd_num,
465                         sender_num = mmd->sender_cmd_data.sender_num;
466
467                 if (senders[sender_num].client_cmds[num])
468                         senders[sender_num].client_cmds[num](&mmd->sender_cmd_data);
469                 mmd->sender_cmd_data.cmd_num = -1;
470         }
471         if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE) {
472                 if (FD_ISSET(vsst->afs_socket, &s->rfds))
473                         recv_afs_result(vsst);
474         } else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
475                 PARA_NOTICE_LOG("requesting new fd from afs\n");
476                 ret = send_buffer(vsst->afs_socket, "new");
477                 vsst->afsss = AFS_SOCKET_AFD_PENDING;
478         }
479         for (i = 0; senders[i].name; i++) {
480                 if (!senders[i].post_select)
481                         continue;
482                 senders[i].post_select(&s->rfds, &s->wfds);
483         }
484         if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
485                         (vss_next() && vss_playing()))
486                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
487         vss_send_chunk(vsst);
488 }
489
490 /**
491  * Initialize the virtual streaming system task.
492  *
493  * \param afs_socket The fd for communication with afs.
494  *
495  * This also initializes all supported senders and starts streaming
496  * if the --autoplay command line flag was given.
497  */
498 void init_vss_task(int afs_socket)
499 {
500         static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
501         int i;
502         char *hn = para_hostname(), *home = para_homedir();
503         long unsigned announce_time = conf.announce_time_arg > 0?
504                         conf.announce_time_arg : 300,
505                 autoplay_delay = conf.autoplay_delay_arg > 0?
506                         conf.autoplay_delay_arg : 0;
507
508         vsst->afs_socket = afs_socket;
509         vsst->task.pre_select = vss_pre_select;
510         vsst->task.post_select = vss_post_select;
511         ms2tv(announce_time, &vsst->announce_tv);
512         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
513         for (i = 0; senders[i].name; i++) {
514                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
515                 senders[i].init(&senders[i]);
516         }
517         free(hn);
518         free(home);
519         mmd->sender_cmd_data.cmd_num = -1;
520         make_empty_status_items(mmd->afd.verbose_ls_output);
521         if (conf.autoplay_given) {
522                 struct timeval tmp;
523                 mmd->vss_status_flags |= VSS_PLAYING;
524                 mmd->new_vss_status_flags |= VSS_PLAYING;
525                 ms2tv(autoplay_delay, &tmp);
526                 tv_add(now, &tmp, &vsst->autoplay_barrier);
527                 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
528                         &vsst->data_send_barrier);
529         }
530         register_task(&vsst->task);
531 }