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;
39 extern void dccp_send_init(struct sender *);
40 extern void http_send_init(struct sender *);
41 extern void udp_send_init(struct sender *);
43 /** The list of supported senders. */
44 struct sender senders[] = {
47 .init = http_send_init,
51 .init = dccp_send_init,
55 .init = udp_send_init,
62 /** The possible states of the afs socket. */
63 enum afs_socket_status {
64 /** Socket is inactive. */
66 /** Socket fd was included in the write fd set for select(). */
67 AFS_SOCKET_CHECK_FOR_WRITE,
68 /** vss wrote a request to the socket and waits for reply from afs. */
69 AFS_SOCKET_AFD_PENDING
72 /** The task structure for the virtual streaming system. */
74 /** Copied from the -announce_time command line option. */
75 struct timeval announce_tv;
76 /** End of the announcing interval. */
77 struct timeval data_send_barrier;
78 /** End of the EOF interval. */
79 struct timeval eof_barrier;
80 /** Only used if --autoplay_delay was given. */
81 struct timeval autoplay_barrier;
82 /** Used for afs-server communication. */
84 /** The current state of \a afs_socket. */
85 enum afs_socket_status afsss;
86 /** The memory mapped audio file. */
88 /** The size of the memory mapping. */
90 /** Used by the scheduler. */
92 /** Pointer to the header of the mapped audio file. */
94 /** Length of the audio file header. */
96 /** Time between audio file headers are sent. */
97 struct timeval header_interval;
98 /* Only used if afh supports dynamic chunks. */
103 * The list of currently connected fec clients.
105 * Senders may use \ref vss_add_fec_client() to add entries to the list.
107 static struct list_head fec_client_list;
110 * Data associated with one FEC group.
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.
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.
122 /** The number of the FEC group. */
124 /** Number of bytes in this group. */
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. */
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;
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 */
150 * Describes one connected 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. */
188 * Get the chunk time of the current audio file.
190 * \return A pointer to a struct containing the chunk time, or NULL,
191 * if currently no audio file is selected.
193 struct timeval *vss_chunk_time(void)
195 if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
196 mmd->afd.afhi.chunk_tv.tv_usec == 0)
198 return &mmd->afd.afhi.chunk_tv;
202 * Write a fec header to a buffer.
204 * \param buf The buffer to write to.
205 * \param h The fec header to write.
207 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
209 char *buf = (char *)fc->enc_buf;
210 struct fec_group *g = &fc->group;
211 struct fec_client_parms *p = fc->fcp;
213 write_u32(buf, FEC_MAGIC);
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);
219 write_u32(buf + 10, g->num);
220 write_u32(buf + 14, g->bytes);
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);
230 static bool need_audio_header(struct fec_client *fc, struct vss_task *vsst)
232 if (!mmd->current_chunk) {
233 tv_add(now, &vsst->header_interval, &fc->next_header_time);
236 if (!vsst->header_buf)
238 if (vsst->header_len == 0)
240 if (fc->group.num > 0) {
241 if (!fc->fcp->need_periodic_header)
243 if (tv_diff(&fc->next_header_time, now, NULL) > 0)
246 tv_add(now, &vsst->header_interval, &fc->next_header_time);
250 static bool need_data_slices(struct fec_client *fc, struct vss_task *vsst)
252 if (fc->group.num > 0)
254 if (!vsst->header_buf)
256 if (vsst->header_len == 0)
258 if (fc->fcp->need_periodic_header)
263 static int num_slices(long unsigned bytes, int max_payload, int rs)
267 assert(max_payload > 0);
269 ret = DIV_ROUND_UP(bytes, max_payload);
275 /* set group start and group duration */
276 static void set_group_timing(struct fec_client *fc, struct vss_task *vsst)
278 struct fec_group *g = &fc->group;
279 struct timeval *chunk_tv = vss_chunk_time();
281 if (!need_data_slices(fc, vsst))
282 ms2tv(200, &g->duration);
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));
291 static int initialize_fec_client(struct fec_client *fc, struct vss_task *vsst)
294 int hs, ds, rs; /* header/data/redundant slices */
295 struct fec_client_parms *fcp = fc->fcp;
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.
304 ret = fcp->init_fec(fc->sc);
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);
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);
318 ret = num_slices(mmd->afd.max_chunk_size, fc->mps - FEC_HEADER_SIZE, rs);
322 if (fc->fcp->need_periodic_header)
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;
331 ret = fec_new(k, n, &fc->parms);
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);
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;
348 static void vss_get_chunk(int chunk_num, struct vss_task *vsst,
349 char **buf, size_t *sz)
354 * Chunk zero is special for header streams: It is the first portion of
355 * the audio file which consists of the audio file header. It may be
356 * arbitrary large due to embedded meta data. Audio format handlers may
357 * replace the header by a stripped one with meta data omitted which is
358 * of bounded size. We always use the stripped header for streaming
359 * rather than the unmodified header (chunk zero).
361 if (chunk_num == 0 && vsst->header_len > 0) {
362 assert(vsst->header_buf);
363 *buf = vsst->header_buf; /* stripped header */
364 *sz = vsst->header_len;
367 ret = afh_get_chunk(chunk_num, &mmd->afd.afhi,
368 mmd->afd.audio_format_id, vsst->map, vsst->mapsize,
369 (const char **)buf, sz, &vsst->afh_context);
371 PARA_WARNING_LOG("could not get chunk %d: %s\n",
372 chunk_num, para_strerror(-ret));
378 static void compute_group_size(struct vss_task *vsst, struct fec_group *g,
383 int i, max_chunks = PARA_MAX(1LU, 150 / tv2ms(vss_chunk_time()));
385 if (g->first_chunk == 0) {
387 vss_get_chunk(0, vsst, &buf, &len);
395 * Include chunks into the group until the group duration is at least
396 * 150ms. For ogg and wma, a single chunk's duration (ogg page/wma
397 * super frame) is already larger than 150ms, so a FEC group consists
398 * of exactly one chunk for these audio formats.
401 int chunk_num = g->first_chunk + i;
403 if (g->bytes > 0 && i >= max_chunks) /* duration limit */
405 if (chunk_num >= mmd->afd.afhi.chunks_total) /* eof */
407 vss_get_chunk(chunk_num, vsst, &buf, &len);
408 if (g->bytes + len > max_bytes)
410 /* Include this chunk */
414 assert(g->num_chunks);
418 * Compute the slice size of the next group.
420 * The FEC parameters n and k are fixed but the slice size varies per
421 * FEC group. We'd like to choose slices as small as possible to avoid
422 * unnecessary FEC calculations but large enough to guarantee that the
423 * k data slices suffice to encode the header (if needed) and the data
426 * Once we know the payload of the next group, we define the number s
427 * of bytes per slice for this group by
429 * s = ceil(payload / k)
431 * However, for header streams, computing s is more complicated since no
432 * overlapping of header and data slices is possible. Hence we have k >=
433 * 2 and s must satisfy
435 * (*) ceil(h / s) + ceil(d / s) <= k
437 * where h and d are payload of the header and the data chunk(s)
438 * respectively. In general there is no value for s such that (*)
439 * becomes an equality, for example if h = 4000, d = 5000 and k = 10.
441 * We use the following approach for computing a suitable value for s:
444 * k1 := ceil(k * min(h, d) / (h + d)),
447 * Note that k >= 2 implies k1 > 0 and k2 > 0, so
449 * s := max(ceil(min(h, d) / k1), ceil(max(h, d) / k2))
451 * is well-defined. Inequality (*) holds for this value of s since k1
452 * slices suffice to store min(h, d) while k2 slices suffice to store
453 * max(h, d), i.e. the first addent of (*) is bounded by k1 and the
456 * For the above example we obtain
458 * k1 = ceil(10 * 4000 / 9000) = 5, k2 = 5,
459 * s = max(4000 / 5, 5000 / 5) = 1000,
461 * which is optimal since a slice size of 999 bytes would already require
464 static int compute_slice_size(struct fec_client *fc, struct vss_task *vsst)
466 struct fec_group *g = &fc->group;
467 int k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
468 int n = fc->fcp->slices_per_group + fc->num_extra_slices;
469 int ret, k1, k2, h, d, min, max, sum;
470 int max_slice_bytes = fc->mps - FEC_HEADER_SIZE;
473 if (!need_audio_header(fc, vsst)) {
474 max_group_bytes = k * max_slice_bytes;
475 g->num_header_slices = 0;
476 compute_group_size(vsst, g, max_group_bytes);
477 g->slice_bytes = DIV_ROUND_UP(g->bytes, k);
478 if (g->slice_bytes == 0)
482 if (!need_data_slices(fc, vsst)) {
485 g->slice_bytes = DIV_ROUND_UP(vsst->header_len, k);
486 g->num_header_slices = k;
489 h = vsst->header_len;
490 max_group_bytes = (k - num_slices(h, max_slice_bytes, n - k))
492 compute_group_size(vsst, g, max_group_bytes);
495 g->slice_bytes = DIV_ROUND_UP(h, k);
496 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
499 g->num_header_slices = ret;
502 min = PARA_MIN(h, d);
503 max = PARA_MAX(h, d);
505 k1 = DIV_ROUND_UP(k * min, sum);
510 g->slice_bytes = PARA_MAX(DIV_ROUND_UP(min, k1), DIV_ROUND_UP(max, k2));
512 * This value of s := g->slice_bytes satisfies inequality (*) above,
513 * but it might be larger than max_slice_bytes. However, we know that
514 * max_slice_bytes are sufficient to store header and data, so:
516 g->slice_bytes = PARA_MIN((int)g->slice_bytes, max_slice_bytes);
518 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
521 g->num_header_slices = ret;
525 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
527 int ret, i, k, n, data_slices;
530 struct fec_group *g = &fc->group;
532 if (fc->state == FEC_STATE_NONE) {
533 ret = initialize_fec_client(fc, vsst);
536 g->first_chunk = mmd->current_chunk;
541 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
544 * Start and duration of this group depend only on the previous
545 * group. Compute the new group start as g->start += g->duration.
548 tv_add(&tmp, &g->duration, &g->start);
549 set_group_timing(fc, vsst);
550 g->first_chunk += g->num_chunks;
553 k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
554 n = fc->fcp->slices_per_group + fc->num_extra_slices;
556 compute_slice_size(fc, vsst);
557 assert(g->slice_bytes > 0);
558 ret = num_slices(g->bytes, g->slice_bytes, n - k);
562 assert(g->num_header_slices + data_slices <= k);
563 fc->current_slice_num = 0;
565 set_group_timing(fc, vsst);
566 /* setup header slices */
567 buf = vsst->header_buf;
568 for (i = 0; i < g->num_header_slices; i++) {
569 uint32_t payload_size;
570 if (buf + g->slice_bytes <= vsst->header_buf + vsst->header_len) {
571 fc->src_data[i] = (const unsigned char *)buf;
572 buf += g->slice_bytes;
576 * Can not use vss->header_buf for this slice as it
577 * goes beyond the buffer. This slice will not be fully
580 payload_size = vsst->header_buf + vsst->header_len - buf;
581 memcpy(fc->extra_header_buf, buf, payload_size);
582 if (payload_size < g->slice_bytes)
583 memset(fc->extra_header_buf + payload_size, 0,
584 g->slice_bytes - payload_size);
586 * There might be more than one header slice to fill although
587 * only the first one will be used. Set all header slices to
590 while (i < g->num_header_slices)
591 fc->src_data[i++] = fc->extra_header_buf;
592 break; /* we don't want i to be increased. */
596 * Setup data slices. Note that for ogg streams chunk 0 points to a
597 * buffer on the heap rather than to the mapped audio file.
599 vss_get_chunk(g->first_chunk, vsst, &buf, &len);
600 for (p = buf; i < g->num_header_slices + data_slices; i++) {
601 if (p + g->slice_bytes > buf + g->bytes) {
603 * We must make a copy for this slice since using p
604 * directly would exceed the buffer.
606 uint32_t payload_size = buf + g->bytes - p;
607 assert(payload_size + FEC_HEADER_SIZE <= fc->mps);
608 memcpy(fc->extra_src_buf, p, payload_size);
609 if (payload_size < g->slice_bytes)
610 memset(fc->extra_src_buf + payload_size, 0,
611 g->slice_bytes - payload_size);
612 fc->src_data[i] = fc->extra_src_buf;
616 fc->src_data[i] = (const unsigned char *)p;
620 /* use arbitrary data for all remaining slices */
623 fc->src_data[i] = (const unsigned char *)buf;
625 PARA_DEBUG_LOG("FEC group %u: %u chunks (%u - %u), %u bytes\n",
626 g->num, g->num_chunks, g->first_chunk,
627 g->first_chunk + g->num_chunks - 1, g->bytes
629 PARA_DEBUG_LOG("slice_bytes: %d, %d header slices, %d data slices\n",
630 g->slice_bytes, g->num_header_slices, data_slices
635 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
637 if (fc->state == FEC_STATE_NONE || fc->current_slice_num
638 == fc->fcp->slices_per_group + fc->num_extra_slices) {
639 int ret = setup_next_fec_group(fc, vsst);
643 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
644 PARA_ERROR_LOG("FEC client temporarily disabled\n");
645 fc->state = FEC_STATE_DISABLED;
649 write_fec_header(fc, vsst);
650 fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
651 fc->current_slice_num, fc->group.slice_bytes);
656 * Return a buffer that marks the end of the stream.
658 * \param buf Result pointer.
659 * \return The length of the eof buffer.
661 * This is used for (multicast) udp streaming where closing the socket on the
662 * sender might not give rise to an eof condition at the peer.
664 size_t vss_get_fec_eof_packet(const char **buf)
666 static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
667 *buf = fec_eof_packet;
668 return FEC_HEADER_SIZE;
672 * Add one entry to the list of active fec clients.
674 * \param sc Generic sender_client data of the transport layer.
675 * \param fcp FEC parameters as supplied by the transport layer.
677 * \return Newly allocated fec_client struct.
679 struct fec_client *vss_add_fec_client(struct sender_client *sc,
680 struct fec_client_parms *fcp)
682 struct fec_client *fc = para_calloc(sizeof(*fc));
686 para_list_add(&fc->node, &fec_client_list);
691 * Remove one entry from the list of active fec clients.
693 * \param fc The client to be removed.
695 void vss_del_fec_client(struct fec_client *fc)
700 free(fc->extra_src_buf);
701 free(fc->extra_header_buf);
707 * Compute if/when next slice is due. If it isn't due yet and \a diff is
708 * not \p Null, compute the time difference next - now, where
710 * next = stream_start + (first_group_chunk - first_stream_chunk)
711 * * chunk_time + slice_num * slice_time
713 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
715 struct timeval tmp, next;
718 if (fc->state == FEC_STATE_NONE)
720 tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
721 tv_add(&tmp, &fc->group.start, &next);
722 ret = tv_diff(&next, now, diff);
723 return ret < 0? 1 : 0;
726 static void set_eof_barrier(struct vss_task *vsst)
728 struct fec_client *fc;
729 struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
733 list_for_each_entry(fc, &fec_client_list, node) {
734 struct timeval group_duration;
736 if (fc->state != FEC_STATE_READY_TO_RUN)
738 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
739 if (tv_diff(&timeout, &group_duration, NULL) < 0)
740 timeout = group_duration;
743 tv_add(now, &timeout, &vsst->eof_barrier);
747 * Check if vss status flag \a P (playing) is set.
749 * \return Greater than zero if playing, zero otherwise.
752 unsigned int vss_playing(void)
754 return mmd->new_vss_status_flags & VSS_PLAYING;
758 * Check if the \a N (next) status flag is set.
760 * \return Greater than zero if set, zero if not.
763 unsigned int vss_next(void)
765 return mmd->new_vss_status_flags & VSS_NEXT;
769 * Check if a reposition request is pending.
771 * \return Greater than zero if true, zero otherwise.
774 unsigned int vss_repos(void)
776 return mmd->new_vss_status_flags & VSS_REPOS;
780 * Check if the vss is currently paused.
782 * \return Greater than zero if paused, zero otherwise.
785 unsigned int vss_paused(void)
787 return !(mmd->new_vss_status_flags & VSS_NEXT)
788 && !(mmd->new_vss_status_flags & VSS_PLAYING);
792 * Check if the vss is currently stopped.
794 * \return Greater than zero if paused, zero otherwise.
797 unsigned int vss_stopped(void)
799 return (mmd->new_vss_status_flags & VSS_NEXT)
800 && !(mmd->new_vss_status_flags & VSS_PLAYING);
803 static int chk_barrier(const char *bname, const struct timeval *barrier,
804 struct timeval *diff, int print_log)
808 if (tv_diff(now, barrier, diff) > 0)
812 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
816 static void vss_compute_timeout(struct sched *s, struct vss_task *vsst)
819 struct fec_client *fc;
821 if (!vss_playing() || !vsst->map)
823 if (vss_next() && vsst->map) /* only sleep a bit, nec*/
824 return sched_request_timeout_ms(100, s);
826 /* Each of these barriers must have passed until we may proceed */
827 if (sched_request_barrier(&vsst->autoplay_barrier, s) == 1)
829 if (sched_request_barrier(&vsst->eof_barrier, s) == 1)
831 if (sched_request_barrier(&vsst->data_send_barrier, s) == 1)
834 * Compute the select timeout as the minimal time until the next
835 * chunk/slice is due for any client.
837 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
838 &mmd->stream_start, &tv);
839 if (sched_request_barrier_or_min_delay(&tv, s) == 0)
841 list_for_each_entry(fc, &fec_client_list, node) {
842 if (fc->state != FEC_STATE_READY_TO_RUN)
844 if (next_slice_is_due(fc, &tv))
845 return sched_min_delay(s);
846 sched_request_timeout(&tv, s);
850 static void vss_eof(struct vss_task *vsst)
855 if (mmd->new_vss_status_flags & VSS_NOMORE)
856 mmd->new_vss_status_flags = VSS_NEXT;
857 set_eof_barrier(vsst);
858 afh_free_header(vsst->header_buf, mmd->afd.audio_format_id);
859 vsst->header_buf = NULL;
860 para_munmap(vsst->map, vsst->mapsize);
862 mmd->chunks_sent = 0;
864 mmd->afd.afhi.seconds_total = 0;
865 mmd->afd.afhi.chunk_tv.tv_sec = 0;
866 mmd->afd.afhi.chunk_tv.tv_usec = 0;
867 free(mmd->afd.afhi.chunk_table);
868 mmd->afd.afhi.chunk_table = NULL;
870 afh_close(vsst->afh_context, mmd->afd.audio_format_id);
871 vsst->afh_context = NULL;
875 static int need_to_request_new_audio_file(struct vss_task *vsst)
879 if (vsst->map) /* have audio file */
881 if (!vss_playing()) /* don't need one */
883 if (mmd->new_vss_status_flags & VSS_NOMORE)
885 if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
887 if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
893 static void set_mmd_offset(void)
895 struct timeval offset;
896 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
897 mmd->offset = tv2ms(&offset);
900 static void vss_pre_select(struct sched *s, void *context)
903 struct vss_task *vsst = context;
905 if (need_to_request_new_audio_file(vsst)) {
906 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
907 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
908 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
910 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
911 for (i = 0; senders[i].name; i++) {
912 if (!senders[i].pre_select)
914 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
916 vss_compute_timeout(s, vsst);
919 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
921 char control[255] __a_aligned(8), buf[8];
922 struct msghdr msg = {.msg_iov = NULL};
923 struct cmsghdr *cmsg;
929 iov.iov_len = sizeof(buf);
932 msg.msg_control = control;
933 msg.msg_controllen = sizeof(control);
934 memset(buf, 0, sizeof(buf));
935 ret = recvmsg(afs_socket, &msg, 0);
937 return -ERRNO_TO_PARA_ERROR(errno);
938 if (iov.iov_len != sizeof(buf))
939 return -E_AFS_SHORT_READ;
940 *code = *(uint32_t*)buf;
941 *data = *(uint32_t*)(buf + 4);
942 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
943 if (cmsg->cmsg_level != SOL_SOCKET
944 || cmsg->cmsg_type != SCM_RIGHTS)
946 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
948 *fd = *(int *)CMSG_DATA(cmsg);
954 #define MAP_POPULATE 0
957 static void recv_afs_result(struct vss_task *vsst, fd_set *rfds)
959 int ret, passed_fd, shmid;
960 uint32_t afs_code = 0, afs_data = 0;
963 if (!FD_ISSET(vsst->afs_socket, rfds))
965 ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
966 if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
970 vsst->afsss = AFS_SOCKET_READY;
971 PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
974 if (afs_code != NEXT_AUDIO_FILE)
979 ret = load_afd(shmid, &mmd->afd);
983 ret = fstat(passed_fd, &statbuf);
985 PARA_ERROR_LOG("fstat error:\n");
986 ret = -ERRNO_TO_PARA_ERROR(errno);
989 ret = para_mmap(statbuf.st_size, PROT_READ, MAP_PRIVATE | MAP_POPULATE,
990 passed_fd, 0, &vsst->map);
993 vsst->mapsize = statbuf.st_size;
995 mmd->chunks_sent = 0;
996 mmd->current_chunk = 0;
1000 mmd->new_vss_status_flags &= (~VSS_NEXT);
1001 afh_get_header(&mmd->afd.afhi, mmd->afd.audio_format_id,
1002 vsst->map, vsst->mapsize, &vsst->header_buf, &vsst->header_len);
1005 free(mmd->afd.afhi.chunk_table);
1008 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1009 mmd->new_vss_status_flags = VSS_NEXT;
1013 * Main sending function.
1015 * This function gets called from vss_post_select(). It checks whether the next
1016 * chunk of data should be pushed out. It obtains a pointer to the data to be
1017 * sent out as well as its length from mmd->afd.afhi. This information is then
1018 * passed to each supported sender's send() function as well as to the send()
1019 * functions of each registered fec client.
1021 static void vss_send(struct vss_task *vsst)
1024 bool fec_active = false;
1026 struct fec_client *fc, *tmp_fc;
1028 if (!vsst->map || !vss_playing())
1030 if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
1032 if (chk_barrier("data send", &vsst->data_send_barrier, &due, 1) < 0)
1034 list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
1035 if (fc->state == FEC_STATE_DISABLED)
1037 if (!next_slice_is_due(fc, NULL)) {
1041 if (compute_next_fec_slice(fc, vsst) <= 0)
1043 PARA_DEBUG_LOG("sending %u:%u (%u bytes)\n", fc->group.num,
1044 fc->current_slice_num, fc->group.slice_bytes);
1045 fc->current_slice_num++;
1046 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf,
1047 fc->group.slice_bytes + FEC_HEADER_SIZE);
1050 if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
1052 mmd->new_vss_status_flags |= VSS_NEXT;
1055 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
1056 &mmd->stream_start, &due);
1057 if (tv_diff(&due, now, NULL) <= 0) {
1061 if (!mmd->chunks_sent) {
1062 mmd->stream_start = *now;
1066 vss_get_chunk(mmd->current_chunk, vsst, &buf, &len);
1067 for (i = 0; senders[i].name; i++) {
1069 * We call ->send() even if len is zero because senders
1070 * might have data queued which can be sent now.
1072 if (!senders[i].send)
1074 senders[i].send(mmd->current_chunk, mmd->chunks_sent,
1075 buf, len, vsst->header_buf, vsst->header_len);
1078 mmd->current_chunk++;
1082 static int vss_post_select(struct sched *s, void *context)
1085 struct vss_task *vsst = context;
1087 if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
1088 /* shut down senders and fec clients */
1089 struct fec_client *fc, *tmp;
1090 for (i = 0; senders[i].name; i++)
1091 if (senders[i].shutdown_clients)
1092 senders[i].shutdown_clients();
1093 list_for_each_entry_safe(fc, tmp, &fec_client_list, node)
1094 fc->state = FEC_STATE_NONE;
1095 mmd->stream_start.tv_sec = 0;
1096 mmd->stream_start.tv_usec = 0;
1100 else if (vss_paused()) {
1101 if (mmd->chunks_sent)
1102 set_eof_barrier(vsst);
1103 mmd->chunks_sent = 0;
1104 } else if (vss_repos()) { /* repositioning due to ff/jmp command */
1105 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1106 set_eof_barrier(vsst);
1107 mmd->chunks_sent = 0;
1108 mmd->current_chunk = afh_get_start_chunk(mmd->repos_request,
1109 &mmd->afd.afhi, mmd->afd.audio_format_id);
1110 mmd->new_vss_status_flags &= ~VSS_REPOS;
1113 /* If a sender command is pending, run it. */
1114 if (mmd->sender_cmd_data.cmd_num >= 0) {
1115 int num = mmd->sender_cmd_data.cmd_num,
1116 sender_num = mmd->sender_cmd_data.sender_num;
1118 if (senders[sender_num].client_cmds[num]) {
1119 ret = senders[sender_num].client_cmds[num]
1120 (&mmd->sender_cmd_data);
1122 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1124 mmd->sender_cmd_data.cmd_num = -1;
1126 if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
1127 recv_afs_result(vsst, &s->rfds);
1128 else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
1129 PARA_NOTICE_LOG("requesting new fd from afs\n");
1130 ret = write_buffer(vsst->afs_socket, "new");
1132 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
1134 vsst->afsss = AFS_SOCKET_AFD_PENDING;
1136 for (i = 0; senders[i].name; i++) {
1137 if (!senders[i].post_select)
1139 senders[i].post_select(&s->rfds, &s->wfds);
1141 if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
1142 (vss_next() && vss_playing()))
1143 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1149 * Initialize the virtual streaming system task.
1151 * \param afs_socket The fd for communication with afs.
1152 * \param s The scheduler to register the vss task to.
1154 * This also initializes all supported senders and starts streaming
1155 * if the --autoplay command line flag was given.
1157 void vss_init(int afs_socket, struct sched *s)
1159 static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
1161 long unsigned announce_time = OPT_UINT32_VAL(ANNOUNCE_TIME),
1162 autoplay_delay = OPT_UINT32_VAL(AUTOPLAY_DELAY);
1163 vsst->header_interval.tv_sec = 5; /* should this be configurable? */
1164 vsst->afs_socket = afs_socket;
1165 ms2tv(announce_time, &vsst->announce_tv);
1166 PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
1167 INIT_LIST_HEAD(&fec_client_list);
1168 for (i = 0; senders[i].name; i++) {
1169 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
1170 senders[i].init(&senders[i]);
1172 mmd->sender_cmd_data.cmd_num = -1;
1173 if (OPT_GIVEN(AUTOPLAY)) {
1175 mmd->vss_status_flags |= VSS_PLAYING;
1176 mmd->new_vss_status_flags |= VSS_PLAYING;
1177 ms2tv(autoplay_delay, &tmp);
1178 tv_add(clock_get_realtime(NULL), &tmp, &vsst->autoplay_barrier);
1179 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1180 &vsst->data_send_barrier);
1182 vsst->task = task_register(&(struct task_info) {
1184 .pre_select = vss_pre_select,
1185 .post_select = vss_post_select,