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