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