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 monitored for writing. */
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. */
152 unsigned char **src_data;
153 /** Last time an audio header was sent. */
154 struct timeval next_header_time;
155 /** Extra slices needed to store largest chunk + header. */
156 int num_extra_slices;
157 /** Contains the FEC-encoded data. */
158 unsigned char *enc_buf;
159 /** Maximal packet size. */
164 * Get the chunk time of the current audio file.
166 * \return A pointer to a struct containing the chunk time, or NULL,
167 * if currently no audio file is selected.
169 struct timeval *vss_chunk_time(void)
171 if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
172 mmd->afd.afhi.chunk_tv.tv_usec == 0)
174 return &mmd->afd.afhi.chunk_tv;
178 * Write a fec header to a buffer.
180 * \param buf The buffer to write to.
181 * \param h The fec header to write.
183 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
185 char *buf = (char *)fc->enc_buf;
186 struct fec_group *g = &fc->group;
187 struct fec_client_parms *p = fc->fcp;
189 write_u32(buf, FEC_MAGIC);
191 write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
192 write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
193 write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
195 write_u32(buf + 10, g->num);
196 write_u32(buf + 14, g->bytes);
198 write_u8(buf + 18, fc->current_slice_num);
199 write_u8(buf + 19, 0); /* unused */
200 write_u16(buf + 20, g->slice_bytes);
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, 8);
206 static bool need_audio_header(struct fec_client *fc, struct vss_task *vsst)
208 if (!mmd->current_chunk) {
209 tv_add(now, &vsst->header_interval, &fc->next_header_time);
212 if (!vsst->header_buf)
214 if (vsst->header_len == 0)
216 if (fc->group.num > 0) {
217 if (!fc->fcp->need_periodic_header)
219 if (tv_diff(&fc->next_header_time, now, NULL) > 0)
222 tv_add(now, &vsst->header_interval, &fc->next_header_time);
226 static bool need_data_slices(struct fec_client *fc, struct vss_task *vsst)
228 if (fc->group.num > 0)
230 if (!vsst->header_buf)
232 if (vsst->header_len == 0)
234 if (fc->fcp->need_periodic_header)
239 static int fc_num_data_slices(const struct fec_client *fc)
241 return fc->fcp->data_slices_per_group + fc->num_extra_slices;
244 static int fc_num_slices(const struct fec_client *fc)
246 return fc->fcp->slices_per_group + fc->num_extra_slices;
249 static int fc_num_redundant_slices(const struct fec_client *fc)
251 return fc->fcp->slices_per_group - fc->fcp->data_slices_per_group;
254 static int num_slices(long unsigned bytes, int max_payload, int rs)
258 assert(max_payload > 0);
260 ret = DIV_ROUND_UP(bytes, max_payload);
266 /* set group start and group duration */
267 static void set_group_timing(struct fec_client *fc, struct vss_task *vsst)
269 struct fec_group *g = &fc->group;
270 struct timeval *chunk_tv = vss_chunk_time();
272 if (!need_data_slices(fc, vsst))
273 ms2tv(200, &g->duration);
275 tv_scale(g->num_chunks, chunk_tv, &g->duration);
276 tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
277 &g->duration, &g->slice_duration);
278 PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
279 tv2ms(&g->duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
282 static int initialize_fec_client(struct fec_client *fc, struct vss_task *vsst)
285 int hs, ds, rs; /* header/data/redundant slices */
286 struct fec_client_parms *fcp = fc->fcp;
291 * Set the maximum slice size to the Maximum Packet Size if the
292 * transport protocol allows determination of this value. The user
293 * can specify a slice size up to this value.
295 ret = fcp->init_fec(fc->sc);
300 fc->mps = generic_max_transport_msg_size(fc->sc->fd);
301 if (fc->mps <= FEC_HEADER_SIZE)
302 return -ERRNO_TO_PARA_ERROR(EINVAL);
304 /* free previous buffers, if any */
306 k = fc_num_data_slices(fc);
307 for (i = 0; i < k; i++)
308 free(fc->src_data[i]);
314 rs = fc_num_redundant_slices(fc);
315 ret = num_slices(vsst->header_len, fc->mps - FEC_HEADER_SIZE, rs);
319 ret = num_slices(mmd->afd.max_chunk_size, fc->mps - FEC_HEADER_SIZE, rs);
323 if (fc->fcp->need_periodic_header)
326 k = PARA_MAX(hs, ds);
327 if (k < fc->fcp->data_slices_per_group)
328 k = fc->fcp->data_slices_per_group;
329 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
330 n = fc_num_slices(fc);
331 PARA_INFO_LOG("mps: %d, k: %d, n: %d, extra slices: %d\n",
332 fc->mps, k, n, fc->num_extra_slices);
335 ret = fec_new(k, n, &fc->parms);
338 fc->src_data = arr_alloc(k, sizeof(char *));
339 for (i = 0; i < k; i++)
340 fc->src_data[i] = alloc(fc->mps);
341 fc->enc_buf = alloc(fc->mps);
343 fc->state = FEC_STATE_READY_TO_RUN;
344 fc->next_header_time.tv_sec = 0;
345 fc->stream_start = *now;
346 fc->first_stream_chunk = mmd->current_chunk;
350 static int vss_get_chunk(int chunk_num, struct vss_task *vsst,
351 char **buf, uint32_t *len)
356 * Chunk zero is special for header streams: It is the first portion of
357 * the audio file which consists of the audio file header. It may be
358 * arbitrary large due to embedded meta data. Audio format handlers may
359 * replace the header by a stripped one with meta data omitted which is
360 * of bounded size. We always use the stripped header for streaming
361 * rather than the unmodified header (chunk zero).
363 if (chunk_num == 0 && vsst->header_len > 0) {
364 assert(vsst->header_buf);
365 *buf = vsst->header_buf; /* stripped header */
366 *len = vsst->header_len;
369 ret = afh_get_chunk(chunk_num, &mmd->afd.afhi,
370 mmd->afd.audio_format_id, vsst->map, vsst->mapsize,
371 (const char **)buf, len, &vsst->afh_context);
379 static int compute_group_size(struct vss_task *vsst, struct fec_group *g,
384 int ret, i, max_chunks = PARA_MAX(1LU, 150 / tv2ms(vss_chunk_time()));
386 if (g->first_chunk == 0) {
388 ret = vss_get_chunk(0, vsst, &buf, &len);
398 * Include chunks into the group until the group duration is at least
399 * 150ms. For ogg and wma, a single chunk's duration (ogg page/wma
400 * super frame) is already larger than 150ms, so a FEC group consists
401 * of exactly one chunk for these audio formats.
404 int chunk_num = g->first_chunk + i;
406 if (g->bytes > 0 && i >= max_chunks) /* duration limit */
408 if (chunk_num >= mmd->afd.afhi.chunks_total) /* eof */
410 ret = vss_get_chunk(chunk_num, vsst, &buf, &len);
413 if (g->bytes + len > max_bytes)
415 /* Include this chunk */
419 if (g->num_chunks == 0)
421 PARA_DEBUG_LOG("group #%u: %u chunks, %u bytes total\n", g->num,
422 g->num_chunks, g->bytes);
427 * Compute the slice size of the next group.
429 * The FEC parameters n and k are fixed but the slice size varies per
430 * FEC group. We'd like to choose slices as small as possible to avoid
431 * unnecessary FEC calculations but large enough to guarantee that the
432 * k data slices suffice to encode the header (if needed) and the data
435 * Once we know the payload of the next group, we define the number s
436 * of bytes per slice for this group by
438 * s = ceil(payload / k)
440 * However, for header streams, computing s is more complicated since no
441 * overlapping of header and data slices is possible. Hence we have k >=
442 * 2 and s must satisfy
444 * (*) ceil(h / s) + ceil(d / s) <= k
446 * where h and d are payload of the header and the data chunk(s)
447 * respectively. In general there is no value for s such that (*)
448 * becomes an equality, for example if h = 4000, d = 5000 and k = 10.
450 * We use the following approach for computing a suitable value for s:
453 * k1 := ceil(k * min(h, d) / (h + d)),
456 * Note that k >= 2 implies k1 > 0 and k2 > 0, so
458 * s := max(ceil(min(h, d) / k1), ceil(max(h, d) / k2))
460 * is well-defined. Inequality (*) holds for this value of s since k1
461 * slices suffice to store min(h, d) while k2 slices suffice to store
462 * max(h, d), i.e. the first addent of (*) is bounded by k1 and the
465 * For the above example we obtain
467 * k1 = ceil(10 * 4000 / 9000) = 5, k2 = 5,
468 * s = max(4000 / 5, 5000 / 5) = 1000,
470 * which is optimal since a slice size of 999 bytes would already require
473 static int compute_slice_size(struct fec_client *fc, struct vss_task *vsst)
475 struct fec_group *g = &fc->group;
476 int k = fc_num_data_slices(fc);
477 int n = fc_num_slices(fc);
478 int ret, k1, k2, h, d, min, max, sum;
479 int max_slice_bytes = fc->mps - FEC_HEADER_SIZE;
482 if (!need_audio_header(fc, vsst)) {
483 max_group_bytes = k * max_slice_bytes;
484 g->num_header_slices = 0;
485 ret = compute_group_size(vsst, g, max_group_bytes);
488 g->slice_bytes = DIV_ROUND_UP(g->bytes, k);
489 if (g->slice_bytes == 0)
493 if (!need_data_slices(fc, vsst)) {
496 g->slice_bytes = DIV_ROUND_UP(vsst->header_len, k);
497 g->num_header_slices = k;
500 h = vsst->header_len;
501 max_group_bytes = (k - num_slices(h, max_slice_bytes, n - k))
503 ret = compute_group_size(vsst, g, max_group_bytes);
508 g->slice_bytes = DIV_ROUND_UP(h, k);
509 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
512 g->num_header_slices = ret;
515 min = PARA_MIN(h, d);
516 max = PARA_MAX(h, d);
518 k1 = DIV_ROUND_UP(k * min, sum);
523 g->slice_bytes = PARA_MAX(DIV_ROUND_UP(min, k1), DIV_ROUND_UP(max, k2));
525 * This value of s := g->slice_bytes satisfies inequality (*) above,
526 * but it might be larger than max_slice_bytes. However, we know that
527 * max_slice_bytes are sufficient to store header and data, so:
529 g->slice_bytes = PARA_MIN((int)g->slice_bytes, max_slice_bytes);
531 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
534 g->num_header_slices = ret;
538 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
541 size_t copy, src_copied, slice_copied;
542 struct fec_group *g = &fc->group;
544 if (fc->state == FEC_STATE_NONE) {
545 ret = initialize_fec_client(fc, vsst);
548 g->first_chunk = mmd->current_chunk;
553 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
556 * Start and duration of this group depend only on the previous
557 * group. Compute the new group start as g->start += g->duration.
560 tv_add(&tmp, &g->duration, &g->start);
561 set_group_timing(fc, vsst);
562 g->first_chunk += g->num_chunks;
565 compute_slice_size(fc, vsst);
566 assert(g->slice_bytes > 0);
567 fc->current_slice_num = 0;
569 set_group_timing(fc, vsst);
570 /* setup header slices */
571 for (i = 0, src_copied = 0; i < g->num_header_slices; i++) {
572 copy = PARA_MIN((size_t)g->slice_bytes, vsst->header_len - src_copied);
575 memcpy(fc->src_data[i], vsst->header_buf + src_copied, copy);
576 if (copy < g->slice_bytes)
577 memset(fc->src_data[i] + copy, 0, g->slice_bytes - copy);
581 * There might be more than one header slice to fill although only the
582 * first one will be used. Zero out any remaining header slices.
584 while (i < g->num_header_slices)
585 memset(fc->src_data[i++], 0, g->slice_bytes);
588 for (c = g->first_chunk; c < g->first_chunk + g->num_chunks; c++) {
591 ret = vss_get_chunk(c, vsst, &buf, &src_len);
597 while (src_copied < src_len) {
598 copy = PARA_MIN((size_t)g->slice_bytes - slice_copied,
599 src_len - src_copied);
600 memcpy(fc->src_data[i] + slice_copied,
601 buf + src_copied, copy);
603 slice_copied += copy;
604 if (slice_copied == g->slice_bytes) {
610 if (i < fc_num_data_slices(fc) && slice_copied < g->slice_bytes)
611 memset(fc->src_data[i] + slice_copied, 0,
612 g->slice_bytes - slice_copied);
613 /* zero out remaining slices, if any */
614 while (++i < fc_num_data_slices(fc))
615 memset(fc->src_data[i], 0, g->slice_bytes);
616 PARA_DEBUG_LOG("FEC group %u: %u chunks (%u - %u), %u bytes\n",
617 g->num, g->num_chunks, g->first_chunk,
618 g->first_chunk + g->num_chunks - 1, g->bytes
620 PARA_DEBUG_LOG("slice_bytes: %d, %d header slices, %d data slices\n",
621 g->slice_bytes, g->num_header_slices, fc_num_data_slices(fc)
626 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
628 if (fc->state == FEC_STATE_NONE || fc->current_slice_num
629 == fc->fcp->slices_per_group + fc->num_extra_slices) {
630 int ret = setup_next_fec_group(fc, vsst);
634 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
635 PARA_ERROR_LOG("FEC client temporarily disabled\n");
636 fc->state = FEC_STATE_DISABLED;
640 write_fec_header(fc, vsst);
641 fec_encode(fc->parms, (const unsigned char * const*)fc->src_data,
642 fc->enc_buf + FEC_HEADER_SIZE, fc->current_slice_num,
643 fc->group.slice_bytes);
648 * Return a buffer that marks the end of the stream.
650 * \param buf Result pointer.
651 * \return The length of the eof buffer.
653 * This is used for (multicast) udp streaming where closing the socket on the
654 * sender might not give rise to an eof condition at the peer.
656 size_t vss_get_fec_eof_packet(const char **buf)
658 static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
659 *buf = fec_eof_packet;
660 return FEC_HEADER_SIZE;
664 * Add one entry to the list of active fec clients.
666 * \param sc Generic sender_client data of the transport layer.
667 * \param fcp FEC parameters as supplied by the transport layer.
669 * \return Newly allocated fec_client struct.
671 struct fec_client *vss_add_fec_client(struct sender_client *sc,
672 struct fec_client_parms *fcp)
674 struct fec_client *fc = zalloc(sizeof(*fc));
678 para_list_add(&fc->node, &fec_client_list);
683 * Remove one entry from the list of active fec clients.
685 * \param fc The client to be removed.
687 void vss_del_fec_client(struct fec_client *fc)
694 for (i = 0; i < fc_num_data_slices(fc); i++)
695 free(fc->src_data[i]);
703 * Compute if/when next slice is due. If it isn't due yet and \a diff is
704 * not \p Null, compute the time difference next - now, where
706 * next = stream_start + (first_group_chunk - first_stream_chunk)
707 * * chunk_time + slice_num * slice_time
709 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
711 struct timeval tmp, next;
714 if (fc->state == FEC_STATE_NONE)
716 tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
717 tv_add(&tmp, &fc->group.start, &next);
718 ret = tv_diff(&next, now, diff);
719 return ret < 0? 1 : 0;
722 static void set_eof_barrier(struct vss_task *vsst)
724 struct fec_client *fc;
725 struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
729 list_for_each_entry(fc, &fec_client_list, node) {
730 struct timeval group_duration;
732 if (fc->state != FEC_STATE_READY_TO_RUN)
734 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
735 if (tv_diff(&timeout, &group_duration, NULL) < 0)
736 timeout = group_duration;
739 tv_add(now, &timeout, &vsst->eof_barrier);
743 * Check if vss status flag \a P (playing) is set.
745 * \return Greater than zero if playing, zero otherwise.
748 unsigned int vss_playing(void)
750 return mmd->new_vss_status_flags & VSS_PLAYING;
754 * Check if the \a N (next) status flag is set.
756 * \return Greater than zero if set, zero if not.
759 unsigned int vss_next(void)
761 return mmd->new_vss_status_flags & VSS_NEXT;
765 * Check if a reposition request is pending.
767 * \return Greater than zero if true, zero otherwise.
770 unsigned int vss_repos(void)
772 return mmd->new_vss_status_flags & VSS_REPOS;
776 * Check if the vss is currently paused.
778 * \return Greater than zero if paused, zero otherwise.
781 unsigned int vss_paused(void)
783 return !(mmd->new_vss_status_flags & VSS_NEXT)
784 && !(mmd->new_vss_status_flags & VSS_PLAYING);
788 * Check if the vss is currently stopped.
790 * \return Greater than zero if paused, zero otherwise.
793 unsigned int vss_stopped(void)
795 return (mmd->new_vss_status_flags & VSS_NEXT)
796 && !(mmd->new_vss_status_flags & VSS_PLAYING);
799 static int chk_barrier(const char *bname, const struct timeval *barrier,
800 struct timeval *diff, int print_log)
804 if (tv_diff(now, barrier, diff) > 0)
808 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
812 static void vss_compute_timeout(struct sched *s, struct vss_task *vsst)
815 struct fec_client *fc;
817 if (!vss_playing() || !vsst->map)
819 if (vss_next() && vsst->map) /* only sleep a bit, nec*/
820 return sched_request_timeout_ms(100, s);
822 /* Each of these barriers must have passed until we may proceed */
823 if (sched_request_barrier(&vsst->autoplay_barrier, s) == 1)
825 if (sched_request_barrier(&vsst->eof_barrier, s) == 1)
827 if (sched_request_barrier(&vsst->data_send_barrier, s) == 1)
830 * Compute the I/O timeout as the minimal time until the next
831 * chunk/slice is due for any client.
833 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
834 &mmd->stream_start, &tv);
835 if (sched_request_barrier_or_min_delay(&tv, s) == 0)
837 list_for_each_entry(fc, &fec_client_list, node) {
838 if (fc->state != FEC_STATE_READY_TO_RUN)
840 if (next_slice_is_due(fc, &tv))
841 return sched_min_delay(s);
842 sched_request_timeout(&tv, s);
846 static void vss_eof(struct vss_task *vsst)
850 if (mmd->new_vss_status_flags & VSS_NOMORE)
851 mmd->new_vss_status_flags = VSS_NEXT;
852 set_eof_barrier(vsst);
853 afh_free_header(vsst->header_buf, mmd->afd.audio_format_id);
854 vsst->header_buf = NULL;
855 para_munmap(vsst->map, vsst->mapsize);
857 mmd->chunks_sent = 0;
858 mmd->afd.afhi.seconds_total = 0;
859 mmd->afd.afhi.chunks_total = 0;
860 mmd->afd.afhi.chunk_tv.tv_sec = 0;
861 mmd->afd.afhi.chunk_tv.tv_usec = 0;
862 free(mmd->afd.afhi.chunk_table);
863 mmd->afd.afhi.chunk_table = NULL;
865 afh_close(vsst->afh_context, mmd->afd.audio_format_id);
866 vsst->afh_context = NULL;
870 static int need_to_request_new_audio_file(struct vss_task *vsst)
874 if (vsst->map) /* have audio file */
876 if (!vss_playing()) /* don't need one */
878 if (mmd->new_vss_status_flags & VSS_NOMORE)
880 if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
882 if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
888 static void set_mmd_offset(void)
890 struct timeval offset;
891 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
892 mmd->offset = tv2ms(&offset);
895 static void vss_pre_monitor(struct sched *s, void *context)
898 struct vss_task *vsst = context;
900 if (need_to_request_new_audio_file(vsst)) {
901 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
902 sched_monitor_writefd(vsst->afs_socket, s);
903 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
905 sched_monitor_readfd(vsst->afs_socket, s);
907 if (!senders[i]->pre_monitor)
909 senders[i]->pre_monitor(s);
911 vss_compute_timeout(s, vsst);
914 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
916 char control[255] __a_aligned(8), buf[8];
917 struct msghdr msg = {.msg_iov = NULL};
918 struct cmsghdr *cmsg;
924 iov.iov_len = sizeof(buf);
927 msg.msg_control = control;
928 msg.msg_controllen = sizeof(control);
929 memset(buf, 0, sizeof(buf));
930 ret = recvmsg(afs_socket, &msg, 0);
932 return -ERRNO_TO_PARA_ERROR(errno);
933 if (iov.iov_len != sizeof(buf))
934 return -E_AFS_SHORT_READ;
935 *code = *(uint32_t*)buf;
936 *data = *(uint32_t*)(buf + 4);
937 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
938 if (cmsg->cmsg_level != SOL_SOCKET
939 || cmsg->cmsg_type != SCM_RIGHTS)
941 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
943 *fd = *(int *)CMSG_DATA(cmsg);
949 /** As of 2018, neither FreeBSD-11.2 nor NetBSD-8.0 have MAP_POPULATE. */
950 #define MAP_POPULATE 0
953 static void recv_afs_result(struct vss_task *vsst, const struct sched *s)
955 int ret, passed_fd, shmid;
956 uint32_t afs_code = 0, afs_data = 0;
959 if (!sched_read_ok(vsst->afs_socket, s))
961 ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
962 if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
966 vsst->afsss = AFS_SOCKET_READY;
967 if (afs_code == NO_ADMISSIBLE_FILES) {
968 PARA_NOTICE_LOG("no admissible files\n");
973 if (afs_code != NEXT_AUDIO_FILE) {
974 PARA_ERROR_LOG("afs code: %u, expected: %d\n", afs_code,
981 ret = load_afd(shmid, &mmd->afd);
985 ret = fstat(passed_fd, &statbuf);
987 PARA_ERROR_LOG("fstat error:\n");
988 ret = -ERRNO_TO_PARA_ERROR(errno);
991 ret = para_mmap(statbuf.st_size, PROT_READ, MAP_PRIVATE | MAP_POPULATE,
992 passed_fd, &vsst->map);
995 vsst->mapsize = statbuf.st_size;
997 mmd->chunks_sent = 0;
998 mmd->current_chunk = 0;
1002 mmd->new_vss_status_flags &= (~VSS_NEXT);
1003 afh_get_header(&mmd->afd.afhi, mmd->afd.audio_format_id,
1004 vsst->map, vsst->mapsize, &vsst->header_buf, &vsst->header_len);
1007 free(mmd->afd.afhi.chunk_table);
1008 mmd->afd.afhi.chunk_table = NULL;
1012 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1013 mmd->new_vss_status_flags = VSS_NEXT;
1017 * If the next chunk needs to be sent, pass a pointer to the chunk data to all
1018 * registered fec clients and to each sender's ->send() method.
1020 static void vss_send(struct vss_task *vsst)
1023 bool fec_active = false;
1025 struct fec_client *fc, *tmp_fc;
1029 if (!vsst->map || !vss_playing())
1031 if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
1033 if (chk_barrier("data send", &vsst->data_send_barrier, &due, 1) < 0)
1035 list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
1036 if (fc->state == FEC_STATE_DISABLED)
1038 if (!next_slice_is_due(fc, NULL)) {
1042 if (compute_next_fec_slice(fc, vsst) <= 0)
1044 PARA_DEBUG_LOG("sending %u:%u (%u bytes)\n", fc->group.num,
1045 fc->current_slice_num, fc->group.slice_bytes);
1046 fc->current_slice_num++;
1047 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf,
1048 fc->group.slice_bytes + FEC_HEADER_SIZE);
1051 if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
1053 mmd->new_vss_status_flags |= VSS_NEXT;
1056 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
1057 &mmd->stream_start, &due);
1058 if (tv_diff(&due, now, NULL) > 0)
1060 if (!mmd->chunks_sent) {
1061 mmd->stream_start = *now;
1065 ret = vss_get_chunk(mmd->current_chunk, vsst, &buf, &len);
1067 PARA_ERROR_LOG("could not get chunk %lu: %s\n",
1068 mmd->current_chunk, para_strerror(-ret));
1071 * We call ->send() even if len is zero because senders might
1072 * have data queued which can be sent now.
1074 FOR_EACH_SENDER(i) {
1075 if (!senders[i]->send)
1077 senders[i]->send(mmd->current_chunk, mmd->chunks_sent,
1078 buf, len, vsst->header_buf, vsst->header_len);
1082 mmd->current_chunk++;
1085 static int vss_post_monitor(struct sched *s, void *context)
1088 struct vss_task *vsst = context;
1090 ret = task_get_notification(vsst->task);
1092 afh_free_header(vsst->header_buf, mmd->afd.audio_format_id);
1095 if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
1096 /* shut down senders and fec clients */
1097 struct fec_client *fc, *tmp;
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;
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, mmd->afd.audio_format_id);
1118 mmd->new_vss_status_flags &= ~VSS_REPOS;
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;
1126 if (senders[sender_num]->client_cmds[num]) {
1127 ret = senders[sender_num]->client_cmds[num]
1128 (&mmd->sender_cmd_data);
1130 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1132 mmd->sender_cmd_data.cmd_num = -1;
1134 if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
1135 recv_afs_result(vsst, s);
1136 else if (sched_write_ok(vsst->afs_socket, s)) {
1137 PARA_INFO_LOG("requesting new fd from afs\n");
1138 ret = write_buffer(vsst->afs_socket, "new");
1140 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
1142 vsst->afsss = AFS_SOCKET_AFD_PENDING;
1144 FOR_EACH_SENDER(i) {
1145 if (!senders[i]->post_monitor)
1147 senders[i]->post_monitor(s);
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);
1157 * Initialize the virtual streaming system task.
1159 * \param afs_socket The fd for communication with afs.
1160 * \param s The scheduler to register the vss task to.
1162 * This also initializes all supported senders and starts streaming
1163 * if the --autoplay command line flag was given.
1165 void vss_init(int afs_socket, struct sched *s)
1167 static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
1169 long unsigned announce_time = OPT_UINT32_VAL(ANNOUNCE_TIME),
1170 autoplay_delay = OPT_UINT32_VAL(AUTOPLAY_DELAY);
1171 vsst->header_interval.tv_sec = 5; /* should this be configurable? */
1172 vsst->afs_socket = afs_socket;
1173 ms2tv(announce_time, &vsst->announce_tv);
1174 PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
1175 init_list_head(&fec_client_list);
1176 FOR_EACH_SENDER(i) {
1177 PARA_NOTICE_LOG("initializing %s sender\n", senders[i]->name);
1180 mmd->sender_cmd_data.cmd_num = -1;
1181 if (OPT_GIVEN(AUTOPLAY)) {
1183 mmd->vss_status_flags |= VSS_PLAYING;
1184 mmd->new_vss_status_flags |= VSS_PLAYING;
1185 ms2tv(autoplay_delay, &tmp);
1186 tv_add(clock_get_realtime(NULL), &tmp, &vsst->autoplay_barrier);
1187 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1188 &vsst->data_send_barrier);
1190 vsst->task = task_register(&(struct task_info) {
1192 .pre_monitor = vss_pre_monitor,
1193 .post_monitor = vss_post_monitor,
1199 * Turn off the virtual streaming system.
1201 * This is only executed on exit. It calls the ->shutdown method of all senders.
1203 void vss_shutdown(void)
1206 bool is_command_handler = process_is_command_handler();
1208 FOR_EACH_SENDER(i) {
1209 if (!senders[i]->shutdown)
1211 if (!is_command_handler)
1212 PARA_NOTICE_LOG("shutting down %s sender\n",
1214 senders[i]->shutdown();