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