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