FEC timing improvements.
[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         k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
258         if (fc->first_stream_chunk < 0) {
259                 uint32_t largest = afh_get_largest_chunk_size(&mmd->afd.afhi)
260                         + vsst->header_len;
261                 uint8_t needed, want;
262
263                 ret = num_slices(largest, fc, &needed);
264                 if (ret < 0)
265                         return ret;
266                 if (needed > fc->fcp->data_slices_per_group)
267                         PARA_WARNING_LOG("fec parms insufficient for this audio file\n");
268                 want = PARA_MAX(needed, fc->fcp->data_slices_per_group);
269                 if (want != k) {
270                         fec_free(fc->parms);
271                         fc->src_data = para_realloc(fc->src_data, want * sizeof(char *));
272                         ret = fec_new(want, want + fc->fcp->slices_per_group
273                                 - fc->fcp->data_slices_per_group, &fc->parms);
274                         if (ret < 0)
275                                 return ret;
276                         k = want;
277                         fc->num_extra_slices = 0;
278                         if (k > fc->fcp->data_slices_per_group) {
279                                 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
280                                 PARA_NOTICE_LOG("using %d extra slices\n",
281                                         fc->num_extra_slices);
282                         }
283                 }
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                 /* use duration of the previous group for the timing of this group */
290                 set_slice_duration(fc, g);
291                 g->first_chunk += g->num_chunks;
292                 g->num++;
293         }
294         if (g->first_chunk >= mmd->afd.afhi.chunks_total)
295                 return 0;
296         if (need_audio_header(fc, vsst)) {
297                 ret = num_slices(vsst->header_len, fc, &g->num_header_slices);
298                 if (ret < 0)
299                         return ret;
300         } else
301                 g->num_header_slices = 0;
302         afh_get_chunk(g->first_chunk, &mmd->afd.afhi, vsst->map, &start_buf,
303                 &len);
304         data_slices = k - g->num_header_slices;
305         assert(data_slices);
306         max_data_size = slice_bytes * data_slices;
307         g->bytes = 0;
308         for (i = g->first_chunk; i < mmd->afd.afhi.chunks_total; i++) {
309                 afh_get_chunk(i, &mmd->afd.afhi, vsst->map, &buf, &len);
310                 if (g->bytes + len > max_data_size)
311                         break;
312                 g->bytes += len;
313         }
314         g->num_chunks = i - g->first_chunk;
315         assert(g->num_chunks);
316         fc->current_slice_num = 0;
317         if (g->num == 0)
318                 set_slice_duration(fc, g);
319
320         /* setup header slices */
321         buf = vsst->header_buf;
322         for (i = 0; i < g->num_header_slices; i++) {
323                 fc->src_data[i] = (const unsigned char *)buf;
324                 buf += slice_bytes;
325         }
326
327         /* setup data slices */
328         buf = start_buf;
329         for (i = g->num_header_slices; i < k; i++) {
330                 if (buf + slice_bytes > vsst->map + mmd->size)
331                         /*
332                          * Can not use the memory mapped audio file for this
333                          * slice as it goes beyond the map. This slice will not
334                          * be fully used.
335                          */
336                         break;
337                 fc->src_data[i] = (const unsigned char *)buf;
338                 buf += slice_bytes;
339         }
340         if (i < k) {
341                 uint32_t payload_size = vsst->map + mmd->size - buf;
342                 memcpy(fc->extra_src_buf, buf, payload_size);
343                 fc->src_data[i] = fc->extra_src_buf;
344                 i++;
345                 /* use arbitrary data for all remaining slices */
346                 buf = vsst->map;
347                 for (; i < k; i++)
348                         fc->src_data[i] = (const unsigned char *)buf;
349         }
350         PARA_DEBUG_LOG("FEC group %d: %d chunks (%d - %d), "
351                 "%d header slices, %d data slices\n",
352                 g->num, g->num_chunks, g->first_chunk,
353                 g->first_chunk + g->num_chunks - 1,
354                 g->num_header_slices, data_slices
355         );
356         /* set group start */
357         tv_scale(g->first_chunk - fc->first_stream_chunk, chunk_tv, &tmp);
358         tv_add(&fc->stream_start, &tmp, &g->start);
359         return 1;
360 }
361
362 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
363 {
364         assert(fc->error >= 0);
365         if (fc->first_stream_chunk < 0 || fc->current_slice_num
366                         == fc->fcp->slices_per_group + fc->num_extra_slices) {
367                 int ret = setup_next_fec_group(fc, vsst);
368                 if (ret == 0)
369                         return 0;
370                 if (ret < 0) {
371                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
372                         PARA_ERROR_LOG("FEC client temporarily disabled\n");
373                         fc->error = ret;
374                         return fc->error;
375                 }
376         }
377         write_fec_header(fc, vsst);
378         fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
379                 fc->current_slice_num,
380                 fc->fcp->max_slice_bytes - FEC_HEADER_SIZE);
381         return 1;
382 }
383
384 /**
385  * Return a buffer that marks the end of the stream.
386  *
387  * \param buf Result pointer.
388  * \return The length of the eof buffer.
389  *
390  * This is used for (multicast) udp streaming where closing the socket on the
391  * sender might not give rise to an eof condition at the peer.
392  */
393 size_t vss_get_fec_eof_packet(const char **buf)
394 {
395         static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
396         *buf = fec_eof_packet;
397         return FEC_HEADER_SIZE;
398 }
399
400 /**
401  * Add one entry to the list of active fec clients.
402  *
403  * \param fcp Describes the fec parameters to be used for this client.
404  * \param result An opaque pointer that must be used by remove the client later.
405  *
406  * \return Standard.
407  */
408 int vss_add_fec_client(struct fec_client_parms *fcp, struct fec_client **result)
409 {
410         int ret;
411         struct fec_client *fc;
412
413         if (fcp->max_slice_bytes < FEC_HEADER_SIZE + fcp->data_slices_per_group)
414                 return -ERRNO_TO_PARA_ERROR(EINVAL);
415         fc = para_calloc(sizeof(*fc));
416         fc->fcp = fcp;
417         ret = fec_new(fcp->data_slices_per_group, fcp->slices_per_group,
418                 &fc->parms);
419         if (ret < 0)
420                 goto err;
421         fc->first_stream_chunk = -1; /* stream not yet started */
422         fc->src_data = para_malloc(fc->fcp->slices_per_group * sizeof(char *));
423         fc->enc_buf = para_calloc(fc->fcp->max_slice_bytes);
424         fc->num_extra_slices = 0;
425         fc->extra_src_buf = para_calloc(fc->fcp->max_slice_bytes);
426         fc->next_header_time.tv_sec = 0;
427         para_list_add(&fc->node, &fec_client_list);
428         *result = fc;
429         return 1;
430 err:
431         fec_free(fc->parms);
432         free(fc);
433         *result = NULL;
434         return ret;
435 }
436
437 /**
438  * Remove one entry from the list of active fec clients.
439  *
440  * \param fc The client to be removed.
441  */
442 void vss_del_fec_client(struct fec_client *fc)
443 {
444         list_del(&fc->node);
445         free(fc->src_data);
446         free(fc->enc_buf);
447         free(fc->extra_src_buf);
448         fec_free(fc->parms);
449         free(fc);
450 }
451
452 /*
453  * Compute if/when next slice is due. If it isn't due yet and \a diff is
454  * not \p Null, compute the time difference next - now, where
455  *
456  *      next = stream_start + (first_group_chunk - first_stream_chunk)
457  *              * chunk_time + slice_num * slice_time
458  */
459 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
460 {
461         struct timeval tmp, next;
462         int ret;
463
464         if (fc->first_stream_chunk < 0)
465                 return 1;
466         tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
467         tv_add(&tmp, &fc->group.start, &next);
468         ret = tv_diff(&next, now, diff);
469         return ret < 0? 1 : 0;
470 }
471
472 static void compute_slice_timeout(struct timeval *timeout)
473 {
474         struct fec_client *fc;
475
476         assert(vss_playing());
477         list_for_each_entry(fc, &fec_client_list, node) {
478                 struct timeval diff;
479
480                 if (fc->error < 0)
481                         continue;
482                 if (next_slice_is_due(fc, &diff)) {
483                         timeout->tv_sec = 0;
484                         timeout->tv_usec = 0;
485                         return;
486                 }
487                 /* timeout = min(timeout, diff) */
488                 if (tv_diff(&diff, timeout, NULL) < 0)
489                         *timeout = diff;
490         }
491 }
492
493 static void set_eof_barrier(struct vss_task *vsst)
494 {
495         struct fec_client *fc;
496         struct timeval timeout = mmd->afd.afhi.eof_tv,
497                 *chunk_tv = vss_chunk_time();
498
499         if (!chunk_tv)
500                 goto out;
501         list_for_each_entry(fc, &fec_client_list, node) {
502                 struct timeval group_duration;
503
504                 if (fc->error < 0)
505                         continue;
506                 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
507                 if (tv_diff(&timeout, &group_duration, NULL) < 0)
508                         timeout = group_duration;
509         }
510 out:
511         tv_add(now, &timeout, &vsst->eof_barrier);
512 }
513
514 /**
515  * Check if vss status flag \a P (playing) is set.
516  *
517  * \return Greater than zero if playing, zero otherwise.
518  *
519  */
520 unsigned int vss_playing(void)
521 {
522         return mmd->new_vss_status_flags & VSS_PLAYING;
523 }
524
525 /**
526  * Check if the \a N (next) status flag is set.
527  *
528  * \return Greater than zero if set, zero if not.
529  *
530  */
531 unsigned int vss_next(void)
532 {
533         return mmd->new_vss_status_flags & VSS_NEXT;
534 }
535
536 /**
537  * Check if a reposition request is pending.
538  *
539  * \return Greater than zero if true, zero otherwise.
540  *
541  */
542 unsigned int vss_repos(void)
543 {
544         return mmd->new_vss_status_flags & VSS_REPOS;
545 }
546
547 /**
548  * Check if the vss is currently paused.
549  *
550  * \return Greater than zero if paused, zero otherwise.
551  *
552  */
553 unsigned int vss_paused(void)
554 {
555         return !(mmd->new_vss_status_flags & VSS_NEXT)
556                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
557 }
558
559 /**
560  * Check if the vss is currently stopped.
561  *
562  * \return Greater than zero if paused, zero otherwise.
563  *
564  */
565 unsigned int vss_stopped(void)
566 {
567         return (mmd->new_vss_status_flags & VSS_NEXT)
568                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
569 }
570
571 static int chk_barrier(const char *bname, const struct timeval *barrier,
572                 struct timeval *diff, int print_log)
573 {
574         long ms;
575
576         if (tv_diff(now, barrier, diff) > 0)
577                 return 1;
578         ms = tv2ms(diff);
579         if (print_log && ms)
580                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
581         return -1;
582 }
583
584 /*
585  * != NULL: timeout for next chunk
586  * NULL: nothing to do
587  */
588 static struct timeval *vss_compute_timeout(struct vss_task *vsst)
589 {
590         static struct timeval the_timeout;
591         struct timeval next_chunk;
592
593         if (vss_next() && vsst->map) {
594                 /* only sleep a bit, nec*/
595                 the_timeout.tv_sec = 0;
596                 the_timeout.tv_usec = 100;
597                 return &the_timeout;
598         }
599         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
600                         &the_timeout, 1) < 0)
601                 return &the_timeout;
602         if (chk_barrier("eof", &vsst->eof_barrier, &the_timeout, 1) < 0)
603                 return &the_timeout;
604         if (chk_barrier("data send", &vsst->data_send_barrier,
605                         &the_timeout, 1) < 0)
606                 return &the_timeout;
607         if (!vss_playing() || !vsst->map)
608                 return NULL;
609         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
610                 &mmd->stream_start, &next_chunk);
611         if (chk_barrier("chunk", &next_chunk, &the_timeout, 0) >= 0) {
612                 /* chunk is due or bof */
613                 the_timeout.tv_sec = 0;
614                 the_timeout.tv_usec = 0;
615                 return &the_timeout;
616         }
617         /* compute min of current timeout and next slice time */
618         compute_slice_timeout(&the_timeout);
619         return &the_timeout;
620 }
621
622 static void vss_eof(struct vss_task *vsst)
623 {
624
625         if (!vsst->map)
626                 return;
627         if (mmd->new_vss_status_flags & VSS_NOMORE)
628                 mmd->new_vss_status_flags = VSS_NEXT;
629         set_eof_barrier(vsst);
630         para_munmap(vsst->map, mmd->size);
631         vsst->map = NULL;
632         mmd->chunks_sent = 0;
633         mmd->offset = 0;
634         mmd->afd.afhi.seconds_total = 0;
635         mmd->afd.afhi.chunk_tv.tv_sec = 0;
636         mmd->afd.afhi.chunk_tv.tv_usec = 0;
637         free(mmd->afd.afhi.chunk_table);
638         mmd->afd.afhi.chunk_table = NULL;
639         free(mmd->afd.afhi.info_string);
640         mmd->afd.afhi.info_string = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_FILE_INFO],
641                 status_item_list[SI_TAGINFO1], status_item_list[SI_TAGINFO2]);
642         make_empty_status_items(mmd->afd.verbose_ls_output);
643         mmd->mtime = 0;
644         mmd->size = 0;
645         mmd->events++;
646 }
647
648 /**
649  * Get the list of all supported audio formats.
650  *
651  * \return Aa space separated list of all supported audio formats
652  * It is not allocated at runtime, i.e. there is no need to free
653  * the returned string in the caller.
654  */
655 const char *supported_audio_formats(void)
656 {
657         return SUPPORTED_AUDIO_FORMATS;
658 }
659
660 static int need_to_request_new_audio_file(struct vss_task *vsst)
661 {
662         struct timeval diff;
663
664         if (vsst->map) /* have audio file */
665                 return 0;
666         if (!vss_playing()) /* don't need one */
667                 return 0;
668         if (mmd->new_vss_status_flags & VSS_NOMORE)
669                 return 0;
670         if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
671                 return 0;
672         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
673                         &diff, 1) < 0)
674                 return 0;
675         return 1;
676 }
677
678 /**
679  * Compute the timeout for the main select-loop of the scheduler.
680  *
681  * \param s Pointer to the server scheduler.
682  * \param t Pointer to the vss task structure.
683  *
684  * Before the timeout is computed, the current vss status flags are evaluated
685  * and acted upon by calling appropriate functions from the lower layers.
686  * Possible actions include
687  *
688  *      - request a new audio file from afs,
689  *      - shutdown of all senders (stop/pause command),
690  *      - reposition the stream (ff/jmp command).
691  */
692 static void vss_pre_select(struct sched *s, struct task *t)
693 {
694         int i;
695         struct timeval *tv, diff;
696         struct vss_task *vsst = container_of(t, struct vss_task, task);
697
698         if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
699                 struct fec_client *fc, *tmp;
700                 for (i = 0; senders[i].name; i++)
701                         if (senders[i].shutdown_clients)
702                                 senders[i].shutdown_clients();
703                 list_for_each_entry_safe(fc, tmp, &fec_client_list, node) {
704                         fc->first_stream_chunk = -1;
705                         fc->error = 0;
706                 }
707                 mmd->stream_start.tv_sec = 0;
708                 mmd->stream_start.tv_usec = 0;
709         }
710         if (vss_next())
711                 vss_eof(vsst);
712         else if (vss_paused()) {
713                 if (mmd->chunks_sent)
714                         set_eof_barrier(vsst);
715                 mmd->chunks_sent = 0;
716         } else if (vss_repos()) {
717                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
718                 set_eof_barrier(vsst);
719                 mmd->chunks_sent = 0;
720                 mmd->current_chunk = mmd->repos_request;
721                 mmd->new_vss_status_flags &= ~VSS_REPOS;
722         }
723         if (need_to_request_new_audio_file(vsst)) {
724                 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
725                 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
726                 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
727         } else
728                 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
729         for (i = 0; senders[i].name; i++) {
730                 if (!senders[i].pre_select)
731                         continue;
732                 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
733         }
734         tv = vss_compute_timeout(vsst);
735         if (tv && tv_diff(tv, &s->timeout, &diff) < 0)
736                 s->timeout = *tv;
737 }
738
739 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
740 {
741         char control[255], buf[8];
742         struct msghdr msg = {.msg_iov = NULL};
743         struct cmsghdr *cmsg;
744         struct iovec iov;
745         int ret = 0;
746
747         *fd = -1;
748         iov.iov_base = buf;
749         iov.iov_len = sizeof(buf);
750         msg.msg_iov = &iov;
751         msg.msg_iovlen = 1;
752         msg.msg_control = control;
753         msg.msg_controllen = sizeof(control);
754         memset(buf, 0, sizeof(buf));
755         ret = recvmsg(afs_socket, &msg, 0);
756         if (ret < 0)
757                 return -ERRNO_TO_PARA_ERROR(errno);
758         if (iov.iov_len != sizeof(buf))
759                 return -E_AFS_SHORT_READ;
760         *code = *(uint32_t*)buf;
761         *data =  *(uint32_t*)(buf + 4);
762         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
763                 if (cmsg->cmsg_level != SOL_SOCKET
764                         || cmsg->cmsg_type != SCM_RIGHTS)
765                         continue;
766                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
767                         continue;
768                 *fd = *(int *)CMSG_DATA(cmsg);
769         }
770         return 1;
771 }
772
773 static void recv_afs_result(struct vss_task *vsst)
774 {
775         int ret, passed_fd, shmid;
776         uint32_t afs_code = 0, afs_data = 0;
777         struct stat statbuf;
778
779         vsst->afsss = AFS_SOCKET_READY;
780         ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
781         if (ret < 0)
782                 goto err;
783         PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
784                 afs_data);
785         ret = -E_NOFD;
786         if (afs_code != NEXT_AUDIO_FILE)
787                 goto err;
788         if (passed_fd < 0)
789                 goto err;
790         shmid = afs_data;
791         free(mmd->afd.afhi.info_string);
792         ret = load_afd(shmid, &mmd->afd);
793         if (ret < 0)
794                 goto err;
795         shm_destroy(shmid);
796         ret = fstat(passed_fd, &statbuf);
797         if (ret < 0) {
798                 PARA_ERROR_LOG("fstat error:\n");
799                 ret = -ERRNO_TO_PARA_ERROR(errno);
800                 goto err;
801         }
802         mmd->size = statbuf.st_size;
803         mmd->mtime = statbuf.st_mtime;
804         ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
805                 0, &vsst->map);
806         if (ret < 0)
807                 goto err;
808         close(passed_fd);
809         mmd->chunks_sent = 0;
810         mmd->current_chunk = 0;
811         mmd->offset = 0;
812         mmd->events++;
813         mmd->num_played++;
814         mmd->new_vss_status_flags &= (~VSS_NEXT);
815         afh_get_header(&mmd->afd.afhi, vsst->map, &vsst->header_buf,
816                 &vsst->header_len);
817         return;
818 err:
819         free(mmd->afd.afhi.chunk_table);
820         if (passed_fd >= 0)
821                 close(passed_fd);
822         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
823         mmd->new_vss_status_flags = VSS_NEXT;
824 }
825
826 /**
827  * Main sending function.
828  *
829  * This function gets called from vss_post_select(). It checks whether the next
830  * chunk of data should be pushed out. It obtains a pointer to the data to be
831  * sent out as well as its length from mmd->afd.afhi. This information is then
832  * passed to each supported sender's send() function as well as to the send()
833  * functions of each registered fec client.
834  */
835 static void vss_send(struct vss_task *vsst)
836 {
837         int i, fec_active = 0;
838         struct timeval due;
839         struct fec_client *fc, *tmp_fc;
840
841         if (!vsst->map || !vss_playing())
842                 return;
843         if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
844                 return;
845         if (chk_barrier("data send", &vsst->data_send_barrier,
846                         &due, 1) < 0)
847                 return;
848         list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
849                 if (fc->error < 0)
850                         continue;
851                 if (!next_slice_is_due(fc, NULL)) {
852                         fec_active = 1;
853                         continue;
854                 }
855                 if (compute_next_fec_slice(fc, vsst) <= 0)
856                         continue;
857                 PARA_DEBUG_LOG("sending %d:%d (%u bytes)\n", fc->group.num,
858                         fc->current_slice_num, fc->fcp->max_slice_bytes);
859                 fc->fcp->send((char *)fc->enc_buf,
860                         fc->fcp->max_slice_bytes,
861                         fc->fcp->private_data);
862                 fc->current_slice_num++;
863                 fec_active = 1;
864         }
865         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
866                 if (!fec_active)
867                         mmd->new_vss_status_flags |= VSS_NEXT;
868                 return;
869         }
870         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
871                 &mmd->stream_start, &due);
872         if (tv_diff(&due, now, NULL) <= 0) {
873                 const char *buf;
874                 size_t len;
875
876                 if (!mmd->chunks_sent) {
877                         struct timeval tmp;
878                         mmd->stream_start = *now;
879                         tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &tmp);
880                         mmd->offset = tv2ms(&tmp);
881                         mmd->events++;
882                 }
883                 /*
884                  * We call the send function also in case of empty chunks as
885                  * they might have still some data queued which can be sent in
886                  * this case.
887                  */
888                 afh_get_chunk(mmd->current_chunk, &mmd->afd.afhi, vsst->map,
889                         &buf, &len);
890                 for (i = 0; senders[i].name; i++) {
891                         if (!senders[i].send)
892                                 continue;
893                         senders[i].send(mmd->current_chunk, mmd->chunks_sent,
894                                 buf, len, vsst->header_buf, vsst->header_len);
895                 }
896                 mmd->chunks_sent++;
897                 mmd->current_chunk++;
898         }
899 }
900
901 static void vss_post_select(struct sched *s, struct task *t)
902 {
903         int ret, i;
904         struct vss_task *vsst = container_of(t, struct vss_task, task);
905
906
907         if (mmd->sender_cmd_data.cmd_num >= 0) {
908                 int num = mmd->sender_cmd_data.cmd_num,
909                         sender_num = mmd->sender_cmd_data.sender_num;
910
911                 if (senders[sender_num].client_cmds[num])
912                         senders[sender_num].client_cmds[num](&mmd->sender_cmd_data);
913                 mmd->sender_cmd_data.cmd_num = -1;
914         }
915         if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE) {
916                 if (FD_ISSET(vsst->afs_socket, &s->rfds))
917                         recv_afs_result(vsst);
918         } else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
919                 PARA_NOTICE_LOG("requesting new fd from afs\n");
920                 ret = send_buffer(vsst->afs_socket, "new");
921                 if (ret < 0)
922                         PARA_CRIT_LOG("%s\n", para_strerror(-ret));
923                 else
924                         vsst->afsss = AFS_SOCKET_AFD_PENDING;
925         }
926         for (i = 0; senders[i].name; i++) {
927                 if (!senders[i].post_select)
928                         continue;
929                 senders[i].post_select(&s->rfds, &s->wfds);
930         }
931         if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
932                         (vss_next() && vss_playing()))
933                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
934         vss_send(vsst);
935 }
936
937 /**
938  * Initialize the virtual streaming system task.
939  *
940  * \param afs_socket The fd for communication with afs.
941  *
942  * This also initializes all supported senders and starts streaming
943  * if the --autoplay command line flag was given.
944  */
945 void init_vss_task(int afs_socket)
946 {
947         static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
948         int i;
949         char *hn = para_hostname(), *home = para_homedir();
950         long unsigned announce_time = conf.announce_time_arg > 0?
951                         conf.announce_time_arg : 300,
952                 autoplay_delay = conf.autoplay_delay_arg > 0?
953                         conf.autoplay_delay_arg : 0;
954         vsst->header_interval.tv_sec = 5; /* should this be configurable? */
955         vsst->afs_socket = afs_socket;
956         vsst->task.pre_select = vss_pre_select;
957         vsst->task.post_select = vss_post_select;
958         ms2tv(announce_time, &vsst->announce_tv);
959         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
960         INIT_LIST_HEAD(&fec_client_list);
961         for (i = 0; senders[i].name; i++) {
962                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
963                 senders[i].init(&senders[i]);
964         }
965         free(hn);
966         free(home);
967         mmd->sender_cmd_data.cmd_num = -1;
968         make_empty_status_items(mmd->afd.verbose_ls_output);
969         if (conf.autoplay_given) {
970                 struct timeval tmp;
971                 mmd->vss_status_flags |= VSS_PLAYING;
972                 mmd->new_vss_status_flags |= VSS_PLAYING;
973                 ms2tv(autoplay_delay, &tmp);
974                 tv_add(now, &tmp, &vsst->autoplay_barrier);
975                 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
976                         &vsst->data_send_barrier);
977         }
978         register_task(&vsst->task);
979 }