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