25082834eb0160de013dd11639f3354160ee261b
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2010 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 <regex.h>
15 #include <dirent.h>
16 #include <osl.h>
17
18 #include "para.h"
19 #include "error.h"
20 #include "portable_io.h"
21 #include "fec.h"
22 #include "string.h"
23 #include "afh.h"
24 #include "afs.h"
25 #include "server.h"
26 #include "net.h"
27 #include "server.cmdline.h"
28 #include "list.h"
29 #include "send.h"
30 #include "vss.h"
31 #include "ipc.h"
32 #include "fd.h"
33 #include "sched.h"
34
35 extern struct misc_meta_data *mmd;
36
37 extern void dccp_send_init(struct sender *);
38 extern void http_send_init(struct sender *);
39 extern void udp_send_init(struct sender *);
40
41 /** The list of supported senders. */
42 struct sender senders[] = {
43         {
44                 .name = "http",
45                 .init = http_send_init,
46         },
47         {
48                 .name = "dccp",
49                 .init = dccp_send_init,
50         },
51         {
52                 .name = "udp",
53                 .init = udp_send_init,
54         },
55         {
56                 .name = NULL,
57         }
58 };
59
60 /** The possible states of the afs socket. */
61 enum afs_socket_status {
62         /** Socket is inactive. */
63         AFS_SOCKET_READY,
64         /** Socket fd was included in the write fd set for select(). */
65         AFS_SOCKET_CHECK_FOR_WRITE,
66         /** vss wrote a request to the socket and waits for reply from afs. */
67         AFS_SOCKET_AFD_PENDING
68 };
69
70 /** The task structure for the virtual streaming system. */
71 struct vss_task {
72         /** Copied from the -announce_time command line option. */
73         struct timeval announce_tv;
74         /** End of the announcing interval. */
75         struct timeval data_send_barrier;
76         /** End of the EOF interval. */
77         struct timeval eof_barrier;
78         /** Only used if --autoplay_delay was given. */
79         struct timeval autoplay_barrier;
80         /** Used for afs-server communication. */
81         int afs_socket;
82         /** The current state of \a afs_socket. */
83         enum afs_socket_status afsss;
84         /** The memory mapped audio file. */
85         char *map;
86         /** Used by the scheduler. */
87         struct task task;
88         /** Pointer to the header of the mapped audio file. */
89         const char *header_buf;
90         /** Length of the audio file header. */
91         size_t header_len;
92         /** Time between audio file headers are sent. */
93         struct timeval header_interval;
94 };
95
96 /**
97  * The list of currently connected fec clients.
98  *
99  * Senders may use \ref vss_add_fec_client() to add entries to the list.
100  */
101 static struct list_head fec_client_list;
102
103 /**
104  * Data associated with one FEC group.
105  *
106  * A FEC group consists of a fixed number of slices and this number is given by
107  * the \a slices_per_group parameter of struct \ref fec_client_parms. Each FEC
108  * group contains a number of chunks of the current audio file.
109  *
110  * FEC slices directly correspond to the data packages sent by the paraslash
111  * senders that use FEC. Each slice is identified by its group number and its
112  * number within the group. All slices have the same size, but the last slice
113  * of the group may not be filled entirely.
114  */
115 struct fec_group {
116         /** The number of the FEC group. */
117         uint32_t num;
118         /** Number of bytes in this group. */
119         uint32_t bytes;
120         /** The first chunk of the current audio file belonging to the group. */
121         uint32_t first_chunk;
122         /** The number of chunks contained in this group. */
123         uint32_t num_chunks;
124         /** When the first chunk was sent. */
125         struct timeval start;
126         /** The duration of the full group. */
127         struct timeval duration;
128         /** The group duration divided by the number of slices. */
129         struct timeval slice_duration;
130         /** Group contains the audio file header that occupies that many slices. */
131         uint8_t num_header_slices;
132 };
133
134 enum fec_client_state {
135         FEC_STATE_NONE = 0,     /**< not initialized and not enabled */
136         FEC_STATE_DISABLED,     /**< temporarily disabled */
137         FEC_STATE_READY_TO_RUN  /**< initialized and enabled */
138 };
139
140 /**
141  * Describes one connected FEC client.
142  */
143 struct fec_client {
144         /** Current state of the client */
145         enum fec_client_state state;
146         /** The connected sender client (transport layer). */
147         struct sender_client *sc;
148         /** Parameters requested by the client. */
149         struct fec_client_parms *fcp;
150         /** Used by the core FEC code. */
151         struct fec_parms *parms;
152         /** The position of this client in the fec client list. */
153         struct list_head node;
154         /** When the first slice for this client was sent. */
155         struct timeval stream_start;
156         /** The first chunk sent to this FEC client. */
157         int first_stream_chunk;
158         /** Describes the current group. */
159         struct fec_group group;
160         /** The current slice. */
161         uint8_t current_slice_num;
162         /** The data to be FEC-encoded (point to a region within the mapped audio file). */
163         const unsigned char **src_data;
164         /** Last time an audio  header was sent. */
165         struct timeval next_header_time;
166         /** Used for the last source pointer of an audio file. */
167         unsigned char *extra_src_buf;
168         /** Extra slices needed to store largest chunk + header. */
169         int num_extra_slices;
170         /** Contains the FEC-encoded data. */
171         unsigned char *enc_buf;
172         /** Maximal packet size. */
173         int mps;
174 };
175
176 /**
177  * Get the chunk time of the current audio file.
178  *
179  * \return A pointer to a struct containing the chunk time, or NULL,
180  * if currently no audio file is selected.
181  */
182 struct timeval *vss_chunk_time(void)
183 {
184         if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
185                         mmd->afd.afhi.chunk_tv.tv_usec == 0)
186                 return NULL;
187         return &mmd->afd.afhi.chunk_tv;
188 }
189
190 /**
191  * Write a fec header to a buffer.
192  *
193  * \param buf The buffer to write to.
194  * \param h The fec header to write.
195  */
196 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
197 {
198         char *buf = (char *)fc->enc_buf;
199         struct fec_group *g = &fc->group;
200         struct fec_client_parms *p = fc->fcp;
201
202         write_u32(buf, FEC_MAGIC);
203
204         write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
205         write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
206         write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
207
208         write_u32(buf + 10, g->num);
209         write_u32(buf + 14, g->bytes);
210
211         write_u8(buf + 18, fc->current_slice_num);
212         write_u16(buf + 20, fc->mps - FEC_HEADER_SIZE);
213         write_u8(buf + 22, g->first_chunk? 0 : 1);
214         write_u8(buf + 23, vsst->header_len? 1 : 0);
215         memset(buf + 24, 0, 7);
216 }
217
218 static int need_audio_header(struct fec_client *fc, struct vss_task *vsst)
219 {
220         if (!mmd->current_chunk) {
221                 tv_add(now, &vsst->header_interval, &fc->next_header_time);
222                 return 0;
223         }
224         if (!vsst->header_buf)
225                 return 0;
226         if (!vsst->header_len)
227                 return 0;
228         if (fc->group.num && tv_diff(&fc->next_header_time, now, NULL) > 0)
229                 return 0;
230         tv_add(now, &vsst->header_interval, &fc->next_header_time);
231         return 1;
232 }
233
234 static int num_slices(long unsigned bytes, int mps, int rs)
235 {
236         int m = mps - FEC_HEADER_SIZE;
237         int ret;
238
239         assert(m > 0);
240         assert(rs > 0);
241         ret = DIV_ROUND_UP(bytes, m);
242         if (ret + rs > 255)
243                 return -E_BAD_CT;
244         return ret;
245 }
246
247 /* set group start and group duration */
248 static void set_group_timing(struct fec_client *fc, struct fec_group *g)
249 {
250         struct timeval *chunk_tv = vss_chunk_time();
251
252         tv_scale(g->num_chunks, chunk_tv, &g->duration);
253         tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
254                 &g->duration, &g->slice_duration);
255         PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
256                 tv2ms(&g->duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
257 }
258
259 static int initialize_fec_client(struct fec_client *fc, struct vss_task *vsst)
260 {
261         int k, n, ret, mps;
262         int hs, ds, rs; /* header/data/redundant slices */
263         struct fec_client_parms *fcp = fc->fcp;
264
265         /* set mps */
266         if (fcp->init_fec) {
267                 /*
268                  * Set the maximum slice size to the Maximum Packet Size if the
269                  * transport protocol allows to determine this value. The user
270                  * can specify a slice size up to this value.
271                  */
272                 ret = fcp->init_fec(fc->sc);
273                 if (ret < 0)
274                         return ret;
275                 mps = ret;
276         } else
277                 mps = generic_max_transport_msg_size(fc->sc->fd);
278         if (mps <= FEC_HEADER_SIZE)
279                 return -ERRNO_TO_PARA_ERROR(EINVAL);
280
281         rs = fc->fcp->slices_per_group - fc->fcp->data_slices_per_group;
282         ret = num_slices(vsst->header_len, mps, rs);
283         if (ret < 0)
284                 goto err;
285         hs = ret;
286         ret = num_slices(afh_get_largest_chunk_size(&mmd->afd.afhi),
287                 mps, rs);
288         if (ret < 0)
289                 goto err;
290         ds = ret;
291         k = ret + ds;
292         if (k < fc->fcp->data_slices_per_group)
293                 k = fc->fcp->data_slices_per_group;
294         n = k + rs;
295         PARA_CRIT_LOG("hs: %d, ds: %d, rs: %d, k: %d, n: %d\n", hs, ds, rs, k, n);
296         fec_free(fc->parms);
297         ret = fec_new(k, n, &fc->parms);
298         if (ret < 0)
299                 return ret;
300         fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
301         PARA_NOTICE_LOG("fec parms %d:%d:%d (%d extra slices)\n",
302                 mps, k, n, fc->num_extra_slices);
303         fc->src_data = para_realloc(fc->src_data, k * sizeof(char *));
304         fc->enc_buf = para_realloc(fc->enc_buf, mps);
305         memset(fc->enc_buf, 0, mps);
306         fc->extra_src_buf = para_realloc(fc->extra_src_buf, mps);
307         memset(fc->extra_src_buf, 0, mps);
308
309         fc->mps = mps;
310         fc->state = FEC_STATE_READY_TO_RUN;
311         fc->next_header_time.tv_sec = 0;
312         fc->stream_start = *now;
313         fc->first_stream_chunk = mmd->current_chunk;
314         return 1;
315 err:
316         fec_free(fc->parms);
317         return ret;
318 }
319
320 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
321 {
322         int ret, i, k, n, data_slices;
323         size_t len;
324         const char *buf, *start_buf;
325         struct fec_group *g = &fc->group;
326         unsigned slice_bytes;
327         uint32_t max_data_size;
328
329         if (fc->state == FEC_STATE_NONE) {
330                 ret = initialize_fec_client(fc, vsst);
331                 if (ret < 0)
332                         return ret;
333                 g->first_chunk = mmd->current_chunk;
334                 g->num = 0;
335                 g->start = *now;
336                 
337         } else {
338                 struct timeval tmp;
339                 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
340                         return 0;
341                 /*
342                  * Start and duration of this group depend only on the previous
343                  * group. Compute the new group start as g->start += g->duration.
344                  */
345                 tmp = g->start;
346                 tv_add(&tmp, &g->duration, &g->start);
347                 set_group_timing(fc, g);
348                 g->first_chunk += g->num_chunks;
349                 g->num++;
350         }
351         slice_bytes = fc->mps - FEC_HEADER_SIZE;
352         PARA_CRIT_LOG("slice_bytes: %d\n", slice_bytes);
353         k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
354         n = fc->fcp->slices_per_group + fc->num_extra_slices;
355         PARA_CRIT_LOG("k: %d, n: %d\n", k, n);
356         if (need_audio_header(fc, vsst)) {
357                 ret = num_slices(vsst->header_len, slice_bytes, n - k);
358                 if (ret < 0)
359                         return ret;
360                 g->num_header_slices = ret;
361         } else
362                 g->num_header_slices = 0;
363         afh_get_chunk(g->first_chunk, &mmd->afd.afhi, vsst->map, &start_buf,
364                 &len);
365         data_slices = k - g->num_header_slices;
366         assert(data_slices);
367         max_data_size = slice_bytes * data_slices;
368         g->bytes = 0;
369         for (i = g->first_chunk; i < mmd->afd.afhi.chunks_total; i++) {
370                 afh_get_chunk(i, &mmd->afd.afhi, vsst->map, &buf, &len);
371                 if (g->bytes + len > max_data_size)
372                         break;
373                 g->bytes += len;
374         }
375         g->num_chunks = i - g->first_chunk;
376         assert(g->num_chunks);
377         fc->current_slice_num = 0;
378         if (g->num == 0)
379                 set_group_timing(fc, g);
380
381         /* setup header slices */
382         buf = vsst->header_buf;
383         for (i = 0; i < g->num_header_slices; i++) {
384                 fc->src_data[i] = (const unsigned char *)buf;
385                 buf += slice_bytes;
386         }
387
388         /* setup data slices */
389         buf = start_buf;
390         for (i = g->num_header_slices; i < k; i++) {
391                 if (buf + slice_bytes > vsst->map + mmd->size)
392                         /*
393                          * Can not use the memory mapped audio file for this
394                          * slice as it goes beyond the map. This slice will not
395                          * be fully used.
396                          */
397                         break;
398                 fc->src_data[i] = (const unsigned char *)buf;
399                 buf += slice_bytes;
400         }
401         if (i < k) {
402                 uint32_t payload_size = vsst->map + mmd->size - buf;
403                 memcpy(fc->extra_src_buf, buf, payload_size);
404                 fc->src_data[i] = fc->extra_src_buf;
405                 i++;
406                 /* use arbitrary data for all remaining slices */
407                 buf = vsst->map;
408                 for (; i < k; i++)
409                         fc->src_data[i] = (const unsigned char *)buf;
410         }
411         PARA_DEBUG_LOG("FEC group %d: %d chunks (%d - %d), "
412                 "%d header slices, %d data slices\n",
413                 g->num, g->num_chunks, g->first_chunk,
414                 g->first_chunk + g->num_chunks - 1,
415                 g->num_header_slices, data_slices
416         );
417         return 1;
418 }
419
420 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
421 {
422         if (fc->state == FEC_STATE_NONE || fc->current_slice_num
423                         == fc->fcp->slices_per_group + fc->num_extra_slices) {
424                 int ret = setup_next_fec_group(fc, vsst);
425                 if (ret == 0)
426                         return 0;
427                 if (ret < 0) {
428                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
429                         PARA_ERROR_LOG("FEC client temporarily disabled\n");
430                         fc->state = FEC_STATE_DISABLED;
431                         return ret;
432                 }
433         }
434         write_fec_header(fc, vsst);
435         fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
436                 fc->current_slice_num, fc->mps - FEC_HEADER_SIZE);
437         return 1;
438 }
439
440 /**
441  * Return a buffer that marks the end of the stream.
442  *
443  * \param buf Result pointer.
444  * \return The length of the eof buffer.
445  *
446  * This is used for (multicast) udp streaming where closing the socket on the
447  * sender might not give rise to an eof condition at the peer.
448  */
449 size_t vss_get_fec_eof_packet(const char **buf)
450 {
451         static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
452         *buf = fec_eof_packet;
453         return FEC_HEADER_SIZE;
454 }
455
456 /**
457  * Add one entry to the list of active fec clients.
458  *
459  * \param sc  Generic sender_client data of the transport layer.
460  * \param fcp FEC parameters as supplied by the transport layer.
461  *
462  * \return Newly allocated fec_client struct.
463  */
464 struct fec_client *vss_add_fec_client(struct sender_client *sc,
465                                       struct fec_client_parms *fcp)
466 {
467         struct fec_client *fc = para_calloc(sizeof(*fc));
468
469         fc->sc  = sc;
470         fc->fcp = fcp;
471         para_list_add(&fc->node, &fec_client_list);
472         return fc;
473 }
474
475 /**
476  * Remove one entry from the list of active fec clients.
477  *
478  * \param fc The client to be removed.
479  */
480 void vss_del_fec_client(struct fec_client *fc)
481 {
482         list_del(&fc->node);
483         free(fc->src_data);
484         free(fc->enc_buf);
485         free(fc->extra_src_buf);
486         fec_free(fc->parms);
487         free(fc);
488 }
489
490 /*
491  * Compute if/when next slice is due. If it isn't due yet and \a diff is
492  * not \p Null, compute the time difference next - now, where
493  *
494  *      next = stream_start + (first_group_chunk - first_stream_chunk)
495  *              * chunk_time + slice_num * slice_time
496  */
497 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
498 {
499         struct timeval tmp, next;
500         int ret;
501
502         if (fc->state == FEC_STATE_NONE)
503                 return 1;
504         tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
505         tv_add(&tmp, &fc->group.start, &next);
506         ret = tv_diff(&next, now, diff);
507         return ret < 0? 1 : 0;
508 }
509
510 static void compute_slice_timeout(struct timeval *timeout)
511 {
512         struct fec_client *fc;
513
514         list_for_each_entry(fc, &fec_client_list, node) {
515                 struct timeval diff;
516
517                 if (fc->state != FEC_STATE_READY_TO_RUN)
518                         continue;
519                 if (next_slice_is_due(fc, &diff)) {
520                         timeout->tv_sec = 0;
521                         timeout->tv_usec = 0;
522                         return;
523                 }
524                 /* timeout = min(timeout, diff) */
525                 if (tv_diff(&diff, timeout, NULL) < 0)
526                         *timeout = diff;
527         }
528 }
529
530 static void set_eof_barrier(struct vss_task *vsst)
531 {
532         struct fec_client *fc;
533         struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
534
535         if (!chunk_tv)
536                 goto out;
537         list_for_each_entry(fc, &fec_client_list, node) {
538                 struct timeval group_duration;
539
540                 if (fc->state != FEC_STATE_READY_TO_RUN)
541                         continue;
542                 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
543                 if (tv_diff(&timeout, &group_duration, NULL) < 0)
544                         timeout = group_duration;
545         }
546 out:
547         tv_add(now, &timeout, &vsst->eof_barrier);
548 }
549
550 /**
551  * Check if vss status flag \a P (playing) is set.
552  *
553  * \return Greater than zero if playing, zero otherwise.
554  *
555  */
556 unsigned int vss_playing(void)
557 {
558         return mmd->new_vss_status_flags & VSS_PLAYING;
559 }
560
561 /**
562  * Check if the \a N (next) status flag is set.
563  *
564  * \return Greater than zero if set, zero if not.
565  *
566  */
567 unsigned int vss_next(void)
568 {
569         return mmd->new_vss_status_flags & VSS_NEXT;
570 }
571
572 /**
573  * Check if a reposition request is pending.
574  *
575  * \return Greater than zero if true, zero otherwise.
576  *
577  */
578 unsigned int vss_repos(void)
579 {
580         return mmd->new_vss_status_flags & VSS_REPOS;
581 }
582
583 /**
584  * Check if the vss is currently paused.
585  *
586  * \return Greater than zero if paused, zero otherwise.
587  *
588  */
589 unsigned int vss_paused(void)
590 {
591         return !(mmd->new_vss_status_flags & VSS_NEXT)
592                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
593 }
594
595 /**
596  * Check if the vss is currently stopped.
597  *
598  * \return Greater than zero if paused, zero otherwise.
599  *
600  */
601 unsigned int vss_stopped(void)
602 {
603         return (mmd->new_vss_status_flags & VSS_NEXT)
604                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
605 }
606
607 static int chk_barrier(const char *bname, const struct timeval *barrier,
608                 struct timeval *diff, int print_log)
609 {
610         long ms;
611
612         if (tv_diff(now, barrier, diff) > 0)
613                 return 1;
614         ms = tv2ms(diff);
615         if (print_log && ms)
616                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
617         return -1;
618 }
619
620 /*
621  * != NULL: timeout for next chunk
622  * NULL: nothing to do
623  */
624 static struct timeval *vss_compute_timeout(struct vss_task *vsst)
625 {
626         static struct timeval the_timeout;
627         struct timeval next_chunk;
628
629         if (vss_next() && vsst->map) {
630                 /* only sleep a bit, nec*/
631                 the_timeout.tv_sec = 0;
632                 the_timeout.tv_usec = 100;
633                 return &the_timeout;
634         }
635         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
636                         &the_timeout, 1) < 0)
637                 return &the_timeout;
638         if (chk_barrier("eof", &vsst->eof_barrier, &the_timeout, 1) < 0)
639                 return &the_timeout;
640         if (chk_barrier("data send", &vsst->data_send_barrier,
641                         &the_timeout, 1) < 0)
642                 return &the_timeout;
643         if (!vss_playing() || !vsst->map)
644                 return NULL;
645         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
646                 &mmd->stream_start, &next_chunk);
647         if (chk_barrier("chunk", &next_chunk, &the_timeout, 0) >= 0) {
648                 /* chunk is due or bof */
649                 the_timeout.tv_sec = 0;
650                 the_timeout.tv_usec = 0;
651                 return &the_timeout;
652         }
653         /* compute min of current timeout and next slice time */
654         compute_slice_timeout(&the_timeout);
655         return &the_timeout;
656 }
657
658 static void vss_eof(struct vss_task *vsst)
659 {
660
661         if (!vsst->map)
662                 return;
663         if (mmd->new_vss_status_flags & VSS_NOMORE)
664                 mmd->new_vss_status_flags = VSS_NEXT;
665         set_eof_barrier(vsst);
666         para_munmap(vsst->map, mmd->size);
667         vsst->map = NULL;
668         mmd->chunks_sent = 0;
669         //mmd->offset = 0;
670         mmd->afd.afhi.seconds_total = 0;
671         mmd->afd.afhi.chunk_tv.tv_sec = 0;
672         mmd->afd.afhi.chunk_tv.tv_usec = 0;
673         free(mmd->afd.afhi.chunk_table);
674         mmd->afd.afhi.chunk_table = NULL;
675         mmd->mtime = 0;
676         mmd->size = 0;
677         mmd->events++;
678 }
679
680 static int need_to_request_new_audio_file(struct vss_task *vsst)
681 {
682         struct timeval diff;
683
684         if (vsst->map) /* have audio file */
685                 return 0;
686         if (!vss_playing()) /* don't need one */
687                 return 0;
688         if (mmd->new_vss_status_flags & VSS_NOMORE)
689                 return 0;
690         if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
691                 return 0;
692         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
693                         &diff, 1) < 0)
694                 return 0;
695         return 1;
696 }
697
698 static void set_mmd_offset(void)
699 {
700         struct timeval offset;
701         tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
702         mmd->offset = tv2ms(&offset);
703 }
704
705 /**
706  * Compute the timeout for the main select-loop of the scheduler.
707  *
708  * \param s Pointer to the server scheduler.
709  * \param t Pointer to the vss task structure.
710  *
711  * Before the timeout is computed, the current vss status flags are evaluated
712  * and acted upon by calling appropriate functions from the lower layers.
713  * Possible actions include
714  *
715  *      - request a new audio file from afs,
716  *      - shutdown of all senders (stop/pause command),
717  *      - reposition the stream (ff/jmp command).
718  */
719 static void vss_pre_select(struct sched *s, struct task *t)
720 {
721         int i;
722         struct timeval *tv;
723         struct vss_task *vsst = container_of(t, struct vss_task, task);
724
725         if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
726                 struct fec_client *fc, *tmp;
727                 for (i = 0; senders[i].name; i++)
728                         if (senders[i].shutdown_clients)
729                                 senders[i].shutdown_clients();
730                 list_for_each_entry_safe(fc, tmp, &fec_client_list, node)
731                         fc->state = FEC_STATE_NONE;
732                 mmd->stream_start.tv_sec = 0;
733                 mmd->stream_start.tv_usec = 0;
734         }
735         if (vss_next())
736                 vss_eof(vsst);
737         else if (vss_paused()) {
738                 if (mmd->chunks_sent)
739                         set_eof_barrier(vsst);
740                 mmd->chunks_sent = 0;
741         } else if (vss_repos()) {
742                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
743                 set_eof_barrier(vsst);
744                 mmd->chunks_sent = 0;
745                 mmd->current_chunk = mmd->repos_request;
746                 mmd->new_vss_status_flags &= ~VSS_REPOS;
747                 set_mmd_offset();
748         }
749         if (need_to_request_new_audio_file(vsst)) {
750                 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
751                 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
752                 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
753         } else
754                 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
755         for (i = 0; senders[i].name; i++) {
756                 if (!senders[i].pre_select)
757                         continue;
758                 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
759         }
760         tv = vss_compute_timeout(vsst);
761         if (tv)
762                 sched_request_timeout(tv, s);
763 }
764
765 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
766 {
767         char control[255], buf[8];
768         struct msghdr msg = {.msg_iov = NULL};
769         struct cmsghdr *cmsg;
770         struct iovec iov;
771         int ret = 0;
772
773         *fd = -1;
774         iov.iov_base = buf;
775         iov.iov_len = sizeof(buf);
776         msg.msg_iov = &iov;
777         msg.msg_iovlen = 1;
778         msg.msg_control = control;
779         msg.msg_controllen = sizeof(control);
780         memset(buf, 0, sizeof(buf));
781         ret = recvmsg(afs_socket, &msg, 0);
782         if (ret < 0)
783                 return -ERRNO_TO_PARA_ERROR(errno);
784         if (iov.iov_len != sizeof(buf))
785                 return -E_AFS_SHORT_READ;
786         *code = *(uint32_t*)buf;
787         *data =  *(uint32_t*)(buf + 4);
788         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
789                 if (cmsg->cmsg_level != SOL_SOCKET
790                         || cmsg->cmsg_type != SCM_RIGHTS)
791                         continue;
792                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
793                         continue;
794                 *fd = *(int *)CMSG_DATA(cmsg);
795         }
796         return 1;
797 }
798
799 static void recv_afs_result(struct vss_task *vsst, fd_set *rfds)
800 {
801         int ret, passed_fd, shmid;
802         uint32_t afs_code = 0, afs_data = 0;
803         struct stat statbuf;
804
805         if (!FD_ISSET(vsst->afs_socket, rfds))
806                 return;
807         ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
808         if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
809                 return;
810         if (ret < 0)
811                 goto err;
812         vsst->afsss = AFS_SOCKET_READY;
813         PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
814                 afs_data);
815         ret = -E_NOFD;
816         if (afs_code != NEXT_AUDIO_FILE)
817                 goto err;
818         if (passed_fd < 0)
819                 goto err;
820         shmid = afs_data;
821         ret = load_afd(shmid, &mmd->afd);
822         if (ret < 0)
823                 goto err;
824         shm_destroy(shmid);
825         ret = fstat(passed_fd, &statbuf);
826         if (ret < 0) {
827                 PARA_ERROR_LOG("fstat error:\n");
828                 ret = -ERRNO_TO_PARA_ERROR(errno);
829                 goto err;
830         }
831         mmd->size = statbuf.st_size;
832         mmd->mtime = statbuf.st_mtime;
833         ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
834                 0, &vsst->map);
835         if (ret < 0)
836                 goto err;
837         close(passed_fd);
838         mmd->chunks_sent = 0;
839         mmd->current_chunk = 0;
840         mmd->offset = 0;
841         mmd->events++;
842         mmd->num_played++;
843         mmd->new_vss_status_flags &= (~VSS_NEXT);
844         afh_get_header(&mmd->afd.afhi, vsst->map, &vsst->header_buf,
845                 &vsst->header_len);
846         return;
847 err:
848         free(mmd->afd.afhi.chunk_table);
849         if (passed_fd >= 0)
850                 close(passed_fd);
851         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
852         mmd->new_vss_status_flags = VSS_NEXT;
853 }
854
855 /**
856  * Main sending function.
857  *
858  * This function gets called from vss_post_select(). It checks whether the next
859  * chunk of data should be pushed out. It obtains a pointer to the data to be
860  * sent out as well as its length from mmd->afd.afhi. This information is then
861  * passed to each supported sender's send() function as well as to the send()
862  * functions of each registered fec client.
863  */
864 static void vss_send(struct vss_task *vsst)
865 {
866         int i, fec_active = 0;
867         struct timeval due;
868         struct fec_client *fc, *tmp_fc;
869
870         if (!vsst->map || !vss_playing())
871                 return;
872         if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
873                 return;
874         if (chk_barrier("data send", &vsst->data_send_barrier,
875                         &due, 1) < 0)
876                 return;
877         list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
878                 if (fc->state == FEC_STATE_DISABLED)
879                         continue;
880                 if (!next_slice_is_due(fc, NULL)) {
881                         fec_active = 1;
882                         continue;
883                 }
884                 if (compute_next_fec_slice(fc, vsst) <= 0)
885                         continue;
886                 PARA_DEBUG_LOG("sending %d:%d (%u bytes)\n", fc->group.num,
887                         fc->current_slice_num, fc->mps);
888                 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf, fc->mps);
889                 fc->current_slice_num++;
890                 fec_active = 1;
891         }
892         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
893                 if (!fec_active)
894                         mmd->new_vss_status_flags |= VSS_NEXT;
895                 return;
896         }
897         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
898                 &mmd->stream_start, &due);
899         if (tv_diff(&due, now, NULL) <= 0) {
900                 const char *buf;
901                 size_t len;
902
903                 if (!mmd->chunks_sent) {
904                         mmd->stream_start = *now;
905                         mmd->events++;
906                         set_mmd_offset();
907                 }
908                 /*
909                  * We call the send function also in case of empty chunks as
910                  * they might have still some data queued which can be sent in
911                  * this case.
912                  */
913                 afh_get_chunk(mmd->current_chunk, &mmd->afd.afhi, vsst->map,
914                         &buf, &len);
915                 for (i = 0; senders[i].name; i++) {
916                         if (!senders[i].send)
917                                 continue;
918                         senders[i].send(mmd->current_chunk, mmd->chunks_sent,
919                                 buf, len, vsst->header_buf, vsst->header_len);
920                 }
921                 mmd->chunks_sent++;
922                 mmd->current_chunk++;
923         }
924 }
925
926 static void vss_post_select(struct sched *s, struct task *t)
927 {
928         int ret, i;
929         struct vss_task *vsst = container_of(t, struct vss_task, task);
930
931
932         if (mmd->sender_cmd_data.cmd_num >= 0) {
933                 int num = mmd->sender_cmd_data.cmd_num,
934                         sender_num = mmd->sender_cmd_data.sender_num;
935
936                 if (senders[sender_num].client_cmds[num]) {
937                         ret = senders[sender_num].client_cmds[num]
938                                 (&mmd->sender_cmd_data);
939                         if (ret < 0)
940                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
941                 }
942                 mmd->sender_cmd_data.cmd_num = -1;
943         }
944         if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
945                 recv_afs_result(vsst, &s->rfds);
946         else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
947                 PARA_NOTICE_LOG("requesting new fd from afs\n");
948                 ret = send_buffer(vsst->afs_socket, "new");
949                 if (ret < 0)
950                         PARA_CRIT_LOG("%s\n", para_strerror(-ret));
951                 else
952                         vsst->afsss = AFS_SOCKET_AFD_PENDING;
953         }
954         for (i = 0; senders[i].name; i++) {
955                 if (!senders[i].post_select)
956                         continue;
957                 senders[i].post_select(&s->rfds, &s->wfds);
958         }
959         if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
960                         (vss_next() && vss_playing()))
961                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
962         vss_send(vsst);
963 }
964
965 /**
966  * Initialize the virtual streaming system task.
967  *
968  * \param afs_socket The fd for communication with afs.
969  *
970  * This also initializes all supported senders and starts streaming
971  * if the --autoplay command line flag was given.
972  */
973 void init_vss_task(int afs_socket)
974 {
975         static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
976         int i;
977         char *hn = para_hostname(), *home = para_homedir();
978         long unsigned announce_time = conf.announce_time_arg > 0?
979                         conf.announce_time_arg : 300,
980                 autoplay_delay = conf.autoplay_delay_arg > 0?
981                         conf.autoplay_delay_arg : 0;
982         vsst->header_interval.tv_sec = 5; /* should this be configurable? */
983         vsst->afs_socket = afs_socket;
984         vsst->task.pre_select = vss_pre_select;
985         vsst->task.post_select = vss_post_select;
986         ms2tv(announce_time, &vsst->announce_tv);
987         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
988         INIT_LIST_HEAD(&fec_client_list);
989         for (i = 0; senders[i].name; i++) {
990                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
991                 senders[i].init(&senders[i]);
992         }
993         free(hn);
994         free(home);
995         mmd->sender_cmd_data.cmd_num = -1;
996         if (conf.autoplay_given) {
997                 struct timeval tmp;
998                 mmd->vss_status_flags |= VSS_PLAYING;
999                 mmd->new_vss_status_flags |= VSS_PLAYING;
1000                 ms2tv(autoplay_delay, &tmp);
1001                 tv_add(now, &tmp, &vsst->autoplay_barrier);
1002                 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1003                         &vsst->data_send_barrier);
1004         }
1005         register_task(&vsst->task);
1006 }