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