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