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