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