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