1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file vss.c The virtual streaming system.
5 * This contains the audio streaming code of para_server which is independent
6 * of the current audio format, audio file selector and of the activated
10 #include <sys/socket.h>
11 #include <netinet/in.h>
14 #include <sys/types.h>
15 #include <arpa/inet.h>
20 #include "server.lsg.h"
23 #include "portable_io.h"
37 extern struct misc_meta_data *mmd;
38 extern const struct sender udp_sender, dccp_sender, http_sender;
39 const struct sender * const senders[] = {
40 &http_sender, &dccp_sender, &udp_sender, NULL};
42 /** The possible states of the afs socket. */
43 enum afs_socket_status {
44 /** Socket is inactive. */
46 /** Socket fd was included in the write fd set for select(). */
47 AFS_SOCKET_CHECK_FOR_WRITE,
48 /** vss wrote a request to the socket and waits for reply from afs. */
49 AFS_SOCKET_AFD_PENDING
52 /** The task structure for the virtual streaming system. */
54 /** Copied from the -announce_time command line option. */
55 struct timeval announce_tv;
56 /** End of the announcing interval. */
57 struct timeval data_send_barrier;
58 /** End of the EOF interval. */
59 struct timeval eof_barrier;
60 /** Only used if --autoplay_delay was given. */
61 struct timeval autoplay_barrier;
62 /** Used for afs-server communication. */
64 /** The current state of \a afs_socket. */
65 enum afs_socket_status afsss;
66 /** The memory mapped audio file. */
68 /** The size of the memory mapping. */
70 /** Used by the scheduler. */
72 /** Pointer to the header of the mapped audio file. */
74 /** Length of the audio file header. */
76 /** Time between audio file headers are sent. */
77 struct timeval header_interval;
78 /* Only used if afh supports dynamic chunks. */
83 * The list of currently connected fec clients.
85 * Senders may use \ref vss_add_fec_client() to add entries to the list.
87 static struct list_head fec_client_list;
90 * Data associated with one FEC group.
92 * A FEC group consists of a fixed number of slices and this number is given by
93 * the \a slices_per_group parameter of struct \ref fec_client_parms. Each FEC
94 * group contains a number of chunks of the current audio file.
96 * FEC slices directly correspond to the data packages sent by the paraslash
97 * senders that use FEC. Each slice is identified by its group number and its
98 * number within the group. All slices have the same size, but the last slice
99 * of the group may not be filled entirely.
102 /** The number of the FEC group. */
104 /** Number of bytes in this group. */
106 /** The first chunk of the current audio file belonging to the group. */
107 uint32_t first_chunk;
108 /** The number of chunks contained in this group. */
110 /** When the first chunk was sent. */
111 struct timeval start;
112 /** The duration of the full group. */
113 struct timeval duration;
114 /** The group duration divided by the number of slices. */
115 struct timeval slice_duration;
116 /** Group contains the audio file header that occupies that many slices. */
117 uint8_t num_header_slices;
118 /** Number of bytes per slice for this group. */
119 uint16_t slice_bytes;
122 /** A FEC client is always in one of these states. */
123 enum fec_client_state {
124 FEC_STATE_NONE = 0, /**< not initialized and not enabled */
125 FEC_STATE_DISABLED, /**< temporarily disabled */
126 FEC_STATE_READY_TO_RUN /**< initialized and enabled */
130 * Describes one connected FEC client.
133 /** Current state of the client */
134 enum fec_client_state state;
135 /** The connected sender client (transport layer). */
136 struct sender_client *sc;
137 /** Parameters requested by the client. */
138 struct fec_client_parms *fcp;
139 /** Used by the core FEC code. */
140 struct fec_parms *parms;
141 /** The position of this client in the fec client list. */
142 struct list_head node;
143 /** When the first slice for this client was sent. */
144 struct timeval stream_start;
145 /** The first chunk sent to this FEC client. */
146 int first_stream_chunk;
147 /** Describes the current group. */
148 struct fec_group group;
149 /** The current slice. */
150 uint8_t current_slice_num;
151 /** The data to be FEC-encoded (point to a region within the mapped audio file). */
152 const unsigned char **src_data;
153 /** Last time an audio header was sent. */
154 struct timeval next_header_time;
155 /** Used for the last source pointer of an audio file. */
156 unsigned char *extra_src_buf;
157 /** Needed for the last slice of the audio file header. */
158 unsigned char *extra_header_buf;
159 /** Extra slices needed to store largest chunk + header. */
160 int num_extra_slices;
161 /** Contains the FEC-encoded data. */
162 unsigned char *enc_buf;
163 /** Maximal packet size. */
168 * Get the chunk time of the current audio file.
170 * \return A pointer to a struct containing the chunk time, or NULL,
171 * if currently no audio file is selected.
173 struct timeval *vss_chunk_time(void)
175 if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
176 mmd->afd.afhi.chunk_tv.tv_usec == 0)
178 return &mmd->afd.afhi.chunk_tv;
182 * Write a fec header to a buffer.
184 * \param buf The buffer to write to.
185 * \param h The fec header to write.
187 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
189 char *buf = (char *)fc->enc_buf;
190 struct fec_group *g = &fc->group;
191 struct fec_client_parms *p = fc->fcp;
193 write_u32(buf, FEC_MAGIC);
195 write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
196 write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
197 write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
199 write_u32(buf + 10, g->num);
200 write_u32(buf + 14, g->bytes);
202 write_u8(buf + 18, fc->current_slice_num);
203 write_u8(buf + 19, 0); /* unused */
204 write_u16(buf + 20, g->slice_bytes);
205 write_u8(buf + 22, g->first_chunk? 0 : 1);
206 write_u8(buf + 23, vsst->header_len? 1 : 0);
207 memset(buf + 24, 0, 8);
210 static bool need_audio_header(struct fec_client *fc, struct vss_task *vsst)
212 if (!mmd->current_chunk) {
213 tv_add(now, &vsst->header_interval, &fc->next_header_time);
216 if (!vsst->header_buf)
218 if (vsst->header_len == 0)
220 if (fc->group.num > 0) {
221 if (!fc->fcp->need_periodic_header)
223 if (tv_diff(&fc->next_header_time, now, NULL) > 0)
226 tv_add(now, &vsst->header_interval, &fc->next_header_time);
230 static bool need_data_slices(struct fec_client *fc, struct vss_task *vsst)
232 if (fc->group.num > 0)
234 if (!vsst->header_buf)
236 if (vsst->header_len == 0)
238 if (fc->fcp->need_periodic_header)
243 static int num_slices(long unsigned bytes, int max_payload, int rs)
247 assert(max_payload > 0);
249 ret = DIV_ROUND_UP(bytes, max_payload);
255 /* set group start and group duration */
256 static void set_group_timing(struct fec_client *fc, struct vss_task *vsst)
258 struct fec_group *g = &fc->group;
259 struct timeval *chunk_tv = vss_chunk_time();
261 if (!need_data_slices(fc, vsst))
262 ms2tv(200, &g->duration);
264 tv_scale(g->num_chunks, chunk_tv, &g->duration);
265 tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
266 &g->duration, &g->slice_duration);
267 PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
268 tv2ms(&g->duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
271 static int initialize_fec_client(struct fec_client *fc, struct vss_task *vsst)
274 int hs, ds, rs; /* header/data/redundant slices */
275 struct fec_client_parms *fcp = fc->fcp;
280 * Set the maximum slice size to the Maximum Packet Size if the
281 * transport protocol allows determination of this value. The user
282 * can specify a slice size up to this value.
284 ret = fcp->init_fec(fc->sc);
289 fc->mps = generic_max_transport_msg_size(fc->sc->fd);
290 if (fc->mps <= FEC_HEADER_SIZE)
291 return -ERRNO_TO_PARA_ERROR(EINVAL);
293 rs = fc->fcp->slices_per_group - fc->fcp->data_slices_per_group;
294 ret = num_slices(vsst->header_len, fc->mps - FEC_HEADER_SIZE, rs);
298 ret = num_slices(mmd->afd.max_chunk_size, fc->mps - FEC_HEADER_SIZE, rs);
302 if (fc->fcp->need_periodic_header)
305 k = PARA_MAX(hs, ds);
306 if (k < fc->fcp->data_slices_per_group)
307 k = fc->fcp->data_slices_per_group;
308 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
311 ret = fec_new(k, n, &fc->parms);
314 PARA_INFO_LOG("mps: %d, k: %d, n: %d, extra slices: %d\n",
315 fc->mps, k, n, fc->num_extra_slices);
316 fc->src_data = para_realloc(fc->src_data, k * sizeof(char *));
317 fc->enc_buf = para_realloc(fc->enc_buf, fc->mps);
318 fc->extra_src_buf = para_realloc(fc->extra_src_buf, fc->mps);
319 fc->extra_header_buf = para_realloc(fc->extra_header_buf, fc->mps);
321 fc->state = FEC_STATE_READY_TO_RUN;
322 fc->next_header_time.tv_sec = 0;
323 fc->stream_start = *now;
324 fc->first_stream_chunk = mmd->current_chunk;
328 static int vss_get_chunk(int chunk_num, struct vss_task *vsst,
329 char **buf, size_t *sz)
334 * Chunk zero is special for header streams: It is the first portion of
335 * the audio file which consists of the audio file header. It may be
336 * arbitrary large due to embedded meta data. Audio format handlers may
337 * replace the header by a stripped one with meta data omitted which is
338 * of bounded size. We always use the stripped header for streaming
339 * rather than the unmodified header (chunk zero).
341 if (chunk_num == 0 && vsst->header_len > 0) {
342 assert(vsst->header_buf);
343 *buf = vsst->header_buf; /* stripped header */
344 *sz = vsst->header_len;
347 ret = afh_get_chunk(chunk_num, &mmd->afd.afhi,
348 mmd->afd.audio_format_id, vsst->map, vsst->mapsize,
349 (const char **)buf, sz, &vsst->afh_context);
357 static int compute_group_size(struct vss_task *vsst, struct fec_group *g,
362 int ret, i, max_chunks = PARA_MAX(1LU, 150 / tv2ms(vss_chunk_time()));
364 if (g->first_chunk == 0) {
366 ret = vss_get_chunk(0, vsst, &buf, &len);
376 * Include chunks into the group until the group duration is at least
377 * 150ms. For ogg and wma, a single chunk's duration (ogg page/wma
378 * super frame) is already larger than 150ms, so a FEC group consists
379 * of exactly one chunk for these audio formats.
382 int chunk_num = g->first_chunk + i;
384 if (g->bytes > 0 && i >= max_chunks) /* duration limit */
386 if (chunk_num >= mmd->afd.afhi.chunks_total) /* eof */
388 ret = vss_get_chunk(chunk_num, vsst, &buf, &len);
391 if (g->bytes + len > max_bytes)
393 /* Include this chunk */
397 assert(g->num_chunks);
402 * Compute the slice size of the next group.
404 * The FEC parameters n and k are fixed but the slice size varies per
405 * FEC group. We'd like to choose slices as small as possible to avoid
406 * unnecessary FEC calculations but large enough to guarantee that the
407 * k data slices suffice to encode the header (if needed) and the data
410 * Once we know the payload of the next group, we define the number s
411 * of bytes per slice for this group by
413 * s = ceil(payload / k)
415 * However, for header streams, computing s is more complicated since no
416 * overlapping of header and data slices is possible. Hence we have k >=
417 * 2 and s must satisfy
419 * (*) ceil(h / s) + ceil(d / s) <= k
421 * where h and d are payload of the header and the data chunk(s)
422 * respectively. In general there is no value for s such that (*)
423 * becomes an equality, for example if h = 4000, d = 5000 and k = 10.
425 * We use the following approach for computing a suitable value for s:
428 * k1 := ceil(k * min(h, d) / (h + d)),
431 * Note that k >= 2 implies k1 > 0 and k2 > 0, so
433 * s := max(ceil(min(h, d) / k1), ceil(max(h, d) / k2))
435 * is well-defined. Inequality (*) holds for this value of s since k1
436 * slices suffice to store min(h, d) while k2 slices suffice to store
437 * max(h, d), i.e. the first addent of (*) is bounded by k1 and the
440 * For the above example we obtain
442 * k1 = ceil(10 * 4000 / 9000) = 5, k2 = 5,
443 * s = max(4000 / 5, 5000 / 5) = 1000,
445 * which is optimal since a slice size of 999 bytes would already require
448 static int compute_slice_size(struct fec_client *fc, struct vss_task *vsst)
450 struct fec_group *g = &fc->group;
451 int k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
452 int n = fc->fcp->slices_per_group + fc->num_extra_slices;
453 int ret, k1, k2, h, d, min, max, sum;
454 int max_slice_bytes = fc->mps - FEC_HEADER_SIZE;
457 if (!need_audio_header(fc, vsst)) {
458 max_group_bytes = k * max_slice_bytes;
459 g->num_header_slices = 0;
460 ret = compute_group_size(vsst, g, max_group_bytes);
463 g->slice_bytes = DIV_ROUND_UP(g->bytes, k);
464 if (g->slice_bytes == 0)
468 if (!need_data_slices(fc, vsst)) {
471 g->slice_bytes = DIV_ROUND_UP(vsst->header_len, k);
472 g->num_header_slices = k;
475 h = vsst->header_len;
476 max_group_bytes = (k - num_slices(h, max_slice_bytes, n - k))
478 ret = compute_group_size(vsst, g, max_group_bytes);
483 g->slice_bytes = DIV_ROUND_UP(h, k);
484 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
487 g->num_header_slices = ret;
490 min = PARA_MIN(h, d);
491 max = PARA_MAX(h, d);
493 k1 = DIV_ROUND_UP(k * min, sum);
498 g->slice_bytes = PARA_MAX(DIV_ROUND_UP(min, k1), DIV_ROUND_UP(max, k2));
500 * This value of s := g->slice_bytes satisfies inequality (*) above,
501 * but it might be larger than max_slice_bytes. However, we know that
502 * max_slice_bytes are sufficient to store header and data, so:
504 g->slice_bytes = PARA_MIN((int)g->slice_bytes, max_slice_bytes);
506 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
509 g->num_header_slices = ret;
513 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
515 int ret, i, k, n, data_slices;
518 struct fec_group *g = &fc->group;
520 if (fc->state == FEC_STATE_NONE) {
521 ret = initialize_fec_client(fc, vsst);
524 g->first_chunk = mmd->current_chunk;
529 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
532 * Start and duration of this group depend only on the previous
533 * group. Compute the new group start as g->start += g->duration.
536 tv_add(&tmp, &g->duration, &g->start);
537 set_group_timing(fc, vsst);
538 g->first_chunk += g->num_chunks;
541 k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
542 n = fc->fcp->slices_per_group + fc->num_extra_slices;
544 compute_slice_size(fc, vsst);
545 assert(g->slice_bytes > 0);
546 ret = num_slices(g->bytes, g->slice_bytes, n - k);
550 assert(g->num_header_slices + data_slices <= k);
551 fc->current_slice_num = 0;
553 set_group_timing(fc, vsst);
554 /* setup header slices */
555 buf = vsst->header_buf;
556 for (i = 0; i < g->num_header_slices; i++) {
557 uint32_t payload_size;
558 if (buf + g->slice_bytes <= vsst->header_buf + vsst->header_len) {
559 fc->src_data[i] = (const unsigned char *)buf;
560 buf += g->slice_bytes;
564 * Can not use vss->header_buf for this slice as it
565 * goes beyond the buffer. This slice will not be fully
568 payload_size = vsst->header_buf + vsst->header_len - buf;
569 memcpy(fc->extra_header_buf, buf, payload_size);
570 if (payload_size < g->slice_bytes)
571 memset(fc->extra_header_buf + payload_size, 0,
572 g->slice_bytes - payload_size);
574 * There might be more than one header slice to fill although
575 * only the first one will be used. Set all header slices to
578 while (i < g->num_header_slices)
579 fc->src_data[i++] = fc->extra_header_buf;
580 break; /* we don't want i to be increased. */
584 * Setup data slices. Note that for ogg streams chunk 0 points to a
585 * buffer on the heap rather than to the mapped audio file.
587 ret = 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) {
593 * We must make a copy for this slice since using p
594 * directly would exceed the buffer.
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;
606 fc->src_data[i] = (const unsigned char *)p;
610 /* use arbitrary data for all remaining slices */
613 fc->src_data[i] = (const unsigned char *)buf;
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
619 PARA_DEBUG_LOG("slice_bytes: %d, %d header slices, %d data slices\n",
620 g->slice_bytes, g->num_header_slices, data_slices
625 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
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);
633 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
634 PARA_ERROR_LOG("FEC client temporarily disabled\n");
635 fc->state = FEC_STATE_DISABLED;
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);
646 * Return a buffer that marks the end of the stream.
648 * \param buf Result pointer.
649 * \return The length of the eof buffer.
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.
654 size_t vss_get_fec_eof_packet(const char **buf)
656 static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
657 *buf = fec_eof_packet;
658 return FEC_HEADER_SIZE;
662 * Add one entry to the list of active fec clients.
664 * \param sc Generic sender_client data of the transport layer.
665 * \param fcp FEC parameters as supplied by the transport layer.
667 * \return Newly allocated fec_client struct.
669 struct fec_client *vss_add_fec_client(struct sender_client *sc,
670 struct fec_client_parms *fcp)
672 struct fec_client *fc = para_calloc(sizeof(*fc));
676 para_list_add(&fc->node, &fec_client_list);
681 * Remove one entry from the list of active fec clients.
683 * \param fc The client to be removed.
685 void vss_del_fec_client(struct fec_client *fc)
690 free(fc->extra_src_buf);
691 free(fc->extra_header_buf);
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
700 * next = stream_start + (first_group_chunk - first_stream_chunk)
701 * * chunk_time + slice_num * slice_time
703 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
705 struct timeval tmp, next;
708 if (fc->state == FEC_STATE_NONE)
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;
716 static void set_eof_barrier(struct vss_task *vsst)
718 struct fec_client *fc;
719 struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
723 list_for_each_entry(fc, &fec_client_list, node) {
724 struct timeval group_duration;
726 if (fc->state != FEC_STATE_READY_TO_RUN)
728 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
729 if (tv_diff(&timeout, &group_duration, NULL) < 0)
730 timeout = group_duration;
733 tv_add(now, &timeout, &vsst->eof_barrier);
737 * Check if vss status flag \a P (playing) is set.
739 * \return Greater than zero if playing, zero otherwise.
742 unsigned int vss_playing(void)
744 return mmd->new_vss_status_flags & VSS_PLAYING;
748 * Check if the \a N (next) status flag is set.
750 * \return Greater than zero if set, zero if not.
753 unsigned int vss_next(void)
755 return mmd->new_vss_status_flags & VSS_NEXT;
759 * Check if a reposition request is pending.
761 * \return Greater than zero if true, zero otherwise.
764 unsigned int vss_repos(void)
766 return mmd->new_vss_status_flags & VSS_REPOS;
770 * Check if the vss is currently paused.
772 * \return Greater than zero if paused, zero otherwise.
775 unsigned int vss_paused(void)
777 return !(mmd->new_vss_status_flags & VSS_NEXT)
778 && !(mmd->new_vss_status_flags & VSS_PLAYING);
782 * Check if the vss is currently stopped.
784 * \return Greater than zero if paused, zero otherwise.
787 unsigned int vss_stopped(void)
789 return (mmd->new_vss_status_flags & VSS_NEXT)
790 && !(mmd->new_vss_status_flags & VSS_PLAYING);
793 static int chk_barrier(const char *bname, const struct timeval *barrier,
794 struct timeval *diff, int print_log)
798 if (tv_diff(now, barrier, diff) > 0)
802 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
806 static void vss_compute_timeout(struct sched *s, struct vss_task *vsst)
809 struct fec_client *fc;
811 if (!vss_playing() || !vsst->map)
813 if (vss_next() && vsst->map) /* only sleep a bit, nec*/
814 return sched_request_timeout_ms(100, s);
816 /* Each of these barriers must have passed until we may proceed */
817 if (sched_request_barrier(&vsst->autoplay_barrier, s) == 1)
819 if (sched_request_barrier(&vsst->eof_barrier, s) == 1)
821 if (sched_request_barrier(&vsst->data_send_barrier, s) == 1)
824 * Compute the select timeout as the minimal time until the next
825 * chunk/slice is due for any client.
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)
831 list_for_each_entry(fc, &fec_client_list, node) {
832 if (fc->state != FEC_STATE_READY_TO_RUN)
834 if (next_slice_is_due(fc, &tv))
835 return sched_min_delay(s);
836 sched_request_timeout(&tv, s);
840 static void vss_eof(struct vss_task *vsst)
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, vsst->mapsize);
852 mmd->chunks_sent = 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;
860 afh_close(vsst->afh_context, mmd->afd.audio_format_id);
861 vsst->afh_context = NULL;
865 static int need_to_request_new_audio_file(struct vss_task *vsst)
869 if (vsst->map) /* have audio file */
871 if (!vss_playing()) /* don't need one */
873 if (mmd->new_vss_status_flags & VSS_NOMORE)
875 if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
877 if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
883 static void set_mmd_offset(void)
885 struct timeval offset;
886 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
887 mmd->offset = tv2ms(&offset);
890 static void vss_pre_select(struct sched *s, void *context)
893 struct vss_task *vsst = context;
895 if (need_to_request_new_audio_file(vsst)) {
896 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
897 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
898 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
900 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
902 if (!senders[i]->pre_select)
904 senders[i]->pre_select(&s->max_fileno, &s->rfds, &s->wfds);
906 vss_compute_timeout(s, vsst);
909 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
911 char control[255] __a_aligned(8), buf[8];
912 struct msghdr msg = {.msg_iov = NULL};
913 struct cmsghdr *cmsg;
919 iov.iov_len = sizeof(buf);
922 msg.msg_control = control;
923 msg.msg_controllen = sizeof(control);
924 memset(buf, 0, sizeof(buf));
925 ret = recvmsg(afs_socket, &msg, 0);
927 return -ERRNO_TO_PARA_ERROR(errno);
928 if (iov.iov_len != sizeof(buf))
929 return -E_AFS_SHORT_READ;
930 *code = *(uint32_t*)buf;
931 *data = *(uint32_t*)(buf + 4);
932 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
933 if (cmsg->cmsg_level != SOL_SOCKET
934 || cmsg->cmsg_type != SCM_RIGHTS)
936 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
938 *fd = *(int *)CMSG_DATA(cmsg);
944 /** As of 2018, neither FreeBSD-11.2 nor NetBSD-8.0 have MAP_POPULATE. */
945 #define MAP_POPULATE 0
948 static void recv_afs_result(struct vss_task *vsst, fd_set *rfds)
950 int ret, passed_fd, shmid;
951 uint32_t afs_code = 0, afs_data = 0;
954 if (!FD_ISSET(vsst->afs_socket, rfds))
956 ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
957 if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
961 vsst->afsss = AFS_SOCKET_READY;
963 if (afs_code != NEXT_AUDIO_FILE) {
964 PARA_ERROR_LOG("afs code: %u, expected: %d\n", afs_code,
971 ret = load_afd(shmid, &mmd->afd);
975 ret = fstat(passed_fd, &statbuf);
977 PARA_ERROR_LOG("fstat error:\n");
978 ret = -ERRNO_TO_PARA_ERROR(errno);
981 ret = para_mmap(statbuf.st_size, PROT_READ, MAP_PRIVATE | MAP_POPULATE,
982 passed_fd, &vsst->map);
985 vsst->mapsize = statbuf.st_size;
987 mmd->chunks_sent = 0;
988 mmd->current_chunk = 0;
992 mmd->new_vss_status_flags &= (~VSS_NEXT);
993 afh_get_header(&mmd->afd.afhi, mmd->afd.audio_format_id,
994 vsst->map, vsst->mapsize, &vsst->header_buf, &vsst->header_len);
997 free(mmd->afd.afhi.chunk_table);
1000 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1001 mmd->new_vss_status_flags = VSS_NEXT;
1005 * Main sending function.
1007 * This function gets called from vss_post_select(). It checks whether the next
1008 * chunk of data should be pushed out. It obtains a pointer to the data to be
1009 * sent out as well as its length from mmd->afd.afhi. This information is then
1010 * passed to each supported sender's send() function as well as to the send()
1011 * functions of each registered fec client.
1013 static void vss_send(struct vss_task *vsst)
1016 bool fec_active = false;
1018 struct fec_client *fc, *tmp_fc;
1022 if (!vsst->map || !vss_playing())
1024 if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
1026 if (chk_barrier("data send", &vsst->data_send_barrier, &due, 1) < 0)
1028 list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
1029 if (fc->state == FEC_STATE_DISABLED)
1031 if (!next_slice_is_due(fc, NULL)) {
1035 if (compute_next_fec_slice(fc, vsst) <= 0)
1037 PARA_DEBUG_LOG("sending %u:%u (%u bytes)\n", fc->group.num,
1038 fc->current_slice_num, fc->group.slice_bytes);
1039 fc->current_slice_num++;
1040 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf,
1041 fc->group.slice_bytes + FEC_HEADER_SIZE);
1044 if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
1046 mmd->new_vss_status_flags |= VSS_NEXT;
1049 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
1050 &mmd->stream_start, &due);
1051 if (tv_diff(&due, now, NULL) > 0)
1053 if (!mmd->chunks_sent) {
1054 mmd->stream_start = *now;
1058 ret = vss_get_chunk(mmd->current_chunk, vsst, &buf, &len);
1060 PARA_ERROR_LOG("could not get chunk %lu: %s\n",
1061 mmd->current_chunk, para_strerror(-ret));
1064 * We call ->send() even if len is zero because senders might
1065 * have data queued which can be sent now.
1067 FOR_EACH_SENDER(i) {
1068 if (!senders[i]->send)
1070 senders[i]->send(mmd->current_chunk, mmd->chunks_sent,
1071 buf, len, vsst->header_buf, vsst->header_len);
1075 mmd->current_chunk++;
1078 static int vss_post_select(struct sched *s, void *context)
1081 struct vss_task *vsst = context;
1083 ret = task_get_notification(vsst->task);
1085 afh_free_header(vsst->header_buf, mmd->afd.audio_format_id);
1088 if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
1089 /* shut down senders and fec clients */
1090 struct fec_client *fc, *tmp;
1092 if (senders[i]->shutdown_clients)
1093 senders[i]->shutdown_clients();
1094 list_for_each_entry_safe(fc, tmp, &fec_client_list, node)
1095 fc->state = FEC_STATE_NONE;
1096 mmd->stream_start.tv_sec = 0;
1097 mmd->stream_start.tv_usec = 0;
1101 else if (vss_paused()) {
1102 if (mmd->chunks_sent)
1103 set_eof_barrier(vsst);
1104 mmd->chunks_sent = 0;
1105 } else if (vss_repos()) { /* repositioning due to ff/jmp command */
1106 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1107 set_eof_barrier(vsst);
1108 mmd->chunks_sent = 0;
1109 mmd->current_chunk = afh_get_start_chunk(mmd->repos_request,
1110 &mmd->afd.afhi, mmd->afd.audio_format_id);
1111 mmd->new_vss_status_flags &= ~VSS_REPOS;
1114 /* If a sender command is pending, run it. */
1115 if (mmd->sender_cmd_data.cmd_num >= 0) {
1116 int num = mmd->sender_cmd_data.cmd_num,
1117 sender_num = mmd->sender_cmd_data.sender_num;
1119 if (senders[sender_num]->client_cmds[num]) {
1120 ret = senders[sender_num]->client_cmds[num]
1121 (&mmd->sender_cmd_data);
1123 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1125 mmd->sender_cmd_data.cmd_num = -1;
1127 if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
1128 recv_afs_result(vsst, &s->rfds);
1129 else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
1130 PARA_NOTICE_LOG("requesting new fd from afs\n");
1131 ret = write_buffer(vsst->afs_socket, "new");
1133 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
1135 vsst->afsss = AFS_SOCKET_AFD_PENDING;
1137 FOR_EACH_SENDER(i) {
1138 if (!senders[i]->post_select)
1140 senders[i]->post_select(&s->rfds, &s->wfds);
1142 if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
1143 (vss_next() && vss_playing()))
1144 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1150 * Initialize the virtual streaming system task.
1152 * \param afs_socket The fd for communication with afs.
1153 * \param s The scheduler to register the vss task to.
1155 * This also initializes all supported senders and starts streaming
1156 * if the --autoplay command line flag was given.
1158 void vss_init(int afs_socket, struct sched *s)
1160 static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
1162 long unsigned announce_time = OPT_UINT32_VAL(ANNOUNCE_TIME),
1163 autoplay_delay = OPT_UINT32_VAL(AUTOPLAY_DELAY);
1164 vsst->header_interval.tv_sec = 5; /* should this be configurable? */
1165 vsst->afs_socket = afs_socket;
1166 ms2tv(announce_time, &vsst->announce_tv);
1167 PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
1168 INIT_LIST_HEAD(&fec_client_list);
1169 FOR_EACH_SENDER(i) {
1170 PARA_NOTICE_LOG("initializing %s sender\n", senders[i]->name);
1173 mmd->sender_cmd_data.cmd_num = -1;
1174 if (OPT_GIVEN(AUTOPLAY)) {
1176 mmd->vss_status_flags |= VSS_PLAYING;
1177 mmd->new_vss_status_flags |= VSS_PLAYING;
1178 ms2tv(autoplay_delay, &tmp);
1179 tv_add(clock_get_realtime(NULL), &tmp, &vsst->autoplay_barrier);
1180 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1181 &vsst->data_send_barrier);
1183 vsst->task = task_register(&(struct task_info) {
1185 .pre_select = vss_pre_select,
1186 .post_select = vss_post_select,
1192 * Turn off the virtual streaming system.
1194 * This is only executed on exit. It calls the ->shutdowwn method of all senders.
1196 void vss_shutdown(void)
1200 FOR_EACH_SENDER(i) {
1201 if (!senders[i]->shutdown)
1203 PARA_NOTICE_LOG("shutting down %s sender\n", senders[i]->name);
1204 senders[i]->shutdown();