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