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