2 * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file vss.c The virtual streaming system.
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
14 #include <sys/socket.h>
15 #include <netinet/in.h>
18 #include <sys/types.h>
19 #include <arpa/inet.h>
24 #include "server.lsg.h"
27 #include "portable_io.h"
41 extern struct misc_meta_data *mmd;
43 extern void dccp_send_init(struct sender *);
44 extern void http_send_init(struct sender *);
45 extern void udp_send_init(struct sender *);
47 /** The list of supported senders. */
48 struct sender senders[] = {
51 .init = http_send_init,
55 .init = dccp_send_init,
59 .init = udp_send_init,
66 /** The possible states of the afs socket. */
67 enum afs_socket_status {
68 /** Socket is inactive. */
70 /** Socket fd was included in the write fd set for select(). */
71 AFS_SOCKET_CHECK_FOR_WRITE,
72 /** vss wrote a request to the socket and waits for reply from afs. */
73 AFS_SOCKET_AFD_PENDING
76 /** The task structure for the virtual streaming system. */
78 /** Copied from the -announce_time command line option. */
79 struct timeval announce_tv;
80 /** End of the announcing interval. */
81 struct timeval data_send_barrier;
82 /** End of the EOF interval. */
83 struct timeval eof_barrier;
84 /** Only used if --autoplay_delay was given. */
85 struct timeval autoplay_barrier;
86 /** Used for afs-server communication. */
88 /** The current state of \a afs_socket. */
89 enum afs_socket_status afsss;
90 /** The memory mapped audio file. */
92 /** The size of the memory mapping. */
94 /** Used by the scheduler. */
96 /** Pointer to the header of the mapped audio file. */
98 /** Length of the audio file header. */
100 /** Time between audio file headers are sent. */
101 struct timeval header_interval;
102 /* Only used if afh supports dynamic chunks. */
107 * The list of currently connected fec clients.
109 * Senders may use \ref vss_add_fec_client() to add entries to the list.
111 static struct list_head fec_client_list;
114 * Data associated with one FEC group.
116 * A FEC group consists of a fixed number of slices and this number is given by
117 * the \a slices_per_group parameter of struct \ref fec_client_parms. Each FEC
118 * group contains a number of chunks of the current audio file.
120 * FEC slices directly correspond to the data packages sent by the paraslash
121 * senders that use FEC. Each slice is identified by its group number and its
122 * number within the group. All slices have the same size, but the last slice
123 * of the group may not be filled entirely.
126 /** The number of the FEC group. */
128 /** Number of bytes in this group. */
130 /** The first chunk of the current audio file belonging to the group. */
131 uint32_t first_chunk;
132 /** The number of chunks contained in this group. */
134 /** When the first chunk was sent. */
135 struct timeval start;
136 /** The duration of the full group. */
137 struct timeval duration;
138 /** The group duration divided by the number of slices. */
139 struct timeval slice_duration;
140 /** Group contains the audio file header that occupies that many slices. */
141 uint8_t num_header_slices;
142 /** Number of bytes per slice for this group. */
143 uint16_t slice_bytes;
146 /** A FEC client is always in one of these states. */
147 enum fec_client_state {
148 FEC_STATE_NONE = 0, /**< not initialized and not enabled */
149 FEC_STATE_DISABLED, /**< temporarily disabled */
150 FEC_STATE_READY_TO_RUN /**< initialized and enabled */
154 * Describes one connected FEC client.
157 /** Current state of the client */
158 enum fec_client_state state;
159 /** The connected sender client (transport layer). */
160 struct sender_client *sc;
161 /** Parameters requested by the client. */
162 struct fec_client_parms *fcp;
163 /** Used by the core FEC code. */
164 struct fec_parms *parms;
165 /** The position of this client in the fec client list. */
166 struct list_head node;
167 /** When the first slice for this client was sent. */
168 struct timeval stream_start;
169 /** The first chunk sent to this FEC client. */
170 int first_stream_chunk;
171 /** Describes the current group. */
172 struct fec_group group;
173 /** The current slice. */
174 uint8_t current_slice_num;
175 /** The data to be FEC-encoded (point to a region within the mapped audio file). */
176 const unsigned char **src_data;
177 /** Last time an audio header was sent. */
178 struct timeval next_header_time;
179 /** Used for the last source pointer of an audio file. */
180 unsigned char *extra_src_buf;
181 /** Needed for the last slice of the audio file header. */
182 unsigned char *extra_header_buf;
183 /** Extra slices needed to store largest chunk + header. */
184 int num_extra_slices;
185 /** Contains the FEC-encoded data. */
186 unsigned char *enc_buf;
187 /** Maximal packet size. */
192 * Get the chunk time of the current audio file.
194 * \return A pointer to a struct containing the chunk time, or NULL,
195 * if currently no audio file is selected.
197 struct timeval *vss_chunk_time(void)
199 if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
200 mmd->afd.afhi.chunk_tv.tv_usec == 0)
202 return &mmd->afd.afhi.chunk_tv;
206 * Write a fec header to a buffer.
208 * \param buf The buffer to write to.
209 * \param h The fec header to write.
211 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
213 char *buf = (char *)fc->enc_buf;
214 struct fec_group *g = &fc->group;
215 struct fec_client_parms *p = fc->fcp;
217 write_u32(buf, FEC_MAGIC);
219 write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
220 write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
221 write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
223 write_u32(buf + 10, g->num);
224 write_u32(buf + 14, g->bytes);
226 write_u8(buf + 18, fc->current_slice_num);
227 write_u8(buf + 19, 0); /* unused */
228 write_u16(buf + 20, g->slice_bytes);
229 write_u8(buf + 22, g->first_chunk? 0 : 1);
230 write_u8(buf + 23, vsst->header_len? 1 : 0);
231 memset(buf + 24, 0, 8);
234 static bool need_audio_header(struct fec_client *fc, struct vss_task *vsst)
236 if (!mmd->current_chunk) {
237 tv_add(now, &vsst->header_interval, &fc->next_header_time);
240 if (!vsst->header_buf)
242 if (vsst->header_len == 0)
244 if (fc->group.num > 0) {
245 if (!fc->fcp->need_periodic_header)
247 if (tv_diff(&fc->next_header_time, now, NULL) > 0)
250 tv_add(now, &vsst->header_interval, &fc->next_header_time);
254 static bool need_data_slices(struct fec_client *fc, struct vss_task *vsst)
256 if (fc->group.num > 0)
258 if (!vsst->header_buf)
260 if (vsst->header_len == 0)
262 if (fc->fcp->need_periodic_header)
267 static int num_slices(long unsigned bytes, int max_payload, int rs)
271 assert(max_payload > 0);
273 ret = DIV_ROUND_UP(bytes, max_payload);
279 /* set group start and group duration */
280 static void set_group_timing(struct fec_client *fc, struct vss_task *vsst)
282 struct fec_group *g = &fc->group;
283 struct timeval *chunk_tv = vss_chunk_time();
285 if (!need_data_slices(fc, vsst))
286 ms2tv(200, &g->duration);
288 tv_scale(g->num_chunks, chunk_tv, &g->duration);
289 tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
290 &g->duration, &g->slice_duration);
291 PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
292 tv2ms(&g->duration), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
295 static int initialize_fec_client(struct fec_client *fc, struct vss_task *vsst)
298 int hs, ds, rs; /* header/data/redundant slices */
299 struct fec_client_parms *fcp = fc->fcp;
304 * Set the maximum slice size to the Maximum Packet Size if the
305 * transport protocol allows to determine this value. The user
306 * can specify a slice size up to this value.
308 ret = fcp->init_fec(fc->sc);
313 fc->mps = generic_max_transport_msg_size(fc->sc->fd);
314 if (fc->mps <= FEC_HEADER_SIZE)
315 return -ERRNO_TO_PARA_ERROR(EINVAL);
317 rs = fc->fcp->slices_per_group - fc->fcp->data_slices_per_group;
318 ret = num_slices(vsst->header_len, fc->mps - FEC_HEADER_SIZE, rs);
322 ret = num_slices(mmd->afd.max_chunk_size, fc->mps - FEC_HEADER_SIZE, rs);
326 if (fc->fcp->need_periodic_header)
329 k = PARA_MAX(hs, ds);
330 if (k < fc->fcp->data_slices_per_group)
331 k = fc->fcp->data_slices_per_group;
332 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
335 ret = fec_new(k, n, &fc->parms);
338 PARA_INFO_LOG("mps: %d, k: %d, n: %d, extra slices: %d\n",
339 fc->mps, k, n, fc->num_extra_slices);
340 fc->src_data = para_realloc(fc->src_data, k * sizeof(char *));
341 fc->enc_buf = para_realloc(fc->enc_buf, fc->mps);
342 fc->extra_src_buf = para_realloc(fc->extra_src_buf, fc->mps);
343 fc->extra_header_buf = para_realloc(fc->extra_header_buf, fc->mps);
345 fc->state = FEC_STATE_READY_TO_RUN;
346 fc->next_header_time.tv_sec = 0;
347 fc->stream_start = *now;
348 fc->first_stream_chunk = mmd->current_chunk;
352 static void vss_get_chunk(int chunk_num, struct vss_task *vsst,
353 char **buf, size_t *sz)
358 * Chunk zero is special for header streams: It is the first portion of
359 * the audio file which consists of the audio file header. It may be
360 * arbitrary large due to embedded meta data. Audio format handlers may
361 * replace the header by a stripped one with meta data omitted which is
362 * of bounded size. We always use the stripped header for streaming
363 * rather than the unmodified header (chunk zero).
365 if (chunk_num == 0 && vsst->header_len > 0) {
366 assert(vsst->header_buf);
367 *buf = vsst->header_buf; /* stripped header */
368 *sz = vsst->header_len;
371 ret = afh_get_chunk(chunk_num, &mmd->afd.afhi,
372 mmd->afd.audio_format_id, vsst->map, vsst->mapsize,
373 (const char **)buf, sz, &vsst->afh_context);
375 PARA_WARNING_LOG("could not get chunk %d: %s\n",
376 chunk_num, para_strerror(-ret));
382 static void compute_group_size(struct vss_task *vsst, struct fec_group *g,
387 int i, max_chunks = PARA_MAX(1LU, 150 / tv2ms(vss_chunk_time()));
389 if (g->first_chunk == 0) {
391 vss_get_chunk(0, vsst, &buf, &len);
399 * Include chunks into the group until the group duration is at least
400 * 150ms. For ogg and wma, a single chunk's duration (ogg page/wma
401 * super frame) is already larger than 150ms, so a FEC group consists
402 * of exactly one chunk for these audio formats.
405 int chunk_num = g->first_chunk + i;
407 if (g->bytes > 0 && i >= max_chunks) /* duration limit */
409 if (chunk_num >= mmd->afd.afhi.chunks_total) /* eof */
411 vss_get_chunk(chunk_num, vsst, &buf, &len);
412 if (g->bytes + len > max_bytes)
414 /* Include this chunk */
418 assert(g->num_chunks);
422 * Compute the slice size of the next group.
424 * The FEC parameters n and k are fixed but the slice size varies per
425 * FEC group. We'd like to choose slices as small as possible to avoid
426 * unnecessary FEC calculations but large enough to guarantee that the
427 * k data slices suffice to encode the header (if needed) and the data
430 * Once we know the payload of the next group, we define the number s
431 * of bytes per slice for this group by
433 * s = ceil(payload / k)
435 * However, for header streams, computing s is more complicated since no
436 * overlapping of header and data slices is possible. Hence we have k >=
437 * 2 and s must satisfy
439 * (*) ceil(h / s) + ceil(d / s) <= k
441 * where h and d are payload of the header and the data chunk(s)
442 * respectively. In general there is no value for s such that (*)
443 * becomes an equality, for example if h = 4000, d = 5000 and k = 10.
445 * We use the following approach for computing a suitable value for s:
448 * k1 := ceil(k * min(h, d) / (h + d)),
451 * Note that k >= 2 implies k1 > 0 and k2 > 0, so
453 * s := max(ceil(min(h, d) / k1), ceil(max(h, d) / k2))
455 * is well-defined. Inequality (*) holds for this value of s since k1
456 * slices suffice to store min(h, d) while k2 slices suffice to store
457 * max(h, d), i.e. the first addent of (*) is bounded by k1 and the
460 * For the above example we obtain
462 * k1 = ceil(10 * 4000 / 9000) = 5, k2 = 5,
463 * s = max(4000 / 5, 5000 / 5) = 1000,
465 * which is optimal since a slice size of 999 bytes would already require
468 static int compute_slice_size(struct fec_client *fc, struct vss_task *vsst)
470 struct fec_group *g = &fc->group;
471 int k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
472 int n = fc->fcp->slices_per_group + fc->num_extra_slices;
473 int ret, k1, k2, h, d, min, max, sum;
474 int max_slice_bytes = fc->mps - FEC_HEADER_SIZE;
477 if (!need_audio_header(fc, vsst)) {
478 max_group_bytes = k * max_slice_bytes;
479 g->num_header_slices = 0;
480 compute_group_size(vsst, g, max_group_bytes);
481 g->slice_bytes = DIV_ROUND_UP(g->bytes, k);
482 if (g->slice_bytes == 0)
486 if (!need_data_slices(fc, vsst)) {
489 g->slice_bytes = DIV_ROUND_UP(vsst->header_len, k);
490 g->num_header_slices = k;
493 h = vsst->header_len;
494 max_group_bytes = (k - num_slices(h, max_slice_bytes, n - k))
496 compute_group_size(vsst, g, max_group_bytes);
499 g->slice_bytes = DIV_ROUND_UP(h, k);
500 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
503 g->num_header_slices = ret;
506 min = PARA_MIN(h, d);
507 max = PARA_MAX(h, d);
509 k1 = DIV_ROUND_UP(k * min, sum);
514 g->slice_bytes = PARA_MAX(DIV_ROUND_UP(min, k1), DIV_ROUND_UP(max, k2));
516 * This value of s := g->slice_bytes satisfies inequality (*) above,
517 * but it might be larger than max_slice_bytes. However, we know that
518 * max_slice_bytes are sufficient to store header and data, so:
520 g->slice_bytes = PARA_MIN((int)g->slice_bytes, max_slice_bytes);
522 ret = num_slices(vsst->header_len, g->slice_bytes, n - k);
525 g->num_header_slices = ret;
529 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
531 int ret, i, k, n, data_slices;
534 struct fec_group *g = &fc->group;
536 if (fc->state == FEC_STATE_NONE) {
537 ret = initialize_fec_client(fc, vsst);
540 g->first_chunk = mmd->current_chunk;
545 if (g->first_chunk + g->num_chunks >= mmd->afd.afhi.chunks_total)
548 * Start and duration of this group depend only on the previous
549 * group. Compute the new group start as g->start += g->duration.
552 tv_add(&tmp, &g->duration, &g->start);
553 set_group_timing(fc, vsst);
554 g->first_chunk += g->num_chunks;
557 k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
558 n = fc->fcp->slices_per_group + fc->num_extra_slices;
560 compute_slice_size(fc, vsst);
561 assert(g->slice_bytes > 0);
562 ret = num_slices(g->bytes, g->slice_bytes, n - k);
566 assert(g->num_header_slices + data_slices <= k);
567 fc->current_slice_num = 0;
569 set_group_timing(fc, vsst);
570 /* setup header slices */
571 buf = vsst->header_buf;
572 for (i = 0; i < g->num_header_slices; i++) {
573 uint32_t payload_size;
574 if (buf + g->slice_bytes <= vsst->header_buf + vsst->header_len) {
575 fc->src_data[i] = (const unsigned char *)buf;
576 buf += g->slice_bytes;
580 * Can not use vss->header_buf for this slice as it
581 * goes beyond the buffer. This slice will not be fully
584 payload_size = vsst->header_buf + vsst->header_len - buf;
585 memcpy(fc->extra_header_buf, buf, payload_size);
586 if (payload_size < g->slice_bytes)
587 memset(fc->extra_header_buf + payload_size, 0,
588 g->slice_bytes - payload_size);
590 * There might be more than one header slice to fill although
591 * only the first one will be used. Set all header slices to
594 while (i < g->num_header_slices)
595 fc->src_data[i++] = fc->extra_header_buf;
596 break; /* we don't want i to be increased. */
600 * Setup data slices. Note that for ogg streams chunk 0 points to a
601 * buffer on the heap rather than to the mapped audio file.
603 vss_get_chunk(g->first_chunk, vsst, &buf, &len);
604 for (p = buf; i < g->num_header_slices + data_slices; i++) {
605 if (p + g->slice_bytes > buf + g->bytes) {
607 * We must make a copy for this slice since using p
608 * directly would exceed the buffer.
610 uint32_t payload_size = buf + g->bytes - p;
611 assert(payload_size + FEC_HEADER_SIZE <= fc->mps);
612 memcpy(fc->extra_src_buf, p, payload_size);
613 if (payload_size < g->slice_bytes)
614 memset(fc->extra_src_buf + payload_size, 0,
615 g->slice_bytes - payload_size);
616 fc->src_data[i] = fc->extra_src_buf;
620 fc->src_data[i] = (const unsigned char *)p;
624 /* use arbitrary data for all remaining slices */
627 fc->src_data[i] = (const unsigned char *)buf;
629 PARA_DEBUG_LOG("FEC group %u: %u chunks (%u - %u), %u bytes\n",
630 g->num, g->num_chunks, g->first_chunk,
631 g->first_chunk + g->num_chunks - 1, g->bytes
633 PARA_DEBUG_LOG("slice_bytes: %d, %d header slices, %d data slices\n",
634 g->slice_bytes, g->num_header_slices, data_slices
639 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
641 if (fc->state == FEC_STATE_NONE || fc->current_slice_num
642 == fc->fcp->slices_per_group + fc->num_extra_slices) {
643 int ret = setup_next_fec_group(fc, vsst);
647 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
648 PARA_ERROR_LOG("FEC client temporarily disabled\n");
649 fc->state = FEC_STATE_DISABLED;
653 write_fec_header(fc, vsst);
654 fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
655 fc->current_slice_num, fc->group.slice_bytes);
660 * Return a buffer that marks the end of the stream.
662 * \param buf Result pointer.
663 * \return The length of the eof buffer.
665 * This is used for (multicast) udp streaming where closing the socket on the
666 * sender might not give rise to an eof condition at the peer.
668 size_t vss_get_fec_eof_packet(const char **buf)
670 static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
671 *buf = fec_eof_packet;
672 return FEC_HEADER_SIZE;
676 * Add one entry to the list of active fec clients.
678 * \param sc Generic sender_client data of the transport layer.
679 * \param fcp FEC parameters as supplied by the transport layer.
681 * \return Newly allocated fec_client struct.
683 struct fec_client *vss_add_fec_client(struct sender_client *sc,
684 struct fec_client_parms *fcp)
686 struct fec_client *fc = para_calloc(sizeof(*fc));
690 para_list_add(&fc->node, &fec_client_list);
695 * Remove one entry from the list of active fec clients.
697 * \param fc The client to be removed.
699 void vss_del_fec_client(struct fec_client *fc)
704 free(fc->extra_src_buf);
705 free(fc->extra_header_buf);
711 * Compute if/when next slice is due. If it isn't due yet and \a diff is
712 * not \p Null, compute the time difference next - now, where
714 * next = stream_start + (first_group_chunk - first_stream_chunk)
715 * * chunk_time + slice_num * slice_time
717 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
719 struct timeval tmp, next;
722 if (fc->state == FEC_STATE_NONE)
724 tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
725 tv_add(&tmp, &fc->group.start, &next);
726 ret = tv_diff(&next, now, diff);
727 return ret < 0? 1 : 0;
730 static void set_eof_barrier(struct vss_task *vsst)
732 struct fec_client *fc;
733 struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
737 list_for_each_entry(fc, &fec_client_list, node) {
738 struct timeval group_duration;
740 if (fc->state != FEC_STATE_READY_TO_RUN)
742 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
743 if (tv_diff(&timeout, &group_duration, NULL) < 0)
744 timeout = group_duration;
747 tv_add(now, &timeout, &vsst->eof_barrier);
751 * Check if vss status flag \a P (playing) is set.
753 * \return Greater than zero if playing, zero otherwise.
756 unsigned int vss_playing(void)
758 return mmd->new_vss_status_flags & VSS_PLAYING;
762 * Check if the \a N (next) status flag is set.
764 * \return Greater than zero if set, zero if not.
767 unsigned int vss_next(void)
769 return mmd->new_vss_status_flags & VSS_NEXT;
773 * Check if a reposition request is pending.
775 * \return Greater than zero if true, zero otherwise.
778 unsigned int vss_repos(void)
780 return mmd->new_vss_status_flags & VSS_REPOS;
784 * Check if the vss is currently paused.
786 * \return Greater than zero if paused, zero otherwise.
789 unsigned int vss_paused(void)
791 return !(mmd->new_vss_status_flags & VSS_NEXT)
792 && !(mmd->new_vss_status_flags & VSS_PLAYING);
796 * Check if the vss is currently stopped.
798 * \return Greater than zero if paused, zero otherwise.
801 unsigned int vss_stopped(void)
803 return (mmd->new_vss_status_flags & VSS_NEXT)
804 && !(mmd->new_vss_status_flags & VSS_PLAYING);
807 static int chk_barrier(const char *bname, const struct timeval *barrier,
808 struct timeval *diff, int print_log)
812 if (tv_diff(now, barrier, diff) > 0)
816 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
820 static void vss_compute_timeout(struct sched *s, struct vss_task *vsst)
823 struct fec_client *fc;
825 if (!vss_playing() || !vsst->map)
827 if (vss_next() && vsst->map) /* only sleep a bit, nec*/
828 return sched_request_timeout_ms(100, s);
830 /* Each of these barriers must have passed until we may proceed */
831 if (sched_request_barrier(&vsst->autoplay_barrier, s) == 1)
833 if (sched_request_barrier(&vsst->eof_barrier, s) == 1)
835 if (sched_request_barrier(&vsst->data_send_barrier, s) == 1)
838 * Compute the select timeout as the minimal time until the next
839 * chunk/slice is due for any client.
841 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
842 &mmd->stream_start, &tv);
843 if (sched_request_barrier_or_min_delay(&tv, s) == 0)
845 list_for_each_entry(fc, &fec_client_list, node) {
846 if (fc->state != FEC_STATE_READY_TO_RUN)
848 if (next_slice_is_due(fc, &tv))
849 return sched_min_delay(s);
850 sched_request_timeout(&tv, s);
854 static void vss_eof(struct vss_task *vsst)
859 if (mmd->new_vss_status_flags & VSS_NOMORE)
860 mmd->new_vss_status_flags = VSS_NEXT;
861 set_eof_barrier(vsst);
862 afh_free_header(vsst->header_buf, mmd->afd.audio_format_id);
863 vsst->header_buf = NULL;
864 para_munmap(vsst->map, vsst->mapsize);
866 mmd->chunks_sent = 0;
868 mmd->afd.afhi.seconds_total = 0;
869 mmd->afd.afhi.chunk_tv.tv_sec = 0;
870 mmd->afd.afhi.chunk_tv.tv_usec = 0;
871 free(mmd->afd.afhi.chunk_table);
872 mmd->afd.afhi.chunk_table = NULL;
874 afh_close(vsst->afh_context, mmd->afd.audio_format_id);
875 vsst->afh_context = NULL;
879 static int need_to_request_new_audio_file(struct vss_task *vsst)
883 if (vsst->map) /* have audio file */
885 if (!vss_playing()) /* don't need one */
887 if (mmd->new_vss_status_flags & VSS_NOMORE)
889 if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
891 if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
897 static void set_mmd_offset(void)
899 struct timeval offset;
900 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &offset);
901 mmd->offset = tv2ms(&offset);
904 static void vss_pre_select(struct sched *s, void *context)
907 struct vss_task *vsst = context;
909 if (need_to_request_new_audio_file(vsst)) {
910 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
911 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
912 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
914 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
915 for (i = 0; senders[i].name; i++) {
916 if (!senders[i].pre_select)
918 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
920 vss_compute_timeout(s, vsst);
923 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
925 char control[255] __a_aligned(8), buf[8];
926 struct msghdr msg = {.msg_iov = NULL};
927 struct cmsghdr *cmsg;
933 iov.iov_len = sizeof(buf);
936 msg.msg_control = control;
937 msg.msg_controllen = sizeof(control);
938 memset(buf, 0, sizeof(buf));
939 ret = recvmsg(afs_socket, &msg, 0);
941 return -ERRNO_TO_PARA_ERROR(errno);
942 if (iov.iov_len != sizeof(buf))
943 return -E_AFS_SHORT_READ;
944 *code = *(uint32_t*)buf;
945 *data = *(uint32_t*)(buf + 4);
946 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
947 if (cmsg->cmsg_level != SOL_SOCKET
948 || cmsg->cmsg_type != SCM_RIGHTS)
950 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
952 *fd = *(int *)CMSG_DATA(cmsg);
958 #define MAP_POPULATE 0
961 static void recv_afs_result(struct vss_task *vsst, fd_set *rfds)
963 int ret, passed_fd, shmid;
964 uint32_t afs_code = 0, afs_data = 0;
967 if (!FD_ISSET(vsst->afs_socket, rfds))
969 ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
970 if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
974 vsst->afsss = AFS_SOCKET_READY;
975 PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
978 if (afs_code != NEXT_AUDIO_FILE)
983 ret = load_afd(shmid, &mmd->afd);
987 ret = fstat(passed_fd, &statbuf);
989 PARA_ERROR_LOG("fstat error:\n");
990 ret = -ERRNO_TO_PARA_ERROR(errno);
993 ret = para_mmap(statbuf.st_size, PROT_READ, MAP_PRIVATE | MAP_POPULATE,
994 passed_fd, 0, &vsst->map);
997 vsst->mapsize = statbuf.st_size;
999 mmd->chunks_sent = 0;
1000 mmd->current_chunk = 0;
1004 mmd->new_vss_status_flags &= (~VSS_NEXT);
1005 afh_get_header(&mmd->afd.afhi, mmd->afd.audio_format_id,
1006 vsst->map, vsst->mapsize, &vsst->header_buf, &vsst->header_len);
1009 free(mmd->afd.afhi.chunk_table);
1012 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1013 mmd->new_vss_status_flags = VSS_NEXT;
1017 * Main sending function.
1019 * This function gets called from vss_post_select(). It checks whether the next
1020 * chunk of data should be pushed out. It obtains a pointer to the data to be
1021 * sent out as well as its length from mmd->afd.afhi. This information is then
1022 * passed to each supported sender's send() function as well as to the send()
1023 * functions of each registered fec client.
1025 static void vss_send(struct vss_task *vsst)
1027 int i, fec_active = 0;
1029 struct fec_client *fc, *tmp_fc;
1031 if (!vsst->map || !vss_playing())
1033 if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
1035 if (chk_barrier("data send", &vsst->data_send_barrier,
1038 list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
1039 if (fc->state == FEC_STATE_DISABLED)
1041 if (!next_slice_is_due(fc, NULL)) {
1045 if (compute_next_fec_slice(fc, vsst) <= 0)
1047 PARA_DEBUG_LOG("sending %u:%u (%u bytes)\n", fc->group.num,
1048 fc->current_slice_num, fc->group.slice_bytes);
1049 fc->fcp->send_fec(fc->sc, (char *)fc->enc_buf,
1050 fc->group.slice_bytes + FEC_HEADER_SIZE);
1051 fc->current_slice_num++;
1054 if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
1056 mmd->new_vss_status_flags |= VSS_NEXT;
1059 compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
1060 &mmd->stream_start, &due);
1061 if (tv_diff(&due, now, NULL) <= 0) {
1065 if (!mmd->chunks_sent) {
1066 mmd->stream_start = *now;
1071 * We call the send function also in case of empty chunks as
1072 * they might have still some data queued which can be sent in
1075 vss_get_chunk(mmd->current_chunk, vsst, &buf, &len);
1076 for (i = 0; senders[i].name; i++) {
1077 if (!senders[i].send)
1079 senders[i].send(mmd->current_chunk, mmd->chunks_sent,
1080 buf, len, vsst->header_buf, vsst->header_len);
1083 * Prefault next chunk(s)
1085 * If the backing device of the memory-mapped audio file is
1086 * slow and read-ahead is turned off or prevented for some
1087 * reason, e.g. due to memory pressure, it may take much longer
1088 * than the chunk interval to get the next chunk on the wire,
1089 * causing buffer underruns on the client side. Mapping the
1090 * file with MAP_POPULATE seems to help a bit, but it does not
1091 * eliminate the delays completely. Moreover, it is supported
1092 * only on Linux. So we do our own read-ahead here.
1094 if (mmd->current_chunk > 0) { /* chunk 0 might be on the heap */
1096 for (i = 0; i < 5 && buf < vsst->map + vsst->mapsize; i++) {
1097 __a_unused volatile char x = *buf;
1102 mmd->current_chunk++;
1106 static int vss_post_select(struct sched *s, void *context)
1109 struct vss_task *vsst = context;
1111 if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
1112 /* shut down senders and fec clients */
1113 struct fec_client *fc, *tmp;
1114 for (i = 0; senders[i].name; i++)
1115 if (senders[i].shutdown_clients)
1116 senders[i].shutdown_clients();
1117 list_for_each_entry_safe(fc, tmp, &fec_client_list, node)
1118 fc->state = FEC_STATE_NONE;
1119 mmd->stream_start.tv_sec = 0;
1120 mmd->stream_start.tv_usec = 0;
1124 else if (vss_paused()) {
1125 if (mmd->chunks_sent)
1126 set_eof_barrier(vsst);
1127 mmd->chunks_sent = 0;
1128 } else if (vss_repos()) { /* repositioning due to ff/jmp command */
1129 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1130 set_eof_barrier(vsst);
1131 mmd->chunks_sent = 0;
1132 mmd->current_chunk = afh_get_start_chunk(mmd->repos_request,
1133 &mmd->afd.afhi, mmd->afd.audio_format_id);
1134 mmd->new_vss_status_flags &= ~VSS_REPOS;
1137 /* If a sender command is pending, run it. */
1138 if (mmd->sender_cmd_data.cmd_num >= 0) {
1139 int num = mmd->sender_cmd_data.cmd_num,
1140 sender_num = mmd->sender_cmd_data.sender_num;
1142 if (senders[sender_num].client_cmds[num]) {
1143 ret = senders[sender_num].client_cmds[num]
1144 (&mmd->sender_cmd_data);
1146 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1148 mmd->sender_cmd_data.cmd_num = -1;
1150 if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE)
1151 recv_afs_result(vsst, &s->rfds);
1152 else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
1153 PARA_NOTICE_LOG("requesting new fd from afs\n");
1154 ret = write_buffer(vsst->afs_socket, "new");
1156 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
1158 vsst->afsss = AFS_SOCKET_AFD_PENDING;
1160 for (i = 0; senders[i].name; i++) {
1161 if (!senders[i].post_select)
1163 senders[i].post_select(&s->rfds, &s->wfds);
1165 if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
1166 (vss_next() && vss_playing()))
1167 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
1173 * Initialize the virtual streaming system task.
1175 * \param afs_socket The fd for communication with afs.
1176 * \param s The scheduler to register the vss task to.
1178 * This also initializes all supported senders and starts streaming
1179 * if the --autoplay command line flag was given.
1181 void init_vss_task(int afs_socket, struct sched *s)
1183 static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
1185 char *hn = para_hostname(), *home = para_homedir();
1186 long unsigned announce_time = OPT_UINT32_VAL(ANNOUNCE_TIME),
1187 autoplay_delay = OPT_UINT32_VAL(AUTOPLAY_DELAY);
1188 vsst->header_interval.tv_sec = 5; /* should this be configurable? */
1189 vsst->afs_socket = afs_socket;
1190 ms2tv(announce_time, &vsst->announce_tv);
1191 PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
1192 INIT_LIST_HEAD(&fec_client_list);
1193 for (i = 0; senders[i].name; i++) {
1194 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
1195 senders[i].init(&senders[i]);
1199 mmd->sender_cmd_data.cmd_num = -1;
1200 if (OPT_GIVEN(AUTOPLAY)) {
1202 mmd->vss_status_flags |= VSS_PLAYING;
1203 mmd->new_vss_status_flags |= VSS_PLAYING;
1204 ms2tv(autoplay_delay, &tmp);
1205 tv_add(clock_get_realtime(NULL), &tmp, &vsst->autoplay_barrier);
1206 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
1207 &vsst->data_send_barrier);
1209 vsst->task = task_register(&(struct task_info) {
1211 .pre_select = vss_pre_select,
1212 .post_select = vss_post_select,