aft.c: Fix a possible memory leak.
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2007 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 <sys/mman.h> /* mmap */
15 #include <sys/time.h> /* gettimeofday */
16 #include <sys/types.h>
17 #include <dirent.h>
18
19 #include "para.h"
20 #include "error.h"
21 #include "string.h"
22 #include "afh.h"
23 #include "afs.h"
24 #include "server.h"
25 #include "net.h"
26 #include "server.cmdline.h"
27 #include "vss.h"
28 #include "send.h"
29 #include "ipc.h"
30 #include "fd.h"
31
32 static struct timeval announce_tv;
33 static struct timeval data_send_barrier;
34 static struct timeval eof_barrier;
35 static struct timeval autoplay_barrier;
36
37 extern struct misc_meta_data *mmd;
38 extern struct sender senders[];
39
40 static char *map;
41
42 /**
43  * Check if vss status flag \a P (playing) is set.
44  *
45  * \return Greater than zero if playing, zero otherwise.
46  *
47  */
48 unsigned int vss_playing(void)
49 {
50         return mmd->new_vss_status_flags & VSS_PLAYING;
51 }
52
53 /**
54  * Check if the \a N (next) status flag is set.
55  *
56  * \return Greater than zero if set, zero if not.
57  *
58  */
59 unsigned int vss_next(void)
60 {
61         return mmd->new_vss_status_flags & VSS_NEXT;
62 }
63
64 /**
65  * Check if a reposition request is pending.
66  *
67  * \return Greater than zero if true, zero otherwise.
68  *
69  */
70 unsigned int vss_repos(void)
71 {
72         return mmd->new_vss_status_flags & VSS_REPOS;
73 }
74
75 /**
76  * Check if the vss is currently paused.
77  *
78  * \return Greater than zero if paused, zero otherwise.
79  *
80  */
81 unsigned int vss_paused(void)
82 {
83         return !(mmd->new_vss_status_flags & VSS_NEXT)
84                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
85 }
86
87 /**
88  * Initialize the virtual streaming system.
89  *
90  * This also initializes all supported senders and starts streaming
91  * if the --autoplay command line flag was given.
92  */
93 void vss_init(void)
94 {
95         int i;
96         char *hn = para_hostname(), *home = para_homedir();
97         long unsigned announce_time = conf.announce_time_arg > 0?
98                         conf.announce_time_arg : 300,
99                 autoplay_delay = conf.autoplay_delay_arg > 0?
100                         conf.autoplay_delay_arg : 0;
101         ms2tv(announce_time, &announce_tv);
102         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&announce_tv));
103         for (i = 0; senders[i].name; i++) {
104                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
105                 senders[i].init(&senders[i]);
106         }
107         free(hn);
108         free(home);
109         if (conf.autoplay_given) {
110                 struct timeval now, tmp;
111                 mmd->vss_status_flags |= VSS_PLAYING;
112                 mmd->new_vss_status_flags |= VSS_PLAYING;
113                 gettimeofday(&now, NULL);
114                 ms2tv(autoplay_delay, &tmp);
115                 tv_add(&now, &tmp, &autoplay_barrier);
116         }
117 }
118
119 static int chk_barrier(const char *bname, const struct timeval *now,
120                 const struct timeval *barrier, struct timeval *diff,
121                 int print_log)
122 {
123         long ms;
124
125         if (tv_diff(now, barrier, diff) > 0)
126                 return 1;
127         ms = tv2ms(diff);
128         if (print_log && ms)
129                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
130         return -1;
131 }
132
133 static void vss_next_chunk_time(struct timeval *due)
134 {
135         struct timeval tmp;
136
137         tv_scale(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv, &tmp);
138         tv_add(&tmp, &mmd->stream_start, due);
139 }
140
141 /*
142  * != NULL: timeout for next chunk
143  * NULL: nothing to do
144  */
145 static struct timeval *vss_compute_timeout(void)
146 {
147         static struct timeval the_timeout;
148         struct timeval now, next_chunk;
149
150         if (vss_next() && map) {
151                 /* only sleep a bit, nec*/
152                 the_timeout.tv_sec = 0;
153                 the_timeout.tv_usec = 100;
154                 return &the_timeout;
155         }
156         gettimeofday(&now, NULL);
157         if (chk_barrier("autoplay_delay", &now, &autoplay_barrier,
158                         &the_timeout, 1) < 0)
159                 return &the_timeout;
160         if (chk_barrier("eof", &now, &eof_barrier, &the_timeout, 1) < 0)
161                 return &the_timeout;
162         if (chk_barrier("data send", &now, &data_send_barrier,
163                         &the_timeout, 1) < 0)
164                 return &the_timeout;
165         if (!vss_playing() || !map)
166                 return NULL;
167         vss_next_chunk_time(&next_chunk);
168         if (chk_barrier("chunk", &now, &next_chunk, &the_timeout, 0) < 0)
169                 return &the_timeout;
170         /* chunk is due or bof */
171         the_timeout.tv_sec = 0;
172         the_timeout.tv_usec = 0;
173         return &the_timeout;
174 }
175
176 static void vss_eof(void)
177 {
178         struct timeval now;
179         int i;
180         char *tmp;
181
182         if (!map) {
183                 for (i = 0; senders[i].name; i++)
184                         senders[i].shutdown_clients();
185                 return;
186         }
187         gettimeofday(&now, NULL);
188         tv_add(&mmd->afd.afhi.eof_tv, &now, &eof_barrier);
189         munmap(map, mmd->size);
190         map = NULL;
191         mmd->chunks_sent = 0;
192         mmd->offset = 0;
193         mmd->afd.afhi.seconds_total = 0;
194         free(mmd->afd.afhi.chunk_table);
195         mmd->afd.afhi.chunk_table = NULL;
196         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_FILE_INFO],
197                 status_item_list[SI_TAG_INFO1], status_item_list[SI_TAG_INFO2]);
198         strncpy(mmd->afd.afhi.info_string, tmp, sizeof(mmd->afd.afhi.info_string));
199         mmd->afd.afhi.info_string[sizeof(mmd->afd.afhi.info_string) - 1] = '\0';
200         free(tmp);
201         mmd->mtime = 0;
202         mmd->size = 0;
203         mmd->events++;
204 }
205
206 /**
207  * Get the header of the current audio file.
208  *
209  * \param header_len The length of the header is stored here.
210  *
211  * \return A pointer to a buffer containing the header, or NULL, if no audio
212  * file is selected or if the current audio format does not need special header
213  * treamtment.
214  *
215  */
216 char *vss_get_header(size_t *header_len)
217 {
218         if (!map || !mmd->afd.afhi.header_len)
219                 return NULL;
220         *header_len = mmd->afd.afhi.header_len;
221         return map + mmd->afd.afhi.header_offset;
222 }
223
224 /**
225  * Get the list of all supported audio formats.
226  *
227  * \return Aa space separated list of all supported audio formats
228  * It is not allocated at runtime, i.e. there is no need to free
229  * the returned string in the caller.
230  */
231 const char *supported_audio_formats(void)
232 {
233         return SUPPORTED_AUDIO_FORMATS;
234 }
235
236 /**
237  * Get the chunk time of the current audio file.
238  *
239  * \return A pointer to a struct containing the chunk time, or NULL,
240  * if currently no audio file is selected.
241  */
242 struct timeval *vss_chunk_time(void)
243 {
244         if (!map)
245                 return NULL;
246         return &mmd->afd.afhi.chunk_tv;
247 }
248
249 enum afs_socket_status {
250         AFS_SOCKET_READY,
251         AFS_SOCKET_CHECK_FOR_WRITE,
252         AFS_SOCKET_AFD_PENDING
253 };
254
255 static enum afs_socket_status afsss;
256
257 /**
258  * Compute the timeout for para_server's main select-loop.
259  *
260  * This function gets called from para_server to determine the timeout value
261  * for its main select loop.
262  *
263  * \param rfds The set of file descriptors to be checked for reading.
264  * \param wfds The set of file descriptors to be checked for writing.
265  * \param max_fileno The highest-numbered file descriptor.
266  *
267  * Before the timeout is computed, the current vss status flags are evaluated
268  * and acted upon by calling appropriate functions from the lower layers.
269  * Possible actions include
270  *
271  *      - request a new audio file from afs,
272  *      - shutdown of all senders (stop/pause command),
273  *      - reposition the stream (ff/jmp command).
274  *
275  * \return A pointer to a struct timeval containing the timeout for the next
276  * chunk of data to be sent, or NULL if we're not sending right now.
277  */
278 struct timeval *vss_preselect(fd_set *rfds, fd_set *wfds, int *max_fileno)
279 {
280         int i;
281         struct timeval *tv;
282
283         para_fd_set(afs_socket, rfds, max_fileno);
284         if (!map)
285                 for (i = 0; senders[i].name; i++)
286                         senders[i].shutdown_clients();
287         else {
288                 if (vss_next()) {
289                         vss_eof();
290                         return vss_compute_timeout();
291                 }
292         }
293         if (vss_paused() || vss_repos()) {
294                 for (i = 0; senders[i].name; i++)
295                         senders[i].shutdown_clients();
296                 if (map) {
297                         struct timeval now;
298                         gettimeofday(&now, NULL);
299                         if (!vss_paused() || mmd->chunks_sent)
300                                 tv_add(&mmd->afd.afhi.eof_tv, &now, &eof_barrier);
301                         if (vss_repos())
302                                 tv_add(&now, &announce_tv, &data_send_barrier);
303                         if (mmd->new_vss_status_flags & VSS_NOMORE)
304                                 mmd->new_vss_status_flags = VSS_NEXT;
305                 }
306                 mmd->chunks_sent = 0;
307         }
308         if (vss_repos()) {
309                 mmd->new_vss_status_flags &= ~(VSS_REPOS);
310                 mmd->current_chunk = mmd->repos_request;
311         }
312         tv = vss_compute_timeout();
313         if (tv)
314                 return tv;
315         if (!map && vss_playing() &&
316                         !(mmd->new_vss_status_flags & VSS_NOMORE)) {
317                 if (afsss == AFS_SOCKET_READY ||
318                                 afsss == AFS_SOCKET_CHECK_FOR_WRITE) {
319                         PARA_DEBUG_LOG("ready and playing, but no audio file\n");
320                         para_fd_set(afs_socket, wfds, max_fileno);
321                         afsss = AFS_SOCKET_CHECK_FOR_WRITE;
322                 }
323         }
324         return tv;
325 }
326
327 static int recv_afs_msg(int *fd, uint32_t *code, uint32_t *data)
328 {
329         char control[255], buf[8];
330         struct msghdr msg = {.msg_iov = NULL};
331         struct cmsghdr *cmsg;
332         struct iovec iov;
333         int ret = 0;
334
335         iov.iov_base = buf;
336         iov.iov_len = sizeof(buf);
337         msg.msg_iov = &iov;
338         msg.msg_iovlen = 1;
339         msg.msg_control = control;
340         msg.msg_controllen = sizeof(control);
341         memset(buf, 0, sizeof(buf));
342         ret = recvmsg(afs_socket, &msg, 0);
343         if (ret < 0)
344                 return -ERRNO_TO_PARA_ERROR(errno);
345         if (iov.iov_len != sizeof(buf))
346                 return -E_SHORT_AFS_READ;
347         *code = *(uint32_t*)buf;
348         *data =  *(uint32_t*)(buf + 4);
349         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
350                 if (cmsg->cmsg_level != SOL_SOCKET
351                         || cmsg->cmsg_type != SCM_RIGHTS)
352                 continue;
353                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
354                 continue;
355                 *fd = *(int *)CMSG_DATA(cmsg);
356         }
357         return 1;
358 }
359
360 static void recv_afs_result(void)
361 {
362         int ret, passed_fd = -1, shmid;
363         uint32_t afs_code = 0, afs_data = 0;
364         struct stat statbuf;
365         struct timeval now;
366
367         ret = recv_afs_msg(&passed_fd, &afs_code, &afs_data);
368         if (ret < 0)
369                 goto err;
370         PARA_DEBUG_LOG("got the fd: %d, code: %u, shmid: %u\n",
371                 passed_fd, afs_code, afs_data);
372         ret = -E_BAD_AFS_CODE;
373         if (afs_code != NEXT_AUDIO_FILE)
374                 goto err;
375         afsss = AFS_SOCKET_READY;
376         shmid = afs_data;
377         ret = load_afd(shmid, &mmd->afd);
378         if (ret < 0)
379                 goto err;
380         shm_destroy(shmid);
381         ret = fstat(passed_fd, &statbuf);
382         if (ret < 0) {
383                 PARA_ERROR_LOG("fstat error:\n");
384                 ret = -ERRNO_TO_PARA_ERROR(errno);
385                 goto err;
386         }
387         mmd->size = statbuf.st_size;
388         mmd->mtime = statbuf.st_mtime;
389         map = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE,
390                 passed_fd, 0);
391         close(passed_fd);
392         mmd->chunks_sent = 0;
393         mmd->current_chunk = 0;
394         mmd->offset = 0;
395         mmd->events++;
396         mmd->num_played++;
397         mmd->new_vss_status_flags &= (~VSS_NEXT);
398         gettimeofday(&now, NULL);
399         tv_add(&now, &announce_tv, &data_send_barrier);
400         return;
401 err:
402         if (passed_fd >= 0)
403                 close(passed_fd);
404         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
405 }
406
407 void vss_post_select(fd_set *rfds, fd_set *wfds)
408 {
409         int ret;
410
411         if (FD_ISSET(afs_socket, rfds))
412                 recv_afs_result();
413         if (afsss != AFS_SOCKET_CHECK_FOR_WRITE || !FD_ISSET(afs_socket, wfds))
414                 return;
415         PARA_NOTICE_LOG("requesting new fd from afs\n");
416         ret = send_buffer(afs_socket, "new");
417         afsss = AFS_SOCKET_AFD_PENDING;
418 }
419
420 static void get_chunk(long unsigned chunk_num, char **buf, size_t *len)
421 {
422         size_t pos = mmd->afd.afhi.chunk_table[chunk_num];
423         *buf = map + pos;
424         *len = mmd->afd.afhi.chunk_table[chunk_num + 1] - pos;
425 }
426
427 /**
428  * Get the data of the given chunk.
429  *
430  * \param chunk_num The number of the desired chunk.
431  * \param buf Chunk data.
432  * \param len Chunk length in bytes.
433  *
434  * \return Standard.
435  */
436 int vss_get_chunk(long unsigned chunk_num, char **buf, size_t *len)
437 {
438         if (!map || !vss_playing())
439                 return -E_CHUNK;
440         if (chunk_num >= mmd->afd.afhi.chunks_total)
441                 return -E_CHUNK;
442         get_chunk(chunk_num, buf, len);
443         return 1;
444 }
445
446 /**
447  * Main sending function.
448  *
449  * This function gets called from para_server as soon as the next chunk of data
450  * should be pushed out. It obtains a pointer to the data to be sent out as
451  * well as its length from mmd->afd.afhi. This information is then passed to
452  * each supported sender's send() function which is supposed to send out the data
453  * to all connected clients.
454  */
455 void vss_send_chunk(void)
456 {
457         int i;
458         struct timeval now, due;
459         char *buf;
460         size_t len;
461
462         if (!map || !vss_playing())
463                 return;
464         gettimeofday(&now, NULL);
465         vss_next_chunk_time(&due);
466         if (tv_diff(&due, &now, NULL) > 0)
467                 return;
468         if (chk_barrier("eof", &now, &eof_barrier, &due, 1) < 0)
469                 return;
470         if (chk_barrier("data send", &now, &data_send_barrier,
471                         &due, 1) < 0)
472                 return;
473         mmd->new_vss_status_flags &= ~VSS_REPOS;
474         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
475                 mmd->new_vss_status_flags |= VSS_NEXT;
476                 return vss_eof();
477         }
478         /*
479          * We call the send function also in case of empty chunks as they
480          * might have still some data queued which can be sent in this case.
481          */
482         if (!mmd->chunks_sent) {
483                 struct timeval tmp;
484                 gettimeofday(&mmd->stream_start, NULL);
485                 tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &tmp);
486                 mmd->offset = tv2ms(&tmp);
487                 mmd->events++;
488         }
489         get_chunk(mmd->current_chunk, &buf, &len);
490         for (i = 0; senders[i].name; i++)
491                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, len);
492         mmd->new_vss_status_flags |= VSS_PLAYING;
493         mmd->chunks_sent++;
494         mmd->current_chunk++;
495 }