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