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