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