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