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