vss: unify calls to the FEC layer
[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 /**
135  * Describes one connected FEC client.
136  */
137 struct fec_client {
138         /** If negative, this client is temporarily disabled. */
139         int error;
140         /** Whether the sender client is ready to push out data. */
141         bool ready;
142         /** The connected sender client (transport layer). */
143         struct sender_client *sc;
144         /** Parameters requested by the client. */
145         struct fec_client_parms *fcp;
146         /** Used by the core FEC code. */
147         struct fec_parms *parms;
148         /** The position of this client in the fec client list. */
149         struct list_head node;
150         /** When the first slice for this client was sent. */
151         struct timeval stream_start;
152         /** The first chunk sent to this FEC client. */
153         int first_stream_chunk;
154         /** Describes the current group. */
155         struct fec_group group;
156         /** The current slice. */
157         uint8_t current_slice_num;
158         /** The data to be FEC-encoded (point to a region within the mapped audio file). */
159         const unsigned char **src_data;
160         /** Last time an audio  header was sent. */
161         struct timeval next_header_time;
162         /** Used for the last source pointer of an audio file. */
163         unsigned char *extra_src_buf;
164         /** Extra slices needed to store largest chunk + header. */
165         int num_extra_slices;
166         /** Contains the FEC-encoded data. */
167         unsigned char *enc_buf;
168         /** Pointer obtained from sender when the client is added. */
169         void *private_data;
170 };
171
172 /**
173  * Get the chunk time of the current audio file.
174  *
175  * \return A pointer to a struct containing the chunk time, or NULL,
176  * if currently no audio file is selected.
177  */
178 struct timeval *vss_chunk_time(void)
179 {
180         if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
181                         mmd->afd.afhi.chunk_tv.tv_usec == 0)
182                 return NULL;
183         return &mmd->afd.afhi.chunk_tv;
184 }
185
186 /**
187  * Write a fec header to a buffer.
188  *
189  * \param buf The buffer to write to.
190  * \param h The fec header to write.
191  */
192 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
193 {
194         char *buf = (char *)fc->enc_buf;
195         struct fec_group *g = &fc->group;
196         struct fec_client_parms *p = fc->fcp;
197
198         write_u32(buf, FEC_MAGIC);
199
200         write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
201         write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
202         write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
203
204         write_u32(buf + 10, g->num);
205         write_u32(buf + 14, g->bytes);
206
207         write_u8(buf + 18, fc->current_slice_num);
208         write_u16(buf + 20, p->max_slice_bytes - FEC_HEADER_SIZE);
209         write_u8(buf + 22, g->first_chunk? 0 : 1);
210         write_u8(buf + 23, vsst->header_len? 1 : 0);
211         memset(buf + 24, 0, 7);
212 }
213
214 static int need_audio_header(struct fec_client *fc, struct vss_task *vsst)
215 {
216         if (!mmd->current_chunk) {
217                 tv_add(now, &vsst->header_interval, &fc->next_header_time);
218                 return 0;
219         }
220         if (!vsst->header_buf)
221                 return 0;
222         if (!vsst->header_len)
223                 return 0;
224         if (fc->group.num && tv_diff(&fc->next_header_time, now, NULL) > 0)
225                 return 0;
226         tv_add(now, &vsst->header_interval, &fc->next_header_time);
227         return 1;
228 }
229
230 static int num_slices(long unsigned bytes, struct fec_client *fc, uint8_t *result)
231 {
232         unsigned long m = fc->fcp->max_slice_bytes - FEC_HEADER_SIZE;
233         unsigned rv, redundant_slices = fc->fcp->slices_per_group
234                 - fc->fcp->data_slices_per_group;
235
236         if (!m)
237                 return -E_BAD_CT;
238         rv = (bytes + m - 1) / m;
239         if (rv + redundant_slices > 255)
240                 return -E_BAD_CT;
241         *result = rv;
242         return 1;
243 }
244
245 /* set group start and group duration */
246 static void set_group_timing(struct fec_client *fc, struct fec_group *g)
247 {
248         struct timeval *chunk_tv = vss_chunk_time();
249
250         tv_scale(g->num_chunks, chunk_tv, &g->duration);
251         tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
252                 &g->duration, &g->slice_duration);
253         PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
254                 tv2ms(&g->duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
255 }
256
257 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
258 {
259         int ret, i, k, data_slices;
260         size_t len;
261         const char *buf, *start_buf;
262         struct fec_group *g = &fc->group;
263         unsigned slice_bytes = fc->fcp->max_slice_bytes - FEC_HEADER_SIZE;
264         uint32_t max_data_size;
265
266         if (fc->first_stream_chunk < 0) {
267                 uint8_t hs, ds; /* needed header/data slices */
268                 uint8_t rs = fc->fcp->slices_per_group
269                         - fc->fcp->data_slices_per_group; /* redundant slices */
270                 int n;
271
272                 ret = num_slices(vsst->header_len, fc, &hs);
273                 if (ret < 0)
274                         return ret;
275                 ret = num_slices(afh_get_largest_chunk_size(&mmd->afd.afhi),
276                         fc, &ds);
277                 if (ret < 0)
278                         return ret;
279                 k = (int)hs + ds;
280                 if (k > 255)
281                         return -E_BAD_CT;
282                 if (k < fc->fcp->data_slices_per_group)
283                         k = fc->fcp->data_slices_per_group;
284                 n = k + rs;
285                 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
286                 PARA_NOTICE_LOG("fec parms %d:%d:%d (%d extra slices)\n",
287                         slice_bytes, k, n, fc->num_extra_slices);
288                 fec_free(fc->parms);
289                 fc->src_data = para_realloc(fc->src_data, k * sizeof(char *));
290                 ret = fec_new(k, n, &fc->parms);
291                 if (ret < 0)
292                         return ret;
293                 fc->stream_start = *now;
294                 fc->first_stream_chunk = mmd->current_chunk;
295                 g->first_chunk = mmd->current_chunk;
296                 g->num = 0;
297                 g->start = *now;
298         } else {
299                 struct timeval tmp;
300                 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
301                         return 0;
302                 /*
303                  * Start and duration of this group depend only on the previous
304                  * group. Compute the new group start as g->start += g->duration.
305                  */
306                 tmp = g->start;
307                 tv_add(&tmp, &g->duration, &g->start);
308                 k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
309                 set_group_timing(fc, g);
310                 g->first_chunk += g->num_chunks;
311                 g->num++;
312         }
313         if (need_audio_header(fc, vsst)) {
314                 ret = num_slices(vsst->header_len, fc, &g->num_header_slices);
315                 if (ret < 0)
316                         return ret;
317         } else
318                 g->num_header_slices = 0;
319         afh_get_chunk(g->first_chunk, &mmd->afd.afhi, vsst->map, &start_buf,
320                 &len);
321         data_slices = k - g->num_header_slices;
322         assert(data_slices);
323         max_data_size = slice_bytes * data_slices;
324         g->bytes = 0;
325         for (i = g->first_chunk; i < mmd->afd.afhi.chunks_total; i++) {
326                 afh_get_chunk(i, &mmd->afd.afhi, vsst->map, &buf, &len);
327                 if (g->bytes + len > max_data_size)
328                         break;
329                 g->bytes += len;
330         }
331         g->num_chunks = i - g->first_chunk;
332         assert(g->num_chunks);
333         fc->current_slice_num = 0;
334         if (g->num == 0)
335                 set_group_timing(fc, g);
336
337         /* setup header slices */
338         buf = vsst->header_buf;
339         for (i = 0; i < g->num_header_slices; i++) {
340                 fc->src_data[i] = (const unsigned char *)buf;
341                 buf += slice_bytes;
342         }
343
344         /* setup data slices */
345         buf = start_buf;
346         for (i = g->num_header_slices; i < k; i++) {
347                 if (buf + slice_bytes > vsst->map + mmd->size)
348                         /*
349                          * Can not use the memory mapped audio file for this
350                          * slice as it goes beyond the map. This slice will not
351                          * be fully used.
352                          */
353                         break;
354                 fc->src_data[i] = (const unsigned char *)buf;
355                 buf += slice_bytes;
356         }
357         if (i < k) {
358                 uint32_t payload_size = vsst->map + mmd->size - buf;
359                 memcpy(fc->extra_src_buf, buf, payload_size);
360                 fc->src_data[i] = fc->extra_src_buf;
361                 i++;
362                 /* use arbitrary data for all remaining slices */
363                 buf = vsst->map;
364                 for (; i < k; i++)
365                         fc->src_data[i] = (const unsigned char *)buf;
366         }
367         PARA_DEBUG_LOG("FEC group %d: %d chunks (%d - %d), "
368                 "%d header slices, %d data slices\n",
369                 g->num, g->num_chunks, g->first_chunk,
370                 g->first_chunk + g->num_chunks - 1,
371                 g->num_header_slices, data_slices
372         );
373         return 1;
374 }
375
376 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
377 {
378         assert(fc->error >= 0);
379         if (fc->first_stream_chunk < 0 || fc->current_slice_num
380                         == fc->fcp->slices_per_group + fc->num_extra_slices) {
381                 int ret = setup_next_fec_group(fc, vsst);
382                 if (ret == 0)
383                         return 0;
384                 if (ret < 0) {
385                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
386                         PARA_ERROR_LOG("FEC client temporarily disabled\n");
387                         fc->error = ret;
388                         return fc->error;
389                 }
390         }
391         write_fec_header(fc, vsst);
392         fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
393                 fc->current_slice_num,
394                 fc->fcp->max_slice_bytes - FEC_HEADER_SIZE);
395         return 1;
396 }
397
398 /**
399  * Return a buffer that marks the end of the stream.
400  *
401  * \param buf Result pointer.
402  * \return The length of the eof buffer.
403  *
404  * This is used for (multicast) udp streaming where closing the socket on the
405  * sender might not give rise to an eof condition at the peer.
406  */
407 size_t vss_get_fec_eof_packet(const char **buf)
408 {
409         static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
410         *buf = fec_eof_packet;
411         return FEC_HEADER_SIZE;
412 }
413
414 /**
415  * Add one entry to the list of active fec clients.
416  *
417  * \param sc  Generic sender_client data of the transport layer.
418  * \param fcp FEC parameters as supplied by the transport layer.
419  *
420  * \return Newly allocated fec_client struct.
421  */
422 struct fec_client *vss_add_fec_client(struct sender_client *sc,
423                                       struct fec_client_parms *fcp)
424 {
425         struct fec_client *fc = para_calloc(sizeof(*fc));
426
427         fc->sc  = sc;
428         fc->fcp = fcp;
429         para_list_add(&fc->node, &fec_client_list);
430         return fc;
431 }
432
433 /**
434  * Remove one entry from the list of active fec clients.
435  *
436  * \param fc The client to be removed.
437  */
438 void vss_del_fec_client(struct fec_client *fc)
439 {
440         list_del(&fc->node);
441         free(fc->src_data);
442         free(fc->enc_buf);
443         free(fc->extra_src_buf);
444         fec_free(fc->parms);
445         free(fc);
446 }
447
448 /*
449  * Compute if/when next slice is due. If it isn't due yet and \a diff is
450  * not \p Null, compute the time difference next - now, where
451  *
452  *      next = stream_start + (first_group_chunk - first_stream_chunk)
453  *              * chunk_time + slice_num * slice_time
454  */
455 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
456 {
457         struct timeval tmp, next;
458         int ret;
459
460         if (fc->first_stream_chunk < 0)
461                 return 1;
462         tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
463         tv_add(&tmp, &fc->group.start, &next);
464         ret = tv_diff(&next, now, diff);
465         return ret < 0? 1 : 0;
466 }
467
468 static void compute_slice_timeout(struct timeval *timeout)
469 {
470         struct fec_client *fc;
471
472         assert(vss_playing());
473         list_for_each_entry(fc, &fec_client_list, node) {
474                 struct timeval diff;
475
476                 if (fc->error < 0)
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->error < 0)
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 /**
640  * Get the list of all supported audio formats.
641  *
642  * \return Aa space separated list of all supported audio formats
643  * It is not allocated at runtime, i.e. there is no need to free
644  * the returned string in the caller.
645  */
646 const char *supported_audio_formats(void)
647 {
648         return SUPPORTED_AUDIO_FORMATS;
649 }
650
651 static int need_to_request_new_audio_file(struct vss_task *vsst)
652 {
653         struct timeval diff;
654
655         if (vsst->map) /* have audio file */
656                 return 0;
657         if (!vss_playing()) /* don't need one */
658                 return 0;
659         if (mmd->new_vss_status_flags & VSS_NOMORE)
660                 return 0;
661         if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
662                 return 0;
663         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
664                         &diff, 1) < 0)
665                 return 0;
666         return 1;
667 }
668
669 static void set_mmd_offset(void)
670 {
671         struct timeval offset;
672         tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
673         mmd->offset = tv2ms(&offset);
674 }
675
676 /**
677  * Compute the timeout for the main select-loop of the scheduler.
678  *
679  * \param s Pointer to the server scheduler.
680  * \param t Pointer to the vss task structure.
681  *
682  * Before the timeout is computed, the current vss status flags are evaluated
683  * and acted upon by calling appropriate functions from the lower layers.
684  * Possible actions include
685  *
686  *      - request a new audio file from afs,
687  *      - shutdown of all senders (stop/pause command),
688  *      - reposition the stream (ff/jmp command).
689  */
690 static void vss_pre_select(struct sched *s, struct task *t)
691 {
692         int i;
693         struct timeval *tv, diff;
694         struct vss_task *vsst = container_of(t, struct vss_task, task);
695
696         if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
697                 struct fec_client *fc, *tmp;
698                 for (i = 0; senders[i].name; i++)
699                         if (senders[i].shutdown_clients)
700                                 senders[i].shutdown_clients();
701                 list_for_each_entry_safe(fc, tmp, &fec_client_list, node) {
702                         fc->first_stream_chunk = -1;
703                         fc->error = 0;
704                 }
705                 mmd->stream_start.tv_sec = 0;
706                 mmd->stream_start.tv_usec = 0;
707         }
708         if (vss_next())
709                 vss_eof(vsst);
710         else if (vss_paused()) {
711                 if (mmd->chunks_sent)
712                         set_eof_barrier(vsst);
713                 mmd->chunks_sent = 0;
714         } else if (vss_repos()) {
715                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
716                 set_eof_barrier(vsst);
717                 mmd->chunks_sent = 0;
718                 mmd->current_chunk = mmd->repos_request;
719                 mmd->new_vss_status_flags &= ~VSS_REPOS;
720                 set_mmd_offset();
721         }
722         if (need_to_request_new_audio_file(vsst)) {
723                 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
724                 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
725                 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
726         } else
727                 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
728         for (i = 0; senders[i].name; i++) {
729                 if (!senders[i].pre_select)
730                         continue;
731                 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
732         }
733         tv = vss_compute_timeout(vsst);
734         if (tv && tv_diff(tv, &s->timeout, &diff) < 0)
735                 s->timeout = *tv;
736 }
737
738 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
739 {
740         char control[255], buf[8];
741         struct msghdr msg = {.msg_iov = NULL};
742         struct cmsghdr *cmsg;
743         struct iovec iov;
744         int ret = 0;
745
746         *fd = -1;
747         iov.iov_base = buf;
748         iov.iov_len = sizeof(buf);
749         msg.msg_iov = &iov;
750         msg.msg_iovlen = 1;
751         msg.msg_control = control;
752         msg.msg_controllen = sizeof(control);
753         memset(buf, 0, sizeof(buf));
754         ret = recvmsg(afs_socket, &msg, 0);
755         if (ret < 0)
756                 return -ERRNO_TO_PARA_ERROR(errno);
757         if (iov.iov_len != sizeof(buf))
758                 return -E_AFS_SHORT_READ;
759         *code = *(uint32_t*)buf;
760         *data =  *(uint32_t*)(buf + 4);
761         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
762                 if (cmsg->cmsg_level != SOL_SOCKET
763                         || cmsg->cmsg_type != SCM_RIGHTS)
764                         continue;
765                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
766                         continue;
767                 *fd = *(int *)CMSG_DATA(cmsg);
768         }
769         return 1;
770 }
771
772 static void recv_afs_result(struct vss_task *vsst, fd_set *rfds)
773 {
774         int ret, passed_fd, shmid;
775         uint32_t afs_code = 0, afs_data = 0;
776         struct stat statbuf;
777
778         if (!FD_ISSET(vsst->afs_socket, rfds))
779                 return;
780         ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
781         if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
782                 return;
783         if (ret < 0)
784                 goto err;
785         vsst->afsss = AFS_SOCKET_READY;
786         PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
787                 afs_data);
788         ret = -E_NOFD;
789         if (afs_code != NEXT_AUDIO_FILE)
790                 goto err;
791         if (passed_fd < 0)
792                 goto err;
793         shmid = afs_data;
794         ret = load_afd(shmid, &mmd->afd);
795         if (ret < 0)
796                 goto err;
797         shm_destroy(shmid);
798         ret = fstat(passed_fd, &statbuf);
799         if (ret < 0) {
800                 PARA_ERROR_LOG("fstat error:\n");
801                 ret = -ERRNO_TO_PARA_ERROR(errno);
802                 goto err;
803         }
804         mmd->size = statbuf.st_size;
805         mmd->mtime = statbuf.st_mtime;
806         ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
807                 0, &vsst->map);
808         if (ret < 0)
809                 goto err;
810         close(passed_fd);
811         mmd->chunks_sent = 0;
812         mmd->current_chunk = 0;
813         mmd->offset = 0;
814         mmd->events++;
815         mmd->num_played++;
816         mmd->new_vss_status_flags &= (~VSS_NEXT);
817         afh_get_header(&mmd->afd.afhi, vsst->map, &vsst->header_buf,
818                 &vsst->header_len);
819         return;
820 err:
821         free(mmd->afd.afhi.chunk_table);
822         if (passed_fd >= 0)
823                 close(passed_fd);
824         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
825         mmd->new_vss_status_flags = VSS_NEXT;
826 }
827
828 static int initialize_fec_client(struct fec_client *fc)
829 {
830         int ret;
831         struct fec_client_parms *fcp = fc->fcp;
832
833         if (fcp->init_fec) {
834                 /*
835                  * Set the maximum slice size to the Maximum Packet Size if the
836                  * transport protocol allows to determine this value. The user
837                  * can specify a slice size up to this value.
838                  */
839                 ret = fcp->init_fec(fc->sc);
840                 if (ret < 0)
841                         return ret;
842                 if (!fcp->max_slice_bytes || fcp->max_slice_bytes > ret)
843                         fcp->max_slice_bytes = ret;
844         }
845         if (fcp->max_slice_bytes < FEC_HEADER_SIZE + fcp->data_slices_per_group)
846                 return -ERRNO_TO_PARA_ERROR(EINVAL);
847         ret = fec_new(fcp->data_slices_per_group, fcp->slices_per_group,
848                 &fc->parms);
849         if (ret < 0)
850                 goto err;
851         fc->first_stream_chunk = -1; /* stream not yet started */
852         fc->src_data = para_malloc(fc->fcp->slices_per_group * sizeof(char *));
853         fc->enc_buf = para_calloc(fc->fcp->max_slice_bytes);
854         fc->num_extra_slices = 0;
855         fc->extra_src_buf = para_calloc(fc->fcp->max_slice_bytes);
856         fc->next_header_time.tv_sec = 0;
857         fc->ready = true;
858         return 1;
859 err:
860         fec_free(fc->parms);
861         return ret;
862 }
863
864 /**
865  * Main sending function.
866  *
867  * This function gets called from vss_post_select(). It checks whether the next
868  * chunk of data should be pushed out. It obtains a pointer to the data to be
869  * sent out as well as its length from mmd->afd.afhi. This information is then
870  * passed to each supported sender's send() function as well as to the send()
871  * functions of each registered fec client.
872  */
873 static void vss_send(struct vss_task *vsst)
874 {
875         int ret, i, fec_active = 0;
876         struct timeval due;
877         struct fec_client *fc, *tmp_fc;
878
879         if (!vsst->map || !vss_playing())
880                 return;
881         if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
882                 return;
883         if (chk_barrier("data send", &vsst->data_send_barrier,
884                         &due, 1) < 0)
885                 return;
886         list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
887                 if (fc->error < 0)
888                         continue;
889                 if (!fc->ready) {
890                         ret = initialize_fec_client(fc);
891                         if (ret < 0) {
892                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
893                                 continue;
894                         }
895                 }
896                 if (!next_slice_is_due(fc, NULL)) {
897                         fec_active = 1;
898                         continue;
899                 }
900                 if (compute_next_fec_slice(fc, vsst) <= 0)
901                         continue;
902                 PARA_DEBUG_LOG("sending %d:%d (%u bytes)\n", fc->group.num,
903                         fc->current_slice_num, fc->fcp->max_slice_bytes);
904                 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf,
905                                   fc->fcp->max_slice_bytes);
906                 fc->current_slice_num++;
907                 fec_active = 1;
908         }
909         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
910                 if (!fec_active)
911                         mmd->new_vss_status_flags |= VSS_NEXT;
912                 return;
913         }
914         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
915                 &mmd->stream_start, &due);
916         if (tv_diff(&due, now, NULL) <= 0) {
917                 const char *buf;
918                 size_t len;
919
920                 if (!mmd->chunks_sent) {
921                         mmd->stream_start = *now;
922                         mmd->events++;
923                         set_mmd_offset();
924                 }
925                 /*
926                  * We call the send function also in case of empty chunks as
927                  * they might have still some data queued which can be sent in
928                  * this case.
929                  */
930                 afh_get_chunk(mmd->current_chunk, &mmd->afd.afhi, vsst->map,
931                         &buf, &len);
932                 for (i = 0; senders[i].name; i++) {
933                         if (!senders[i].send)
934                                 continue;
935                         senders[i].send(mmd->current_chunk, mmd->chunks_sent,
936                                 buf, len, vsst->header_buf, vsst->header_len);
937                 }
938                 mmd->chunks_sent++;
939                 mmd->current_chunk++;
940         }
941 }
942
943 static void vss_post_select(struct sched *s, struct task *t)
944 {
945         int ret, i;
946         struct vss_task *vsst = container_of(t, struct vss_task, task);
947
948
949         if (mmd->sender_cmd_data.cmd_num >= 0) {
950                 int num = mmd->sender_cmd_data.cmd_num,
951                         sender_num = mmd->sender_cmd_data.sender_num;
952
953                 if (senders[sender_num].client_cmds[num])
954                         senders[sender_num].client_cmds[num](&mmd->sender_cmd_data);
955                 mmd->sender_cmd_data.cmd_num = -1;
956         }
957         if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
958                 recv_afs_result(vsst, &s->rfds);
959         else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
960                 PARA_NOTICE_LOG("requesting new fd from afs\n");
961                 ret = send_buffer(vsst->afs_socket, "new");
962                 if (ret < 0)
963                         PARA_CRIT_LOG("%s\n", para_strerror(-ret));
964                 else
965                         vsst->afsss = AFS_SOCKET_AFD_PENDING;
966         }
967         for (i = 0; senders[i].name; i++) {
968                 if (!senders[i].post_select)
969                         continue;
970                 senders[i].post_select(&s->rfds, &s->wfds);
971         }
972         if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
973                         (vss_next() && vss_playing()))
974                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
975         vss_send(vsst);
976 }
977
978 /**
979  * Initialize the virtual streaming system task.
980  *
981  * \param afs_socket The fd for communication with afs.
982  *
983  * This also initializes all supported senders and starts streaming
984  * if the --autoplay command line flag was given.
985  */
986 void init_vss_task(int afs_socket)
987 {
988         static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
989         int i;
990         char *hn = para_hostname(), *home = para_homedir();
991         long unsigned announce_time = conf.announce_time_arg > 0?
992                         conf.announce_time_arg : 300,
993                 autoplay_delay = conf.autoplay_delay_arg > 0?
994                         conf.autoplay_delay_arg : 0;
995         vsst->header_interval.tv_sec = 5; /* should this be configurable? */
996         vsst->afs_socket = afs_socket;
997         vsst->task.pre_select = vss_pre_select;
998         vsst->task.post_select = vss_post_select;
999         ms2tv(announce_time, &vsst->announce_tv);
1000         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
1001         INIT_LIST_HEAD(&fec_client_list);
1002         for (i = 0; senders[i].name; i++) {
1003                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
1004                 senders[i].init(&senders[i]);
1005         }
1006         free(hn);
1007         free(home);
1008         mmd->sender_cmd_data.cmd_num = -1;
1009         if (conf.autoplay_given) {
1010                 struct timeval tmp;
1011                 mmd->vss_status_flags |= VSS_PLAYING;
1012                 mmd->new_vss_status_flags |= VSS_PLAYING;
1013                 ms2tv(autoplay_delay, &tmp);
1014                 tv_add(now, &tmp, &vsst->autoplay_barrier);
1015                 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1016                         &vsst->data_send_barrier);
1017         }
1018         register_task(&vsst->task);
1019 }