Introduce vss_stopped().
[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 enum afs_socket_status {
265         AFS_SOCKET_READY,
266         AFS_SOCKET_CHECK_FOR_WRITE,
267         AFS_SOCKET_AFD_PENDING
268 };
269
270 static enum afs_socket_status afsss;
271
272 /**
273  * Compute the timeout for para_server's main select-loop.
274  *
275  * This function gets called from para_server to determine the timeout value
276  * for its main select loop.
277  *
278  * \param rfds The set of file descriptors to be checked for reading.
279  * \param wfds The set of file descriptors to be checked for writing.
280  * \param max_fileno The highest-numbered file descriptor.
281  *
282  * Before the timeout is computed, the current vss status flags are evaluated
283  * and acted upon by calling appropriate functions from the lower layers.
284  * Possible actions include
285  *
286  *      - request a new audio file from afs,
287  *      - shutdown of all senders (stop/pause command),
288  *      - reposition the stream (ff/jmp command).
289  *
290  * \return A pointer to a struct timeval containing the timeout for the next
291  * chunk of data to be sent, or NULL if we're not sending right now.
292  */
293 struct timeval *vss_preselect(fd_set *rfds, fd_set *wfds, int *max_fileno)
294 {
295         int i;
296         struct timeval *tv;
297
298         para_fd_set(afs_socket, rfds, max_fileno);
299         if (!map)
300                 for (i = 0; senders[i].name; i++)
301                         senders[i].shutdown_clients();
302         else {
303                 if (vss_next()) {
304                         vss_eof();
305                         return vss_compute_timeout();
306                 }
307         }
308         if (vss_paused() || vss_repos()) {
309                 for (i = 0; senders[i].name; i++)
310                         senders[i].shutdown_clients();
311                 if (map) {
312                         struct timeval now;
313                         gettimeofday(&now, NULL);
314                         if (!vss_paused() || mmd->chunks_sent)
315                                 tv_add(&mmd->afd.afhi.eof_tv, &now, &eof_barrier);
316                         if (vss_repos())
317                                 tv_add(&now, &announce_tv, &data_send_barrier);
318                 }
319                 mmd->chunks_sent = 0;
320         }
321         if (vss_repos()) {
322                 mmd->new_vss_status_flags &= ~(VSS_REPOS);
323                 mmd->current_chunk = mmd->repos_request;
324         }
325         tv = vss_compute_timeout();
326         if (tv)
327                 return tv;
328         if (!map && vss_playing() &&
329                         !(mmd->new_vss_status_flags & VSS_NOMORE)) {
330                 if (afsss == AFS_SOCKET_READY ||
331                                 afsss == AFS_SOCKET_CHECK_FOR_WRITE) {
332                         PARA_DEBUG_LOG("ready and playing, but no audio file\n");
333                         para_fd_set(afs_socket, wfds, max_fileno);
334                         afsss = AFS_SOCKET_CHECK_FOR_WRITE;
335                 }
336         }
337         return tv;
338 }
339
340 static int recv_afs_msg(int *fd, uint32_t *code, uint32_t *data)
341 {
342         char control[255], buf[8];
343         struct msghdr msg = {.msg_iov = NULL};
344         struct cmsghdr *cmsg;
345         struct iovec iov;
346         int ret = 0;
347
348         iov.iov_base = buf;
349         iov.iov_len = sizeof(buf);
350         msg.msg_iov = &iov;
351         msg.msg_iovlen = 1;
352         msg.msg_control = control;
353         msg.msg_controllen = sizeof(control);
354         memset(buf, 0, sizeof(buf));
355         ret = recvmsg(afs_socket, &msg, 0);
356         if (ret < 0)
357                 return -ERRNO_TO_PARA_ERROR(errno);
358         if (iov.iov_len != sizeof(buf))
359                 return -E_SHORT_AFS_READ;
360         *code = *(uint32_t*)buf;
361         *data =  *(uint32_t*)(buf + 4);
362         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
363                 if (cmsg->cmsg_level != SOL_SOCKET
364                         || cmsg->cmsg_type != SCM_RIGHTS)
365                 continue;
366                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
367                 continue;
368                 *fd = *(int *)CMSG_DATA(cmsg);
369         }
370         return 1;
371 }
372
373 static void recv_afs_result(void)
374 {
375         int ret, passed_fd = -1, shmid;
376         uint32_t afs_code = 0, afs_data = 0;
377         struct stat statbuf;
378         struct timeval now;
379
380         ret = recv_afs_msg(&passed_fd, &afs_code, &afs_data);
381         if (ret < 0)
382                 goto err;
383         PARA_DEBUG_LOG("got the fd: %d, code: %u, shmid: %u\n",
384                 passed_fd, afs_code, afs_data);
385         ret = -E_BAD_AFS_CODE;
386         if (afs_code != NEXT_AUDIO_FILE)
387                 goto err;
388         afsss = AFS_SOCKET_READY;
389         shmid = afs_data;
390         ret = load_afd(shmid, &mmd->afd);
391         if (ret < 0)
392                 goto err;
393         shm_destroy(shmid);
394         ret = fstat(passed_fd, &statbuf);
395         if (ret < 0) {
396                 PARA_ERROR_LOG("fstat error:\n");
397                 ret = -ERRNO_TO_PARA_ERROR(errno);
398                 goto err;
399         }
400         mmd->size = statbuf.st_size;
401         mmd->mtime = statbuf.st_mtime;
402         map = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE,
403                 passed_fd, 0);
404         close(passed_fd);
405         mmd->chunks_sent = 0;
406         mmd->current_chunk = 0;
407         mmd->offset = 0;
408         mmd->events++;
409         mmd->num_played++;
410         mmd->new_vss_status_flags &= (~VSS_NEXT);
411         gettimeofday(&now, NULL);
412         tv_add(&now, &announce_tv, &data_send_barrier);
413         return;
414 err:
415         if (passed_fd >= 0)
416                 close(passed_fd);
417         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
418 }
419
420 void vss_post_select(fd_set *rfds, fd_set *wfds)
421 {
422         int ret;
423
424         if (FD_ISSET(afs_socket, rfds))
425                 recv_afs_result();
426         if (afsss != AFS_SOCKET_CHECK_FOR_WRITE || !FD_ISSET(afs_socket, wfds))
427                 return;
428         PARA_NOTICE_LOG("requesting new fd from afs\n");
429         ret = send_buffer(afs_socket, "new");
430         afsss = AFS_SOCKET_AFD_PENDING;
431 }
432
433 static void get_chunk(long unsigned chunk_num, char **buf, size_t *len)
434 {
435         size_t pos = mmd->afd.afhi.chunk_table[chunk_num];
436         *buf = map + pos;
437         *len = mmd->afd.afhi.chunk_table[chunk_num + 1] - pos;
438 }
439
440 /**
441  * Get the data of the given chunk.
442  *
443  * \param chunk_num The number of the desired chunk.
444  * \param buf Chunk data.
445  * \param len Chunk length in bytes.
446  *
447  * \return Standard.
448  */
449 int vss_get_chunk(long unsigned chunk_num, char **buf, size_t *len)
450 {
451         if (!map || !vss_playing())
452                 return -E_CHUNK;
453         if (chunk_num >= mmd->afd.afhi.chunks_total)
454                 return -E_CHUNK;
455         get_chunk(chunk_num, buf, len);
456         return 1;
457 }
458
459 /**
460  * Main sending function.
461  *
462  * This function gets called from para_server as soon as the next chunk of data
463  * should be pushed out. It obtains a pointer to the data to be sent out as
464  * well as its length from mmd->afd.afhi. This information is then passed to
465  * each supported sender's send() function which is supposed to send out the data
466  * to all connected clients.
467  */
468 void vss_send_chunk(void)
469 {
470         int i;
471         struct timeval now, due;
472         char *buf;
473         size_t len;
474
475         if (!map || !vss_playing())
476                 return;
477         gettimeofday(&now, NULL);
478         vss_next_chunk_time(&due);
479         if (tv_diff(&due, &now, NULL) > 0)
480                 return;
481         if (chk_barrier("eof", &now, &eof_barrier, &due, 1) < 0)
482                 return;
483         if (chk_barrier("data send", &now, &data_send_barrier,
484                         &due, 1) < 0)
485                 return;
486         mmd->new_vss_status_flags &= ~VSS_REPOS;
487         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
488                 mmd->new_vss_status_flags |= VSS_NEXT;
489                 return vss_eof();
490         }
491         /*
492          * We call the send function also in case of empty chunks as they
493          * might have still some data queued which can be sent in this case.
494          */
495         if (!mmd->chunks_sent) {
496                 struct timeval tmp;
497                 gettimeofday(&mmd->stream_start, NULL);
498                 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &tmp);
499                 mmd->offset = tv2ms(&tmp);
500                 mmd->events++;
501         }
502         get_chunk(mmd->current_chunk, &buf, &len);
503         for (i = 0; senders[i].name; i++)
504                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, len);
505         mmd->new_vss_status_flags |= VSS_PLAYING;
506         mmd->chunks_sent++;
507         mmd->current_chunk++;
508 }