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