manual: Mention that also DCCP streams are FEC-encoded.
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2011 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file vss.c The virtual streaming system.
8  *
9  * This contains the audio streaming code of para_server which is independent
10  * of the current audio format, audio file selector and of the activated
11  * senders.
12  */
13
14 #include <regex.h>
15 #include <dirent.h>
16 #include <osl.h>
17
18 #include "para.h"
19 #include "error.h"
20 #include "portable_io.h"
21 #include "fec.h"
22 #include "string.h"
23 #include "afh.h"
24 #include "afs.h"
25 #include "server.h"
26 #include "net.h"
27 #include "server.cmdline.h"
28 #include "list.h"
29 #include "send.h"
30 #include "vss.h"
31 #include "ipc.h"
32 #include "fd.h"
33 #include "sched.h"
34
35 extern struct misc_meta_data *mmd;
36
37 extern void dccp_send_init(struct sender *);
38 extern void http_send_init(struct sender *);
39 extern void udp_send_init(struct sender *);
40
41 /** The list of supported senders. */
42 struct sender senders[] = {
43         {
44                 .name = "http",
45                 .init = http_send_init,
46         },
47         {
48                 .name = "dccp",
49                 .init = dccp_send_init,
50         },
51         {
52                 .name = "udp",
53                 .init = udp_send_init,
54         },
55         {
56                 .name = NULL,
57         }
58 };
59
60 /** The possible states of the afs socket. */
61 enum afs_socket_status {
62         /** Socket is inactive. */
63         AFS_SOCKET_READY,
64         /** Socket fd was included in the write fd set for select(). */
65         AFS_SOCKET_CHECK_FOR_WRITE,
66         /** vss wrote a request to the socket and waits for reply from afs. */
67         AFS_SOCKET_AFD_PENDING
68 };
69
70 /** The task structure for the virtual streaming system. */
71 struct vss_task {
72         /** Copied from the -announce_time command line option. */
73         struct timeval announce_tv;
74         /** End of the announcing interval. */
75         struct timeval data_send_barrier;
76         /** End of the EOF interval. */
77         struct timeval eof_barrier;
78         /** Only used if --autoplay_delay was given. */
79         struct timeval autoplay_barrier;
80         /** Used for afs-server communication. */
81         int afs_socket;
82         /** The current state of \a afs_socket. */
83         enum afs_socket_status afsss;
84         /** The memory mapped audio file. */
85         char *map;
86         /** Used by the scheduler. */
87         struct task task;
88         /** Pointer to the header of the mapped audio file. */
89         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         /** Number of bytes per slice for this group. */
133         uint16_t slice_bytes;
134 };
135
136 enum fec_client_state {
137         FEC_STATE_NONE = 0,     /**< not initialized and not enabled */
138         FEC_STATE_DISABLED,     /**< temporarily disabled */
139         FEC_STATE_READY_TO_RUN  /**< initialized and enabled */
140 };
141
142 /**
143  * Describes one connected FEC client.
144  */
145 struct fec_client {
146         /** Current state of the client */
147         enum fec_client_state state;
148         /** The connected sender client (transport layer). */
149         struct sender_client *sc;
150         /** Parameters requested by the client. */
151         struct fec_client_parms *fcp;
152         /** Used by the core FEC code. */
153         struct fec_parms *parms;
154         /** The position of this client in the fec client list. */
155         struct list_head node;
156         /** When the first slice for this client was sent. */
157         struct timeval stream_start;
158         /** The first chunk sent to this FEC client. */
159         int first_stream_chunk;
160         /** Describes the current group. */
161         struct fec_group group;
162         /** The current slice. */
163         uint8_t current_slice_num;
164         /** The data to be FEC-encoded (point to a region within the mapped audio file). */
165         const unsigned char **src_data;
166         /** Last time an audio  header was sent. */
167         struct timeval next_header_time;
168         /** Used for the last source pointer of an audio file. */
169         unsigned char *extra_src_buf;
170         /** Needed for the last slice of the audio file header. */
171         unsigned char *extra_header_buf;
172         /** Extra slices needed to store largest chunk + header. */
173         int num_extra_slices;
174         /** Contains the FEC-encoded data. */
175         unsigned char *enc_buf;
176         /** Maximal packet size. */
177         int mps;
178 };
179
180 /**
181  * Get the chunk time of the current audio file.
182  *
183  * \return A pointer to a struct containing the chunk time, or NULL,
184  * if currently no audio file is selected.
185  */
186 struct timeval *vss_chunk_time(void)
187 {
188         if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
189                         mmd->afd.afhi.chunk_tv.tv_usec == 0)
190                 return NULL;
191         return &mmd->afd.afhi.chunk_tv;
192 }
193
194 /**
195  * Write a fec header to a buffer.
196  *
197  * \param buf The buffer to write to.
198  * \param h The fec header to write.
199  */
200 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
201 {
202         char *buf = (char *)fc->enc_buf;
203         struct fec_group *g = &fc->group;
204         struct fec_client_parms *p = fc->fcp;
205
206         write_u32(buf, FEC_MAGIC);
207
208         write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
209         write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
210         write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
211
212         write_u32(buf + 10, g->num);
213         write_u32(buf + 14, g->bytes);
214
215         write_u8(buf + 18, fc->current_slice_num);
216         write_u8(buf + 19, 0); /* unused */
217         write_u16(buf + 20, g->slice_bytes);
218         write_u8(buf + 22, g->first_chunk? 0 : 1);
219         write_u8(buf + 23, vsst->header_len? 1 : 0);
220         memset(buf + 24, 0, 8);
221 }
222
223 static bool need_audio_header(struct fec_client *fc, struct vss_task *vsst)
224 {
225         if (!mmd->current_chunk) {
226                 tv_add(now, &vsst->header_interval, &fc->next_header_time);
227                 return false;
228         }
229         if (!vsst->header_buf)
230                 return false;
231         if (vsst->header_len == 0)
232                 return false;
233         if (fc->group.num > 0) {
234                 if (!fc->fcp->need_periodic_header)
235                         return false;
236                 if (tv_diff(&fc->next_header_time, now, NULL) > 0)
237                         return false;
238         }
239         tv_add(now, &vsst->header_interval, &fc->next_header_time);
240         return true;
241 }
242
243 static bool need_data_slices(struct fec_client *fc, struct vss_task *vsst)
244 {
245         if (fc->group.num > 0)
246                 return true;
247         if (!vsst->header_buf)
248                 return true;
249         if (vsst->header_len == 0)
250                 return true;
251         if (fc->fcp->need_periodic_header)
252                 return true;
253         return false;
254 }
255
256 static int num_slices(long unsigned bytes, int max_payload, int rs)
257 {
258         int ret;
259
260         assert(max_payload > 0);
261         assert(rs > 0);
262         ret = DIV_ROUND_UP(bytes, max_payload);
263         if (ret + rs > 255)
264                 return -E_BAD_CT;
265         return ret;
266 }
267
268 /* set group start and group duration */
269 static void set_group_timing(struct fec_client *fc, struct vss_task *vsst)
270 {
271         struct fec_group *g = &fc->group;
272         struct timeval *chunk_tv = vss_chunk_time();
273
274         if (!need_data_slices(fc, vsst))
275                 ms2tv(200, &g->duration);
276         else
277                 tv_scale(g->num_chunks, chunk_tv, &g->duration);
278         tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
279                 &g->duration, &g->slice_duration);
280         PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
281                 tv2ms(&g->duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
282 }
283
284 static int initialize_fec_client(struct fec_client *fc, struct vss_task *vsst)
285 {
286         int k, n, ret;
287         int hs, ds, rs; /* header/data/redundant slices */
288         struct fec_client_parms *fcp = fc->fcp;
289
290         /* set mps */
291         if (fcp->init_fec) {
292                 /*
293                  * Set the maximum slice size to the Maximum Packet Size if the
294                  * transport protocol allows to determine this value. The user
295                  * can specify a slice size up to this value.
296                  */
297                 ret = fcp->init_fec(fc->sc);
298                 if (ret < 0)
299                         return ret;
300                 fc->mps = ret;
301         } else
302                 fc->mps = generic_max_transport_msg_size(fc->sc->fd);
303         if (fc->mps <= FEC_HEADER_SIZE)
304                 return -ERRNO_TO_PARA_ERROR(EINVAL);
305
306         rs = fc->fcp->slices_per_group - fc->fcp->data_slices_per_group;
307         ret = num_slices(vsst->header_len, fc->mps - FEC_HEADER_SIZE, rs);
308         if (ret < 0)
309                 return ret;
310         hs = ret;
311         ret = num_slices(mmd->afd.max_chunk_size, fc->mps - FEC_HEADER_SIZE, rs);
312         if (ret < 0)
313                 return ret;
314         ds = ret;
315         if (fc->fcp->need_periodic_header)
316                 k = hs + ds;
317         else
318                 k = PARA_MAX(hs, ds);
319         if (k < fc->fcp->data_slices_per_group)
320                 k = fc->fcp->data_slices_per_group;
321         fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
322         n = k + rs;
323         fec_free(fc->parms);
324         ret = fec_new(k, n, &fc->parms);
325         if (ret < 0)
326                 return ret;
327         PARA_INFO_LOG("mps: %d, k: %d, n: %d, extra slices: %d\n",
328                 fc->mps, k, n, fc->num_extra_slices);
329         fc->src_data = para_realloc(fc->src_data, k * sizeof(char *));
330         fc->enc_buf = para_realloc(fc->enc_buf, fc->mps);
331         fc->extra_src_buf = para_realloc(fc->extra_src_buf, fc->mps);
332         fc->extra_header_buf = para_realloc(fc->extra_header_buf, fc->mps);
333
334         fc->state = FEC_STATE_READY_TO_RUN;
335         fc->next_header_time.tv_sec = 0;
336         fc->stream_start = *now;
337         fc->first_stream_chunk = mmd->current_chunk;
338         return 1;
339 }
340
341 static void vss_get_chunk(int chunk_num, struct vss_task *vsst,
342                 char **buf, size_t *sz)
343 {
344         /*
345          * Chunk zero is special for header streams: It is the first portion of
346          * the audio file which consists of the audio file header. It may be
347          * arbitrary large due to embedded meta data. Audio format handlers may
348          * replace the header by a stripped one with meta data omitted which is
349          * of bounded size. We always use the stripped header for streaming
350          * rather than the unmodified header (chunk zero).
351          */
352         if (chunk_num == 0 && vsst->header_len > 0) {
353                 *buf = vsst->header_buf; /* stripped header */
354                 *sz = vsst->header_len;
355                 return;
356         }
357         afh_get_chunk(chunk_num, &mmd->afd.afhi, vsst->map, (const char **)buf,
358                 sz);
359 }
360
361 static void compute_group_size(struct vss_task *vsst, struct fec_group *g,
362                 int max_bytes)
363 {
364         int i, max_chunks = PARA_MAX(1LU, 150 / tv2ms(vss_chunk_time()));
365
366         g->num_chunks = 0;
367         g->bytes = 0;
368         /*
369          * Include chunks into the group until the group duration is at least
370          * 150ms.  For ogg and wma, a single chunk's duration (ogg page/wma
371          * super frame) is already larger than 150ms, so a FEC group consists
372          * of exactly one chunk for these audio formats.
373          */
374         for (i = 0;; i++) {
375                 char *buf;
376                 size_t len;
377                 int chunk_num = g->first_chunk + i;
378
379                 if (g->bytes > 0 && i >= max_chunks) /* duration limit */
380                         break;
381                 if (chunk_num >= mmd->afd.afhi.chunks_total) /* eof */
382                         break;
383                 vss_get_chunk(chunk_num, vsst, &buf, &len);
384                 if (g->bytes + len > max_bytes)
385                         break;
386                 /* Include this chunk */
387                 g->bytes += len;
388                 g->num_chunks++;
389         }
390         assert(g->num_chunks);
391 }
392
393 /*
394  * Compute the slice size of the next group.
395  *
396  * The FEC parameters n and k are fixed but the slice size varies per
397  * FEC group.  We'd like to choose slices as small as possible to avoid
398  * unnecessary FEC calculations but large enough to guarantee that the
399  * k data slices suffice to encode the header (if needed) and the data
400  * chunk(s).
401  *
402  * Once we know the payload of the next group, we define the number s
403  * of bytes per slice for this group by
404  *
405  *      s = ceil(payload / k)
406  *
407  * However, for header streams, computing s is more complicated since no
408  * overlapping of header and data slices is possible. Hence we have k >=
409  * 2 and s must satisfy
410  *
411  * (*)  ceil(h / s) + ceil(d / s) <= k
412  *
413  * where h and d are payload of the header and the data chunk(s)
414  * respectively. In general there is no value for s such that (*)
415  * becomes an equality, for example if h = 4000, d = 5000 and k = 10.
416  *
417  * We use the following approach for computing a suitable value for s:
418  *
419  * Let
420  *      k1 := ceil(k * min(h, d) / (h + d)),
421  *      k2 := k - k1.
422  *
423  * Note that k >= 2 implies k1 > 0 and k2 > 0, so
424  *
425  *      s := max(ceil(min(h, d) / k1), ceil(max(h, d) / k2))
426  *
427  * is well-defined. Inequality (*) holds for this value of s since k1
428  * slices suffice to store min(h, d) while k2 slices suffice to store
429  * max(h, d), i.e. the first addent of (*) is bounded by k1 and the
430  * second by k2.
431  *
432  * For the above example we obtain
433  *
434  *      k1 = ceil(10 * 4000 / 9000) = 5, k2 = 5,
435  *      s = max(4000 / 5, 5000 / 5) = 1000,
436  *
437  * which is optimal since a slice size of 999 bytes would already require
438  * 11 slices.
439  */
440 static int compute_slice_size(struct fec_client *fc, struct vss_task *vsst)
441 {
442         struct fec_group *g = &fc->group;
443         int k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
444         int n = fc->fcp->slices_per_group + fc->num_extra_slices;
445         int ret, k1, k2, h, d, min, max, sum;
446         int max_slice_bytes = fc->mps - FEC_HEADER_SIZE;
447         int max_group_bytes;
448
449         if (!need_audio_header(fc, vsst)) {
450                 max_group_bytes = k * max_slice_bytes;
451                 g->num_header_slices = 0;
452                 compute_group_size(vsst, g, max_group_bytes);
453                 g->slice_bytes = DIV_ROUND_UP(g->bytes, k);
454                 if (g->slice_bytes == 0)
455                         g->slice_bytes = 1;
456                 return 1;
457         }
458         if (!need_data_slices(fc, vsst)) {
459                 g->bytes = 0;
460                 g->num_chunks = 0;
461                 g->slice_bytes = DIV_ROUND_UP(vsst->header_len, k);
462                 g->num_header_slices = k;
463                 return 1;
464         }
465         h = vsst->header_len;
466         max_group_bytes = (k - num_slices(h, max_slice_bytes, n - k))
467                 * max_slice_bytes;
468         compute_group_size(vsst, g, max_group_bytes);
469         d = g->bytes;
470         if (d == 0) {
471                 g->slice_bytes = DIV_ROUND_UP(h, k);
472                 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
473                 if (ret < 0)
474                         return ret;
475                 g->num_header_slices = ret;
476                 return 1;
477         }
478         min = PARA_MIN(h, d);
479         max = PARA_MAX(h, d);
480         sum = h + d;
481         k1 = DIV_ROUND_UP(k * min, sum);
482         k2 = k - k1;
483         assert(k1 > 0);
484         assert(k2 > 0);
485
486         g->slice_bytes = PARA_MAX(DIV_ROUND_UP(min, k1), DIV_ROUND_UP(max, k2));
487         /*
488          * This value of s := g->slice_bytes satisfies inequality (*) above,
489          * but it might be larger than max_slice_bytes. However, we know that
490          * max_slice_bytes are sufficient to store header and data, so:
491          */
492         g->slice_bytes = PARA_MIN((int)g->slice_bytes, max_slice_bytes);
493
494         ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
495         if (ret < 0)
496                 return ret;
497         g->num_header_slices = ret;
498         return 1;
499 }
500
501 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
502 {
503         int ret, i, k, n, data_slices;
504         size_t len;
505         char *buf;
506         struct fec_group *g = &fc->group;
507
508         if (fc->state == FEC_STATE_NONE) {
509                 ret = initialize_fec_client(fc, vsst);
510                 if (ret < 0)
511                         return ret;
512                 g->first_chunk = mmd->current_chunk;
513                 g->num = 0;
514                 g->start = *now;
515         } else {
516                 struct timeval tmp;
517                 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
518                         return 0;
519                 /*
520                  * Start and duration of this group depend only on the previous
521                  * group. Compute the new group start as g->start += g->duration.
522                  */
523                 tmp = g->start;
524                 tv_add(&tmp, &g->duration, &g->start);
525                 set_group_timing(fc, vsst);
526                 g->first_chunk += g->num_chunks;
527                 g->num++;
528         }
529         k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
530         n = fc->fcp->slices_per_group + fc->num_extra_slices;
531
532         compute_slice_size(fc, vsst);
533         assert(g->slice_bytes > 0);
534         ret = num_slices(g->bytes, g->slice_bytes, n - k);
535         if (ret < 0)
536                 return ret;
537         data_slices = ret;
538         assert(g->num_header_slices + data_slices <= k);
539         fc->current_slice_num = 0;
540         if (g->num == 0)
541                 set_group_timing(fc, vsst);
542         /* setup header slices */
543         buf = vsst->header_buf;
544         for (i = 0; i < g->num_header_slices; i++) {
545                 if (buf + g->slice_bytes <= vsst->header_buf + vsst->header_len) {
546                         fc->src_data[i] = (const unsigned char *)buf;
547                         buf += g->slice_bytes;
548                         continue;
549                 }
550                 /*
551                  * Can not use vss->header_buf for this slice as it
552                  * goes beyond the buffer. This slice will not be fully
553                  * used.
554                  */
555                 uint32_t payload_size = vsst->header_buf
556                         + vsst->header_len - buf;
557                 memcpy(fc->extra_header_buf, buf, payload_size);
558                 if (payload_size < g->slice_bytes)
559                         memset(fc->extra_header_buf + payload_size, 0,
560                                 g->slice_bytes - payload_size);
561                 fc->src_data[i] = fc->extra_header_buf;
562                 assert(i == g->num_header_slices - 1);
563         }
564
565         /* setup data slices */
566         vss_get_chunk(g->first_chunk, vsst, &buf, &len);
567         for (; i < g->num_header_slices + data_slices; i++) {
568                 if (buf + g->slice_bytes > vsst->map + mmd->size) {
569                         /*
570                          * Can not use the memory mapped audio file for this
571                          * slice as it goes beyond the map.
572                          */
573                         uint32_t payload_size = vsst->map + mmd->size - buf;
574                         memcpy(fc->extra_src_buf, buf, payload_size);
575                         if (payload_size < g->slice_bytes)
576                                 memset(fc->extra_src_buf + payload_size, 0,
577                                         g->slice_bytes - payload_size);
578                         fc->src_data[i] = fc->extra_src_buf;
579                         i++;
580                         break;
581                 }
582                 fc->src_data[i] = (const unsigned char *)buf;
583                 buf += g->slice_bytes;
584         }
585         if (i < k) {
586                 /* use arbitrary data for all remaining slices */
587                 buf = vsst->map;
588                 for (; i < k; i++)
589                         fc->src_data[i] = (const unsigned char *)buf;
590         }
591         PARA_DEBUG_LOG("FEC group %d: %d chunks (%d - %d), %d bytes\n",
592                 g->num, g->num_chunks, g->first_chunk,
593                 g->first_chunk + g->num_chunks - 1, g->bytes
594         );
595         PARA_DEBUG_LOG("slice_bytes: %d, %d header slices, %d data slices\n",
596                 g->slice_bytes, g->num_header_slices, data_slices
597         );
598         return 1;
599 }
600
601 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
602 {
603         if (fc->state == FEC_STATE_NONE || fc->current_slice_num
604                         == fc->fcp->slices_per_group + fc->num_extra_slices) {
605                 int ret = setup_next_fec_group(fc, vsst);
606                 if (ret == 0)
607                         return 0;
608                 if (ret < 0) {
609                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
610                         PARA_ERROR_LOG("FEC client temporarily disabled\n");
611                         fc->state = FEC_STATE_DISABLED;
612                         return ret;
613                 }
614         }
615         write_fec_header(fc, vsst);
616         fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
617                 fc->current_slice_num, fc->group.slice_bytes);
618         return 1;
619 }
620
621 /**
622  * Return a buffer that marks the end of the stream.
623  *
624  * \param buf Result pointer.
625  * \return The length of the eof buffer.
626  *
627  * This is used for (multicast) udp streaming where closing the socket on the
628  * sender might not give rise to an eof condition at the peer.
629  */
630 size_t vss_get_fec_eof_packet(const char **buf)
631 {
632         static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
633         *buf = fec_eof_packet;
634         return FEC_HEADER_SIZE;
635 }
636
637 /**
638  * Add one entry to the list of active fec clients.
639  *
640  * \param sc  Generic sender_client data of the transport layer.
641  * \param fcp FEC parameters as supplied by the transport layer.
642  *
643  * \return Newly allocated fec_client struct.
644  */
645 struct fec_client *vss_add_fec_client(struct sender_client *sc,
646                                       struct fec_client_parms *fcp)
647 {
648         struct fec_client *fc = para_calloc(sizeof(*fc));
649
650         fc->sc  = sc;
651         fc->fcp = fcp;
652         para_list_add(&fc->node, &fec_client_list);
653         return fc;
654 }
655
656 /**
657  * Remove one entry from the list of active fec clients.
658  *
659  * \param fc The client to be removed.
660  */
661 void vss_del_fec_client(struct fec_client *fc)
662 {
663         list_del(&fc->node);
664         free(fc->src_data);
665         free(fc->enc_buf);
666         free(fc->extra_src_buf);
667         free(fc->extra_header_buf);
668         fec_free(fc->parms);
669         free(fc);
670 }
671
672 /*
673  * Compute if/when next slice is due. If it isn't due yet and \a diff is
674  * not \p Null, compute the time difference next - now, where
675  *
676  *      next = stream_start + (first_group_chunk - first_stream_chunk)
677  *              * chunk_time + slice_num * slice_time
678  */
679 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
680 {
681         struct timeval tmp, next;
682         int ret;
683
684         if (fc->state == FEC_STATE_NONE)
685                 return 1;
686         tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
687         tv_add(&tmp, &fc->group.start, &next);
688         ret = tv_diff(&next, now, diff);
689         return ret < 0? 1 : 0;
690 }
691
692 static void compute_slice_timeout(struct timeval *timeout)
693 {
694         struct fec_client *fc;
695
696         list_for_each_entry(fc, &fec_client_list, node) {
697                 struct timeval diff;
698
699                 if (fc->state != FEC_STATE_READY_TO_RUN)
700                         continue;
701                 if (next_slice_is_due(fc, &diff)) {
702                         timeout->tv_sec = 0;
703                         timeout->tv_usec = 0;
704                         return;
705                 }
706                 /* timeout = min(timeout, diff) */
707                 if (tv_diff(&diff, timeout, NULL) < 0)
708                         *timeout = diff;
709         }
710 }
711
712 static void set_eof_barrier(struct vss_task *vsst)
713 {
714         struct fec_client *fc;
715         struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
716
717         if (!chunk_tv)
718                 goto out;
719         list_for_each_entry(fc, &fec_client_list, node) {
720                 struct timeval group_duration;
721
722                 if (fc->state != FEC_STATE_READY_TO_RUN)
723                         continue;
724                 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
725                 if (tv_diff(&timeout, &group_duration, NULL) < 0)
726                         timeout = group_duration;
727         }
728 out:
729         tv_add(now, &timeout, &vsst->eof_barrier);
730 }
731
732 /**
733  * Check if vss status flag \a P (playing) is set.
734  *
735  * \return Greater than zero if playing, zero otherwise.
736  *
737  */
738 unsigned int vss_playing(void)
739 {
740         return mmd->new_vss_status_flags & VSS_PLAYING;
741 }
742
743 /**
744  * Check if the \a N (next) status flag is set.
745  *
746  * \return Greater than zero if set, zero if not.
747  *
748  */
749 unsigned int vss_next(void)
750 {
751         return mmd->new_vss_status_flags & VSS_NEXT;
752 }
753
754 /**
755  * Check if a reposition request is pending.
756  *
757  * \return Greater than zero if true, zero otherwise.
758  *
759  */
760 unsigned int vss_repos(void)
761 {
762         return mmd->new_vss_status_flags & VSS_REPOS;
763 }
764
765 /**
766  * Check if the vss is currently paused.
767  *
768  * \return Greater than zero if paused, zero otherwise.
769  *
770  */
771 unsigned int vss_paused(void)
772 {
773         return !(mmd->new_vss_status_flags & VSS_NEXT)
774                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
775 }
776
777 /**
778  * Check if the vss is currently stopped.
779  *
780  * \return Greater than zero if paused, zero otherwise.
781  *
782  */
783 unsigned int vss_stopped(void)
784 {
785         return (mmd->new_vss_status_flags & VSS_NEXT)
786                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
787 }
788
789 static int chk_barrier(const char *bname, const struct timeval *barrier,
790                 struct timeval *diff, int print_log)
791 {
792         long ms;
793
794         if (tv_diff(now, barrier, diff) > 0)
795                 return 1;
796         ms = tv2ms(diff);
797         if (print_log && ms)
798                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
799         return -1;
800 }
801
802 /*
803  * != NULL: timeout for next chunk
804  * NULL: nothing to do
805  */
806 static struct timeval *vss_compute_timeout(struct vss_task *vsst)
807 {
808         static struct timeval the_timeout;
809         struct timeval next_chunk;
810
811         if (vss_next() && vsst->map) {
812                 /* only sleep a bit, nec*/
813                 the_timeout.tv_sec = 0;
814                 the_timeout.tv_usec = 100;
815                 return &the_timeout;
816         }
817         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
818                         &the_timeout, 1) < 0)
819                 return &the_timeout;
820         if (chk_barrier("eof", &vsst->eof_barrier, &the_timeout, 1) < 0)
821                 return &the_timeout;
822         if (chk_barrier("data send", &vsst->data_send_barrier,
823                         &the_timeout, 1) < 0)
824                 return &the_timeout;
825         if (!vss_playing() || !vsst->map)
826                 return NULL;
827         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
828                 &mmd->stream_start, &next_chunk);
829         if (chk_barrier("chunk", &next_chunk, &the_timeout, 0) >= 0) {
830                 /* chunk is due or bof */
831                 the_timeout.tv_sec = 0;
832                 the_timeout.tv_usec = 0;
833                 return &the_timeout;
834         }
835         /* compute min of current timeout and next slice time */
836         compute_slice_timeout(&the_timeout);
837         return &the_timeout;
838 }
839
840 static void vss_eof(struct vss_task *vsst)
841 {
842
843         if (!vsst->map)
844                 return;
845         if (mmd->new_vss_status_flags & VSS_NOMORE)
846                 mmd->new_vss_status_flags = VSS_NEXT;
847         set_eof_barrier(vsst);
848         afh_free_header(vsst->header_buf, mmd->afd.audio_format_id);
849         vsst->header_buf = NULL;
850         para_munmap(vsst->map, mmd->size);
851         vsst->map = NULL;
852         mmd->chunks_sent = 0;
853         //mmd->offset = 0;
854         mmd->afd.afhi.seconds_total = 0;
855         mmd->afd.afhi.chunk_tv.tv_sec = 0;
856         mmd->afd.afhi.chunk_tv.tv_usec = 0;
857         free(mmd->afd.afhi.chunk_table);
858         mmd->afd.afhi.chunk_table = NULL;
859         mmd->mtime = 0;
860         mmd->size = 0;
861         mmd->events++;
862 }
863
864 static int need_to_request_new_audio_file(struct vss_task *vsst)
865 {
866         struct timeval diff;
867
868         if (vsst->map) /* have audio file */
869                 return 0;
870         if (!vss_playing()) /* don't need one */
871                 return 0;
872         if (mmd->new_vss_status_flags & VSS_NOMORE)
873                 return 0;
874         if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
875                 return 0;
876         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
877                         &diff, 1) < 0)
878                 return 0;
879         return 1;
880 }
881
882 static void set_mmd_offset(void)
883 {
884         struct timeval offset;
885         tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
886         mmd->offset = tv2ms(&offset);
887 }
888
889 /**
890  * Compute the timeout for the main select-loop of the scheduler.
891  *
892  * \param s Pointer to the server scheduler.
893  * \param t Pointer to the vss task structure.
894  *
895  * Before the timeout is computed, the current vss status flags are evaluated
896  * and acted upon by calling appropriate functions from the lower layers.
897  * Possible actions include
898  *
899  *      - request a new audio file from afs,
900  *      - shutdown of all senders (stop/pause command),
901  *      - reposition the stream (ff/jmp command).
902  */
903 static void vss_pre_select(struct sched *s, struct task *t)
904 {
905         int i;
906         struct timeval *tv;
907         struct vss_task *vsst = container_of(t, struct vss_task, task);
908
909         if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
910                 struct fec_client *fc, *tmp;
911                 for (i = 0; senders[i].name; i++)
912                         if (senders[i].shutdown_clients)
913                                 senders[i].shutdown_clients();
914                 list_for_each_entry_safe(fc, tmp, &fec_client_list, node)
915                         fc->state = FEC_STATE_NONE;
916                 mmd->stream_start.tv_sec = 0;
917                 mmd->stream_start.tv_usec = 0;
918         }
919         if (vss_next())
920                 vss_eof(vsst);
921         else if (vss_paused()) {
922                 if (mmd->chunks_sent)
923                         set_eof_barrier(vsst);
924                 mmd->chunks_sent = 0;
925         } else if (vss_repos()) {
926                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
927                 set_eof_barrier(vsst);
928                 mmd->chunks_sent = 0;
929                 mmd->current_chunk = mmd->repos_request;
930                 mmd->new_vss_status_flags &= ~VSS_REPOS;
931                 set_mmd_offset();
932         }
933         if (need_to_request_new_audio_file(vsst)) {
934                 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
935                 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
936                 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
937         } else
938                 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
939         for (i = 0; senders[i].name; i++) {
940                 if (!senders[i].pre_select)
941                         continue;
942                 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
943         }
944         tv = vss_compute_timeout(vsst);
945         if (tv)
946                 sched_request_timeout(tv, s);
947 }
948
949 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
950 {
951         char control[255], buf[8];
952         struct msghdr msg = {.msg_iov = NULL};
953         struct cmsghdr *cmsg;
954         struct iovec iov;
955         int ret = 0;
956
957         *fd = -1;
958         iov.iov_base = buf;
959         iov.iov_len = sizeof(buf);
960         msg.msg_iov = &iov;
961         msg.msg_iovlen = 1;
962         msg.msg_control = control;
963         msg.msg_controllen = sizeof(control);
964         memset(buf, 0, sizeof(buf));
965         ret = recvmsg(afs_socket, &msg, 0);
966         if (ret < 0)
967                 return -ERRNO_TO_PARA_ERROR(errno);
968         if (iov.iov_len != sizeof(buf))
969                 return -E_AFS_SHORT_READ;
970         *code = *(uint32_t*)buf;
971         *data =  *(uint32_t*)(buf + 4);
972         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
973                 if (cmsg->cmsg_level != SOL_SOCKET
974                         || cmsg->cmsg_type != SCM_RIGHTS)
975                         continue;
976                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
977                         continue;
978                 *fd = *(int *)CMSG_DATA(cmsg);
979         }
980         return 1;
981 }
982
983 static void recv_afs_result(struct vss_task *vsst, fd_set *rfds)
984 {
985         int ret, passed_fd, shmid;
986         uint32_t afs_code = 0, afs_data = 0;
987         struct stat statbuf;
988
989         if (!FD_ISSET(vsst->afs_socket, rfds))
990                 return;
991         ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
992         if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
993                 return;
994         if (ret < 0)
995                 goto err;
996         vsst->afsss = AFS_SOCKET_READY;
997         PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
998                 afs_data);
999         ret = -E_NOFD;
1000         if (afs_code != NEXT_AUDIO_FILE)
1001                 goto err;
1002         if (passed_fd < 0)
1003                 goto err;
1004         shmid = afs_data;
1005         ret = load_afd(shmid, &mmd->afd);
1006         if (ret < 0)
1007                 goto err;
1008         shm_destroy(shmid);
1009         ret = fstat(passed_fd, &statbuf);
1010         if (ret < 0) {
1011                 PARA_ERROR_LOG("fstat error:\n");
1012                 ret = -ERRNO_TO_PARA_ERROR(errno);
1013                 goto err;
1014         }
1015         mmd->size = statbuf.st_size;
1016         mmd->mtime = statbuf.st_mtime;
1017         ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
1018                 0, &vsst->map);
1019         if (ret < 0)
1020                 goto err;
1021         close(passed_fd);
1022         mmd->chunks_sent = 0;
1023         mmd->current_chunk = 0;
1024         mmd->offset = 0;
1025         mmd->events++;
1026         mmd->num_played++;
1027         mmd->new_vss_status_flags &= (~VSS_NEXT);
1028         afh_get_header(&mmd->afd.afhi, mmd->afd.audio_format_id,
1029                 vsst->map, mmd->size, &vsst->header_buf, &vsst->header_len);
1030         return;
1031 err:
1032         free(mmd->afd.afhi.chunk_table);
1033         if (passed_fd >= 0)
1034                 close(passed_fd);
1035         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1036         mmd->new_vss_status_flags = VSS_NEXT;
1037 }
1038
1039 /**
1040  * Main sending function.
1041  *
1042  * This function gets called from vss_post_select(). It checks whether the next
1043  * chunk of data should be pushed out. It obtains a pointer to the data to be
1044  * sent out as well as its length from mmd->afd.afhi. This information is then
1045  * passed to each supported sender's send() function as well as to the send()
1046  * functions of each registered fec client.
1047  */
1048 static void vss_send(struct vss_task *vsst)
1049 {
1050         int i, fec_active = 0;
1051         struct timeval due;
1052         struct fec_client *fc, *tmp_fc;
1053
1054         if (!vsst->map || !vss_playing())
1055                 return;
1056         if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
1057                 return;
1058         if (chk_barrier("data send", &vsst->data_send_barrier,
1059                         &due, 1) < 0)
1060                 return;
1061         list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
1062                 if (fc->state == FEC_STATE_DISABLED)
1063                         continue;
1064                 if (!next_slice_is_due(fc, NULL)) {
1065                         fec_active = 1;
1066                         continue;
1067                 }
1068                 if (compute_next_fec_slice(fc, vsst) <= 0)
1069                         continue;
1070                 PARA_DEBUG_LOG("sending %d:%d (%u bytes)\n", fc->group.num,
1071                         fc->current_slice_num, fc->group.slice_bytes);
1072                 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf,
1073                         fc->group.slice_bytes + FEC_HEADER_SIZE);
1074                 fc->current_slice_num++;
1075                 fec_active = 1;
1076         }
1077         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
1078                 if (!fec_active)
1079                         mmd->new_vss_status_flags |= VSS_NEXT;
1080                 return;
1081         }
1082         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
1083                 &mmd->stream_start, &due);
1084         if (tv_diff(&due, now, NULL) <= 0) {
1085                 char *buf;
1086                 size_t len;
1087
1088                 if (!mmd->chunks_sent) {
1089                         mmd->stream_start = *now;
1090                         mmd->events++;
1091                         set_mmd_offset();
1092                 }
1093                 /*
1094                  * We call the send function also in case of empty chunks as
1095                  * they might have still some data queued which can be sent in
1096                  * this case.
1097                  */
1098                 vss_get_chunk(mmd->current_chunk, vsst, &buf, &len);
1099                 for (i = 0; senders[i].name; i++) {
1100                         if (!senders[i].send)
1101                                 continue;
1102                         senders[i].send(mmd->current_chunk, mmd->chunks_sent,
1103                                 buf, len, vsst->header_buf, vsst->header_len);
1104                 }
1105                 mmd->chunks_sent++;
1106                 mmd->current_chunk++;
1107         }
1108 }
1109
1110 static void vss_post_select(struct sched *s, struct task *t)
1111 {
1112         int ret, i;
1113         struct vss_task *vsst = container_of(t, struct vss_task, task);
1114
1115
1116         if (mmd->sender_cmd_data.cmd_num >= 0) {
1117                 int num = mmd->sender_cmd_data.cmd_num,
1118                         sender_num = mmd->sender_cmd_data.sender_num;
1119
1120                 if (senders[sender_num].client_cmds[num]) {
1121                         ret = senders[sender_num].client_cmds[num]
1122                                 (&mmd->sender_cmd_data);
1123                         if (ret < 0)
1124                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1125                 }
1126                 mmd->sender_cmd_data.cmd_num = -1;
1127         }
1128         if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
1129                 recv_afs_result(vsst, &s->rfds);
1130         else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
1131                 PARA_NOTICE_LOG("requesting new fd from afs\n");
1132                 ret = send_buffer(vsst->afs_socket, "new");
1133                 if (ret < 0)
1134                         PARA_CRIT_LOG("%s\n", para_strerror(-ret));
1135                 else
1136                         vsst->afsss = AFS_SOCKET_AFD_PENDING;
1137         }
1138         for (i = 0; senders[i].name; i++) {
1139                 if (!senders[i].post_select)
1140                         continue;
1141                 senders[i].post_select(&s->rfds, &s->wfds);
1142         }
1143         if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
1144                         (vss_next() && vss_playing()))
1145                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1146         vss_send(vsst);
1147 }
1148
1149 /**
1150  * Initialize the virtual streaming system task.
1151  *
1152  * \param afs_socket The fd for communication with afs.
1153  *
1154  * This also initializes all supported senders and starts streaming
1155  * if the --autoplay command line flag was given.
1156  */
1157 void init_vss_task(int afs_socket)
1158 {
1159         static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
1160         int i;
1161         char *hn = para_hostname(), *home = para_homedir();
1162         long unsigned announce_time = conf.announce_time_arg > 0?
1163                         conf.announce_time_arg : 300,
1164                 autoplay_delay = conf.autoplay_delay_arg > 0?
1165                         conf.autoplay_delay_arg : 0;
1166         vsst->header_interval.tv_sec = 5; /* should this be configurable? */
1167         vsst->afs_socket = afs_socket;
1168         vsst->task.pre_select = vss_pre_select;
1169         vsst->task.post_select = vss_post_select;
1170         ms2tv(announce_time, &vsst->announce_tv);
1171         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
1172         INIT_LIST_HEAD(&fec_client_list);
1173         for (i = 0; senders[i].name; i++) {
1174                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
1175                 senders[i].init(&senders[i]);
1176         }
1177         free(hn);
1178         free(home);
1179         mmd->sender_cmd_data.cmd_num = -1;
1180         if (conf.autoplay_given) {
1181                 struct timeval tmp;
1182                 mmd->vss_status_flags |= VSS_PLAYING;
1183                 mmd->new_vss_status_flags |= VSS_PLAYING;
1184                 ms2tv(autoplay_delay, &tmp);
1185                 tv_add(now, &tmp, &vsst->autoplay_barrier);
1186                 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1187                         &vsst->data_send_barrier);
1188         }
1189         sprintf(vsst->task.status, "vss task");
1190         register_task(&vsst->task);
1191 }