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