Merge branch 'master' into next
[paraslash.git] / vss.c
1 /*
2 * Copyright (C) 1997-2009 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 "vss.h"
30 #include "send.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 group duration divided by the number of slices. */
127 struct timeval slice_duration;
128 /** Group contains the audio file header that occupies that many slices. */
129 uint8_t num_header_slices;
130 };
131
132 /**
133 * Describes one connected FEC client.
134 */
135 struct fec_client {
136 /** If negative, this client is temporarily disabled. */
137 int error;
138 /** Parameters requested by the client. */
139 struct fec_client_parms *fcp;
140 /** Used by the core FEC code. */
141 struct fec_parms *parms;
142 /** The position of this client in the fec client list. */
143 struct list_head node;
144 /** When the first slice for this client was sent. */
145 struct timeval stream_start;
146 /** The first chunk sent to this FEC client. */
147 int first_stream_chunk;
148 /** Describes the current group. */
149 struct fec_group group;
150 /** The current slice. */
151 uint8_t current_slice_num;
152 /** The data to be FEC-encoded (point to a region within the mapped audio file). */
153 const unsigned char **src_data;
154 /** Last time an audio header was sent. */
155 struct timeval next_header_time;
156 /** Used for the last source pointer of an audio file. */
157 unsigned char *extra_src_buf;
158 /** Extra slices needed to store largest chunk + header. */
159 int num_extra_slices;
160 /** Contains the FEC-encoded data. */
161 unsigned char *enc_buf;
162 };
163
164 /**
165 * Get the chunk time of the current audio file.
166 *
167 * \return A pointer to a struct containing the chunk time, or NULL,
168 * if currently no audio file is selected.
169 */
170 struct timeval *vss_chunk_time(void)
171 {
172 if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
173 mmd->afd.afhi.chunk_tv.tv_usec == 0)
174 return NULL;
175 return &mmd->afd.afhi.chunk_tv;
176 }
177
178 /**
179 * Write a fec header to a buffer.
180 *
181 * \param buf The buffer to write to.
182 * \param h The fec header to write.
183 */
184 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
185 {
186 char *buf = (char *)fc->enc_buf;
187 struct fec_group *g = &fc->group;
188 struct fec_client_parms *p = fc->fcp;
189
190 write_u32(buf, FEC_MAGIC);
191
192 write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
193 write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
194 write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
195
196 write_u32(buf + 10, g->num);
197 write_u32(buf + 14, g->bytes);
198
199 write_u8(buf + 18, fc->current_slice_num);
200 write_u16(buf + 20, p->max_slice_bytes - FEC_HEADER_SIZE);
201 write_u8(buf + 22, g->first_chunk? 0 : 1);
202 write_u8(buf + 23, vsst->header_len? 1 : 0);
203 memset(buf + 24, 0, 7);
204 }
205
206 static int need_audio_header(struct fec_client *fc, struct vss_task *vsst)
207 {
208 if (!mmd->current_chunk) {
209 tv_add(now, &vsst->header_interval, &fc->next_header_time);
210 return 0;
211 }
212 if (!vsst->header_buf)
213 return 0;
214 if (!vsst->header_len)
215 return 0;
216 if (fc->group.num && tv_diff(&fc->next_header_time, now, NULL) > 0)
217 return 0;
218 tv_add(now, &vsst->header_interval, &fc->next_header_time);
219 return 1;
220 }
221
222 static int num_slices(long unsigned bytes, struct fec_client *fc, uint8_t *result)
223 {
224 unsigned long m = fc->fcp->max_slice_bytes - FEC_HEADER_SIZE;
225 unsigned rv, redundant_slices = fc->fcp->slices_per_group
226 - fc->fcp->data_slices_per_group;
227
228 if (!m)
229 return -E_BAD_CT;
230 rv = (bytes + m - 1) / m;
231 if (rv + redundant_slices > 255)
232 return -E_BAD_CT;
233 *result = rv;
234 return 1;
235 }
236
237 static void set_slice_duration(struct fec_client *fc, struct fec_group *g)
238 {
239 struct timeval group_duration, *chunk_tv = vss_chunk_time();
240
241 tv_scale(g->num_chunks, chunk_tv, &group_duration);
242 tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
243 &group_duration, &g->slice_duration);
244 PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
245 tv2ms(&group_duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
246 }
247
248 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
249 {
250 int ret, i, k, data_slices;
251 size_t len;
252 const char *buf, *start_buf;
253 struct timeval tmp, *chunk_tv = vss_chunk_time();
254 struct fec_group *g = &fc->group;
255 unsigned slice_bytes = fc->fcp->max_slice_bytes - FEC_HEADER_SIZE;
256 uint32_t max_data_size;
257
258 assert(chunk_tv);
259 k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
260 if (fc->first_stream_chunk < 0) {
261 uint32_t largest = afh_get_largest_chunk_size(&mmd->afd.afhi)
262 + vsst->header_len;
263 uint8_t needed, want;
264
265 ret = num_slices(largest, fc, &needed);
266 if (ret < 0)
267 return ret;
268 if (needed > fc->fcp->data_slices_per_group)
269 PARA_WARNING_LOG("fec parms insufficient for this audio file\n");
270 want = PARA_MAX(needed, fc->fcp->data_slices_per_group);
271 if (want != k) {
272 fec_free(fc->parms);
273 fc->src_data = para_realloc(fc->src_data, want * sizeof(char *));
274 ret = fec_new(want, want + fc->fcp->slices_per_group
275 - fc->fcp->data_slices_per_group, &fc->parms);
276 if (ret < 0)
277 return ret;
278 k = want;
279 fc->num_extra_slices = 0;
280 if (k > fc->fcp->data_slices_per_group) {
281 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
282 PARA_NOTICE_LOG("using %d extra slices\n",
283 fc->num_extra_slices);
284 }
285 }
286 fc->stream_start = *now;
287 fc->first_stream_chunk = mmd->current_chunk;
288 g->first_chunk = mmd->current_chunk;
289 g->num = 0;
290 } else {
291 /* use duration of the previous group for the timing of this group */
292 set_slice_duration(fc, g);
293 g->first_chunk += g->num_chunks;
294 g->num++;
295 }
296 if (g->first_chunk >= mmd->afd.afhi.chunks_total)
297 return 0;
298 if (need_audio_header(fc, vsst)) {
299 ret = num_slices(vsst->header_len, fc, &g->num_header_slices);
300 if (ret < 0)
301 return ret;
302 } else
303 g->num_header_slices = 0;
304 afh_get_chunk(g->first_chunk, &mmd->afd.afhi, vsst->map, &start_buf,
305 &len);
306 data_slices = k - g->num_header_slices;
307 assert(data_slices);
308 max_data_size = slice_bytes * data_slices;
309 g->bytes = 0;
310 for (i = g->first_chunk; i < mmd->afd.afhi.chunks_total; i++) {
311 afh_get_chunk(i, &mmd->afd.afhi, vsst->map, &buf, &len);
312 if (g->bytes + len > max_data_size)
313 break;
314 g->bytes += len;
315 }
316 g->num_chunks = i - g->first_chunk;
317 assert(g->num_chunks);
318 fc->current_slice_num = 0;
319 if (g->num == 0)
320 set_slice_duration(fc, g);
321
322 /* setup header slices */
323 buf = vsst->header_buf;
324 for (i = 0; i < g->num_header_slices; i++) {
325 fc->src_data[i] = (const unsigned char *)buf;
326 buf += slice_bytes;
327 }
328
329 /* setup data slices */
330 buf = start_buf;
331 for (i = g->num_header_slices; i < k; i++) {
332 if (buf + slice_bytes > vsst->map + mmd->size)
333 /*
334 * Can not use the memory mapped audio file for this
335 * slice as it goes beyond the map. This slice will not
336 * be fully used.
337 */
338 break;
339 fc->src_data[i] = (const unsigned char *)buf;
340 buf += slice_bytes;
341 }
342 if (i < k) {
343 uint32_t payload_size = vsst->map + mmd->size - buf;
344 memcpy(fc->extra_src_buf, buf, payload_size);
345 fc->src_data[i] = fc->extra_src_buf;
346 i++;
347 /* use arbitrary data for all remaining slices */
348 buf = vsst->map;
349 for (; i < k; i++)
350 fc->src_data[i] = (const unsigned char *)buf;
351 }
352 PARA_DEBUG_LOG("FEC group %d: %d chunks (%d - %d), "
353 "%d header slices, %d data slices\n",
354 g->num, g->num_chunks, g->first_chunk,
355 g->first_chunk + g->num_chunks - 1,
356 g->num_header_slices, data_slices
357 );
358 /* set group start */
359 tv_scale(g->first_chunk - fc->first_stream_chunk, chunk_tv, &tmp);
360 tv_add(&fc->stream_start, &tmp, &g->start);
361 return 1;
362 }
363
364 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
365 {
366 assert(fc->error >= 0);
367 if (fc->first_stream_chunk < 0 || fc->current_slice_num
368 == fc->fcp->slices_per_group + fc->num_extra_slices) {
369 int ret = setup_next_fec_group(fc, vsst);
370 if (ret == 0)
371 return 0;
372 if (ret < 0) {
373 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
374 PARA_ERROR_LOG("FEC client temporarily disabled\n");
375 fc->error = ret;
376 return fc->error;
377 }
378 }
379 write_fec_header(fc, vsst);
380 fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
381 fc->current_slice_num,
382 fc->fcp->max_slice_bytes - FEC_HEADER_SIZE);
383 return 1;
384 }
385
386 /**
387 * Return a buffer that marks the end of the stream.
388 *
389 * \param buf Result pointer.
390 * \return The length of the eof buffer.
391 *
392 * This is used for (multicast) udp streaming where closing the socket on the
393 * sender might not give rise to an eof condition at the peer.
394 */
395 size_t vss_get_fec_eof_packet(const char **buf)
396 {
397 static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
398 *buf = fec_eof_packet;
399 return FEC_HEADER_SIZE;
400 }
401
402 /**
403 * Add one entry to the list of active fec clients.
404 *
405 * \param fcp Describes the fec parameters to be used for this client.
406 * \param result An opaque pointer that must be used by remove the client later.
407 *
408 * \return Standard.
409 */
410 int vss_add_fec_client(struct fec_client_parms *fcp, struct fec_client **result)
411 {
412 int ret;
413 struct fec_client *fc;
414
415 if (fcp->max_slice_bytes < FEC_HEADER_SIZE + fcp->data_slices_per_group)
416 return -ERRNO_TO_PARA_ERROR(EINVAL);
417 fc = para_calloc(sizeof(*fc));
418 fc->fcp = fcp;
419 ret = fec_new(fcp->data_slices_per_group, fcp->slices_per_group,
420 &fc->parms);
421 if (ret < 0)
422 goto err;
423 fc->first_stream_chunk = -1; /* stream not yet started */
424 fc->src_data = para_malloc(fc->fcp->slices_per_group * sizeof(char *));
425 fc->enc_buf = para_calloc(fc->fcp->max_slice_bytes);
426 fc->num_extra_slices = 0;
427 fc->extra_src_buf = para_calloc(fc->fcp->max_slice_bytes);
428 fc->next_header_time.tv_sec = 0;
429 para_list_add(&fc->node, &fec_client_list);
430 *result = fc;
431 return 1;
432 err:
433 fec_free(fc->parms);
434 free(fc);
435 *result = NULL;
436 return ret;
437 }
438
439 /**
440 * Remove one entry from the list of active fec clients.
441 *
442 * \param fc The client to be removed.
443 */
444 void vss_del_fec_client(struct fec_client *fc)
445 {
446 list_del(&fc->node);
447 free(fc->src_data);
448 free(fc->enc_buf);
449 free(fc->extra_src_buf);
450 fec_free(fc->parms);
451 free(fc);
452 }
453
454 /*
455 * Compute if/when next slice is due. If it isn't due yet and \a diff is
456 * not \p Null, compute the time difference next - now, where
457 *
458 * next = stream_start + (first_group_chunk - first_stream_chunk)
459 * * chunk_time + slice_num * slice_time
460 */
461 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
462 {
463 struct timeval tmp, next;
464 int ret;
465
466 if (fc->first_stream_chunk < 0)
467 return 1;
468 tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
469 tv_add(&tmp, &fc->group.start, &next);
470 ret = tv_diff(&next, now, diff);
471 return ret < 0? 1 : 0;
472 }
473
474 static void compute_slice_timeout(struct timeval *timeout)
475 {
476 struct fec_client *fc;
477
478 assert(vss_playing());
479 list_for_each_entry(fc, &fec_client_list, node) {
480 struct timeval diff;
481
482 if (fc->error < 0)
483 continue;
484 if (next_slice_is_due(fc, &diff)) {
485 timeout->tv_sec = 0;
486 timeout->tv_usec = 0;
487 return;
488 }
489 /* timeout = min(timeout, diff) */
490 if (tv_diff(&diff, timeout, NULL) < 0)
491 *timeout = diff;
492 }
493 }
494
495 static void set_eof_barrier(struct vss_task *vsst)
496 {
497 struct fec_client *fc;
498 struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
499
500 if (!chunk_tv)
501 goto out;
502 list_for_each_entry(fc, &fec_client_list, node) {
503 struct timeval group_duration;
504
505 if (fc->error < 0)
506 continue;
507 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
508 if (tv_diff(&timeout, &group_duration, NULL) < 0)
509 timeout = group_duration;
510 }
511 out:
512 tv_add(now, &timeout, &vsst->eof_barrier);
513 }
514
515 /**
516 * Check if vss status flag \a P (playing) is set.
517 *
518 * \return Greater than zero if playing, zero otherwise.
519 *
520 */
521 unsigned int vss_playing(void)
522 {
523 return mmd->new_vss_status_flags & VSS_PLAYING;
524 }
525
526 /**
527 * Check if the \a N (next) status flag is set.
528 *
529 * \return Greater than zero if set, zero if not.
530 *
531 */
532 unsigned int vss_next(void)
533 {
534 return mmd->new_vss_status_flags & VSS_NEXT;
535 }
536
537 /**
538 * Check if a reposition request is pending.
539 *
540 * \return Greater than zero if true, zero otherwise.
541 *
542 */
543 unsigned int vss_repos(void)
544 {
545 return mmd->new_vss_status_flags & VSS_REPOS;
546 }
547
548 /**
549 * Check if the vss is currently paused.
550 *
551 * \return Greater than zero if paused, zero otherwise.
552 *
553 */
554 unsigned int vss_paused(void)
555 {
556 return !(mmd->new_vss_status_flags & VSS_NEXT)
557 && !(mmd->new_vss_status_flags & VSS_PLAYING);
558 }
559
560 /**
561 * Check if the vss is currently stopped.
562 *
563 * \return Greater than zero if paused, zero otherwise.
564 *
565 */
566 unsigned int vss_stopped(void)
567 {
568 return (mmd->new_vss_status_flags & VSS_NEXT)
569 && !(mmd->new_vss_status_flags & VSS_PLAYING);
570 }
571
572 static int chk_barrier(const char *bname, const struct timeval *barrier,
573 struct timeval *diff, int print_log)
574 {
575 long ms;
576
577 if (tv_diff(now, barrier, diff) > 0)
578 return 1;
579 ms = tv2ms(diff);
580 if (print_log && ms)
581 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
582 return -1;
583 }
584
585 /*
586 * != NULL: timeout for next chunk
587 * NULL: nothing to do
588 */
589 static struct timeval *vss_compute_timeout(struct vss_task *vsst)
590 {
591 static struct timeval the_timeout;
592 struct timeval next_chunk;
593
594 if (vss_next() && vsst->map) {
595 /* only sleep a bit, nec*/
596 the_timeout.tv_sec = 0;
597 the_timeout.tv_usec = 100;
598 return &the_timeout;
599 }
600 if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
601 &the_timeout, 1) < 0)
602 return &the_timeout;
603 if (chk_barrier("eof", &vsst->eof_barrier, &the_timeout, 1) < 0)
604 return &the_timeout;
605 if (chk_barrier("data send", &vsst->data_send_barrier,
606 &the_timeout, 1) < 0)
607 return &the_timeout;
608 if (!vss_playing() || !vsst->map)
609 return NULL;
610 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
611 &mmd->stream_start, &next_chunk);
612 if (chk_barrier("chunk", &next_chunk, &the_timeout, 0) >= 0) {
613 /* chunk is due or bof */
614 the_timeout.tv_sec = 0;
615 the_timeout.tv_usec = 0;
616 return &the_timeout;
617 }
618 /* compute min of current timeout and next slice time */
619 compute_slice_timeout(&the_timeout);
620 return &the_timeout;
621 }
622
623 static void vss_eof(struct vss_task *vsst)
624 {
625
626 if (!vsst->map)
627 return;
628 if (mmd->new_vss_status_flags & VSS_NOMORE)
629 mmd->new_vss_status_flags = VSS_NEXT;
630 set_eof_barrier(vsst);
631 para_munmap(vsst->map, mmd->size);
632 vsst->map = NULL;
633 mmd->chunks_sent = 0;
634 mmd->offset = 0;
635 mmd->afd.afhi.seconds_total = 0;
636 mmd->afd.afhi.chunk_tv.tv_sec = 0;
637 mmd->afd.afhi.chunk_tv.tv_usec = 0;
638 free(mmd->afd.afhi.chunk_table);
639 mmd->afd.afhi.chunk_table = NULL;
640 mmd->mtime = 0;
641 mmd->size = 0;
642 mmd->events++;
643 }
644
645 /**
646 * Get the list of all supported audio formats.
647 *
648 * \return Aa space separated list of all supported audio formats
649 * It is not allocated at runtime, i.e. there is no need to free
650 * the returned string in the caller.
651 */
652 const char *supported_audio_formats(void)
653 {
654 return SUPPORTED_AUDIO_FORMATS;
655 }
656
657 static int need_to_request_new_audio_file(struct vss_task *vsst)
658 {
659 struct timeval diff;
660
661 if (vsst->map) /* have audio file */
662 return 0;
663 if (!vss_playing()) /* don't need one */
664 return 0;
665 if (mmd->new_vss_status_flags & VSS_NOMORE)
666 return 0;
667 if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
668 return 0;
669 if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
670 &diff, 1) < 0)
671 return 0;
672 return 1;
673 }
674
675 /**
676 * Compute the timeout for the main select-loop of the scheduler.
677 *
678 * \param s Pointer to the server scheduler.
679 * \param t Pointer to the vss task structure.
680 *
681 * Before the timeout is computed, the current vss status flags are evaluated
682 * and acted upon by calling appropriate functions from the lower layers.
683 * Possible actions include
684 *
685 * - request a new audio file from afs,
686 * - shutdown of all senders (stop/pause command),
687 * - reposition the stream (ff/jmp command).
688 */
689 static void vss_pre_select(struct sched *s, struct task *t)
690 {
691 int i;
692 struct timeval *tv, diff;
693 struct vss_task *vsst = container_of(t, struct vss_task, task);
694
695 if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
696 struct fec_client *fc, *tmp;
697 for (i = 0; senders[i].name; i++)
698 if (senders[i].shutdown_clients)
699 senders[i].shutdown_clients();
700 list_for_each_entry_safe(fc, tmp, &fec_client_list, node) {
701 fc->first_stream_chunk = -1;
702 fc->error = 0;
703 }
704 mmd->stream_start.tv_sec = 0;
705 mmd->stream_start.tv_usec = 0;
706 }
707 if (vss_next())
708 vss_eof(vsst);
709 else if (vss_paused()) {
710 if (mmd->chunks_sent)
711 set_eof_barrier(vsst);
712 mmd->chunks_sent = 0;
713 } else if (vss_repos()) {
714 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
715 set_eof_barrier(vsst);
716 mmd->chunks_sent = 0;
717 mmd->current_chunk = mmd->repos_request;
718 mmd->new_vss_status_flags &= ~VSS_REPOS;
719 }
720 if (need_to_request_new_audio_file(vsst)) {
721 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
722 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
723 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
724 } else
725 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
726 for (i = 0; senders[i].name; i++) {
727 if (!senders[i].pre_select)
728 continue;
729 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
730 }
731 tv = vss_compute_timeout(vsst);
732 if (tv && tv_diff(tv, &s->timeout, &diff) < 0)
733 s->timeout = *tv;
734 }
735
736 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
737 {
738 char control[255], buf[8];
739 struct msghdr msg = {.msg_iov = NULL};
740 struct cmsghdr *cmsg;
741 struct iovec iov;
742 int ret = 0;
743
744 *fd = -1;
745 iov.iov_base = buf;
746 iov.iov_len = sizeof(buf);
747 msg.msg_iov = &iov;
748 msg.msg_iovlen = 1;
749 msg.msg_control = control;
750 msg.msg_controllen = sizeof(control);
751 memset(buf, 0, sizeof(buf));
752 ret = recvmsg(afs_socket, &msg, 0);
753 if (ret < 0)
754 return -ERRNO_TO_PARA_ERROR(errno);
755 if (iov.iov_len != sizeof(buf))
756 return -E_AFS_SHORT_READ;
757 *code = *(uint32_t*)buf;
758 *data = *(uint32_t*)(buf + 4);
759 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
760 if (cmsg->cmsg_level != SOL_SOCKET
761 || cmsg->cmsg_type != SCM_RIGHTS)
762 continue;
763 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
764 continue;
765 *fd = *(int *)CMSG_DATA(cmsg);
766 }
767 return 1;
768 }
769
770 static void recv_afs_result(struct vss_task *vsst)
771 {
772 int ret, passed_fd, shmid;
773 uint32_t afs_code = 0, afs_data = 0;
774 struct stat statbuf;
775
776 vsst->afsss = AFS_SOCKET_READY;
777 ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
778 if (ret < 0)
779 goto err;
780 PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
781 afs_data);
782 ret = -E_NOFD;
783 if (afs_code != NEXT_AUDIO_FILE)
784 goto err;
785 if (passed_fd < 0)
786 goto err;
787 shmid = afs_data;
788 ret = load_afd(shmid, &mmd->afd);
789 if (ret < 0)
790 goto err;
791 shm_destroy(shmid);
792 ret = fstat(passed_fd, &statbuf);
793 if (ret < 0) {
794 PARA_ERROR_LOG("fstat error:\n");
795 ret = -ERRNO_TO_PARA_ERROR(errno);
796 goto err;
797 }
798 mmd->size = statbuf.st_size;
799 mmd->mtime = statbuf.st_mtime;
800 ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
801 0, &vsst->map);
802 if (ret < 0)
803 goto err;
804 close(passed_fd);
805 mmd->chunks_sent = 0;
806 mmd->current_chunk = 0;
807 mmd->offset = 0;
808 mmd->events++;
809 mmd->num_played++;
810 mmd->new_vss_status_flags &= (~VSS_NEXT);
811 afh_get_header(&mmd->afd.afhi, vsst->map, &vsst->header_buf,
812 &vsst->header_len);
813 return;
814 err:
815 free(mmd->afd.afhi.chunk_table);
816 if (passed_fd >= 0)
817 close(passed_fd);
818 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
819 mmd->new_vss_status_flags = VSS_NEXT;
820 }
821
822 /**
823 * Main sending function.
824 *
825 * This function gets called from vss_post_select(). It checks whether the next
826 * chunk of data should be pushed out. It obtains a pointer to the data to be
827 * sent out as well as its length from mmd->afd.afhi. This information is then
828 * passed to each supported sender's send() function as well as to the send()
829 * functions of each registered fec client.
830 */
831 static void vss_send(struct vss_task *vsst)
832 {
833 int i, fec_active = 0;
834 struct timeval due;
835 struct fec_client *fc, *tmp_fc;
836
837 if (!vsst->map || !vss_playing())
838 return;
839 if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
840 return;
841 if (chk_barrier("data send", &vsst->data_send_barrier,
842 &due, 1) < 0)
843 return;
844 list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
845 if (fc->error < 0)
846 continue;
847 if (!next_slice_is_due(fc, NULL)) {
848 fec_active = 1;
849 continue;
850 }
851 if (compute_next_fec_slice(fc, vsst) <= 0)
852 continue;
853 PARA_DEBUG_LOG("sending %d:%d (%u bytes)\n", fc->group.num,
854 fc->current_slice_num, fc->fcp->max_slice_bytes);
855 fc->fcp->send((char *)fc->enc_buf,
856 fc->fcp->max_slice_bytes,
857 fc->fcp->private_data);
858 fc->current_slice_num++;
859 fec_active = 1;
860 }
861 if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
862 if (!fec_active)
863 mmd->new_vss_status_flags |= VSS_NEXT;
864 return;
865 }
866 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
867 &mmd->stream_start, &due);
868 if (tv_diff(&due, now, NULL) <= 0) {
869 const char *buf;
870 size_t len;
871
872 if (!mmd->chunks_sent) {
873 struct timeval tmp;
874 mmd->stream_start = *now;
875 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &tmp);
876 mmd->offset = tv2ms(&tmp);
877 mmd->events++;
878 }
879 /*
880 * We call the send function also in case of empty chunks as
881 * they might have still some data queued which can be sent in
882 * this case.
883 */
884 afh_get_chunk(mmd->current_chunk, &mmd->afd.afhi, vsst->map,
885 &buf, &len);
886 for (i = 0; senders[i].name; i++) {
887 if (!senders[i].send)
888 continue;
889 senders[i].send(mmd->current_chunk, mmd->chunks_sent,
890 buf, len, vsst->header_buf, vsst->header_len);
891 }
892 mmd->chunks_sent++;
893 mmd->current_chunk++;
894 }
895 }
896
897 static void vss_post_select(struct sched *s, struct task *t)
898 {
899 int ret, i;
900 struct vss_task *vsst = container_of(t, struct vss_task, task);
901
902
903 if (mmd->sender_cmd_data.cmd_num >= 0) {
904 int num = mmd->sender_cmd_data.cmd_num,
905 sender_num = mmd->sender_cmd_data.sender_num;
906
907 if (senders[sender_num].client_cmds[num])
908 senders[sender_num].client_cmds[num](&mmd->sender_cmd_data);
909 mmd->sender_cmd_data.cmd_num = -1;
910 }
911 if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE) {
912 if (FD_ISSET(vsst->afs_socket, &s->rfds))
913 recv_afs_result(vsst);
914 } else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
915 PARA_NOTICE_LOG("requesting new fd from afs\n");
916 ret = send_buffer(vsst->afs_socket, "new");
917 if (ret < 0)
918 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
919 else
920 vsst->afsss = AFS_SOCKET_AFD_PENDING;
921 }
922 for (i = 0; senders[i].name; i++) {
923 if (!senders[i].post_select)
924 continue;
925 senders[i].post_select(&s->rfds, &s->wfds);
926 }
927 if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
928 (vss_next() && vss_playing()))
929 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
930 vss_send(vsst);
931 }
932
933 /**
934 * Initialize the virtual streaming system task.
935 *
936 * \param afs_socket The fd for communication with afs.
937 *
938 * This also initializes all supported senders and starts streaming
939 * if the --autoplay command line flag was given.
940 */
941 void init_vss_task(int afs_socket)
942 {
943 static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
944 int i;
945 char *hn = para_hostname(), *home = para_homedir();
946 long unsigned announce_time = conf.announce_time_arg > 0?
947 conf.announce_time_arg : 300,
948 autoplay_delay = conf.autoplay_delay_arg > 0?
949 conf.autoplay_delay_arg : 0;
950 vsst->header_interval.tv_sec = 5; /* should this be configurable? */
951 vsst->afs_socket = afs_socket;
952 vsst->task.pre_select = vss_pre_select;
953 vsst->task.post_select = vss_post_select;
954 ms2tv(announce_time, &vsst->announce_tv);
955 PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
956 INIT_LIST_HEAD(&fec_client_list);
957 for (i = 0; senders[i].name; i++) {
958 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
959 senders[i].init(&senders[i]);
960 }
961 free(hn);
962 free(home);
963 mmd->sender_cmd_data.cmd_num = -1;
964 if (conf.autoplay_given) {
965 struct timeval tmp;
966 mmd->vss_status_flags |= VSS_PLAYING;
967 mmd->new_vss_status_flags |= VSS_PLAYING;
968 ms2tv(autoplay_delay, &tmp);
969 tv_add(now, &tmp, &vsst->autoplay_barrier);
970 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
971 &vsst->data_send_barrier);
972 }
973 register_task(&vsst->task);
974 }