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