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