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