Merge /home/maan/scm/paraslash_fml/paraslash
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2007 Andre Noll <maan@systemlinux.org>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 /** \file vss.c the virtual streaming system
20  *
21  * This contains the audio sending part of para_server which is independent of
22  * the current audio format, audio file selector and of the activated senders.
23  */
24
25 #include "server.h"
26 #include <sys/time.h> /* gettimeofday */
27 #include "server.cmdline.h"
28 #include "db.h"
29 #include "afh.h"
30 #include "vss.h"
31 #include "send.h"
32 #include "error.h"
33 #include "string.h"
34
35 extern const char *status_item_list[];
36
37 static struct timeval announce_tv;
38 static struct timeval data_send_barrier;
39 static struct timeval eof_barrier;
40 static struct timeval autoplay_barrier;
41
42 extern struct misc_meta_data *mmd;
43 extern struct audio_file_selector selectors[];
44 extern struct sender senders[];
45
46 static FILE *audio_file = NULL;
47
48 #if 1
49         void mp3_init(struct audio_format_handler *);
50 #endif
51
52 #ifdef HAVE_OGGVORBIS
53         void ogg_init(struct audio_format_handler *);
54 #endif
55 #ifdef HAVE_FAAD
56         void aac_afh_init(struct audio_format_handler *);
57 #endif
58
59 /**
60  * the list of supported  audio formats
61  */
62 static struct audio_format_handler afl[] = {
63 #if 1
64         {
65                 .name = "mp3",
66                 .init = mp3_init,
67         },
68 #endif
69 #ifdef HAVE_OGGVORBIS
70         {
71                 .name = "ogg",
72                 .init = ogg_init,
73         },
74 #endif
75 #ifdef HAVE_FAAD
76         {
77                 .name = "aac",
78                 .init = aac_afh_init,
79         },
80 #endif
81         {
82                 .name = NULL,
83         }
84 };
85
86 /** iterate over each supported audio format */
87 #define FOR_EACH_AUDIO_FORMAT(i) for (i = 0; afl[i].name; i++)
88
89 /**
90  * check if vss status flag \a P (playing) is set
91  *
92  * \return greater than zero if playing, zero otherwise.
93  *
94  */
95 unsigned int vss_playing(void)
96 {
97         return mmd->new_vss_status_flags & VSS_PLAYING;
98 }
99
100 /**
101  * check if \a N (next) status flag is set
102  *
103  * \return greater than zero if set, zero if not.
104  *
105  */
106 unsigned int vss_next(void)
107 {
108         return mmd->new_vss_status_flags & VSS_NEXT;
109 }
110
111 /**
112  * check if a reposition request is pending
113  *
114  * \return greater than zero if true, zero otherwise.
115  *
116  */
117 unsigned int vss_repos(void)
118 {
119         return mmd->new_vss_status_flags & VSS_REPOS;
120 }
121
122 /**
123  * check if the vss is currently paused
124  *
125  * \return greater than zero if paused, zero otherwise.
126  *
127  */
128 unsigned int vss_paused(void)
129 {
130         return !(mmd->new_vss_status_flags & VSS_NEXT)
131                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
132 }
133
134 /**
135  * get the name of the given audio format
136  * \param i the audio format number
137  *
138  * This returns a pointer to statically allocated memory so it
139  * must not be freed by the caller.
140  */
141 const char *audio_format_name(int i)
142 {
143         return i >= 0?  afl[i].name : "(none)";
144 }
145
146 /**
147  * initialize the virtual streaming system
148  *
149  * Call the init functions of all supported audio format handlers and
150  * initialize all supported senders.
151  */
152 void vss_init(void)
153 {
154         int i;
155         char *hn = para_hostname(), *home = para_homedir();
156
157         PARA_DEBUG_LOG("supported audio formats: %s\n",
158                 SUPPORTED_AUDIO_FORMATS);
159         for (i = 0; afl[i].name; i++) {
160                 PARA_NOTICE_LOG("initializing %s handler\n",
161                         afl[i].name);
162                 afl[i].init(&afl[i]);
163         }
164         ms2tv(conf.announce_time_arg, &announce_tv);
165         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&announce_tv));
166         for (i = 0; senders[i].name; i++) {
167                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
168                 senders[i].init(&senders[i]);
169         }
170         free(hn);
171         free(home);
172         if (conf.autoplay_given) {
173                 struct timeval now, tmp;
174                 mmd->vss_status_flags |= VSS_PLAYING;
175                 mmd->new_vss_status_flags |= VSS_PLAYING;
176                 gettimeofday(&now, NULL);
177                 ms2tv(conf.autoplay_delay_arg, &tmp);
178                 tv_add(&now, &tmp, &autoplay_barrier);
179         }
180 }
181
182 static int get_file_info(int i)
183 {
184         return  afl[i].get_file_info(audio_file, mmd->audio_file_info,
185                 &mmd->chunks_total, &mmd->seconds_total);
186 }
187
188 /**
189  * guess the audio format judging from filename
190  *
191  * \param name the filename
192  *
193  * \return This function returns -1 if it has no idea what kind of audio
194  * file this might be. Otherwise the (non-negative) number of the audio format
195  * is returned.
196  */
197 int guess_audio_format(const char *name)
198 {
199         int i,j, len = strlen(name);
200
201         FOR_EACH_AUDIO_FORMAT(i) {
202                 for (j = 0; afl[i].suffixes[j]; j++) {
203                         const char *p = afl[i].suffixes[j];
204                         int plen = strlen(p);
205                         if (len < plen + 1)
206                                 continue;
207                         if (name[len - plen - 1] != '.')
208                                 continue;
209                         if (strcasecmp(name + len - plen, p))
210                                 continue;
211 //                      PARA_DEBUG_LOG("might be %s\n", audio_format_name(i));
212                         return i;
213                 }
214         }
215         return -1;
216 }
217
218 static int get_audio_format(int omit)
219 {
220         int i;
221
222         FOR_EACH_AUDIO_FORMAT(i) {
223                 if (i == omit || !afl[i].get_file_info)
224                         continue;
225                 rewind(audio_file);
226                 if (get_file_info(i) > 0)
227                         return i;
228                 rewind(audio_file);
229         }
230         return -E_AUDIO_FORMAT;
231 }
232
233 /*
234  * upddate shared mem
235  */
236 static int update_mmd(void)
237 {
238         int i;
239         struct stat file_status;
240
241         i = guess_audio_format(mmd->filename);
242         if (i < 0 || get_file_info(i) < 0)
243                 i = get_audio_format(i);
244         if (i < 0)
245                 return i;
246         mmd->audio_format = i;
247         mmd->chunks_sent = 0;
248         mmd->current_chunk = 0;
249         mmd->offset = 0;
250         if (fstat(fileno(audio_file), &file_status) == -1)
251                 return -E_FSTAT;
252         mmd->size = file_status.st_size;
253         mmd->mtime = file_status.st_mtime;
254         mmd->events++;
255         PARA_NOTICE_LOG("next audio file: %s\n", mmd->filename);
256         return 1;
257 }
258
259 static void get_song(void)
260 {
261         char **sl = selectors[mmd->selector_num].get_audio_file_list(10);
262         int i;
263
264         if (!sl)
265                 goto err_out;
266         for (i = 0; sl[i]; i++) {
267                 struct timeval now;
268                 PARA_INFO_LOG("trying %s\n", sl[i]);
269                 if (strlen(sl[i]) >= _POSIX_PATH_MAX)
270                         continue;
271                 audio_file = fopen(sl[i], "r");
272                 if (!audio_file)
273                         continue;
274                 strcpy(mmd->filename, sl[i]);
275                 if (update_mmd() < 0) {
276                         fclose(audio_file);
277                         audio_file = NULL;
278                         continue;
279                 }
280                 mmd->num_played++;
281                 if (selectors[mmd->selector_num].update_audio_file)
282                         selectors[mmd->selector_num].update_audio_file(sl[i]);
283                 PARA_DEBUG_LOG("%s", "success\n");
284                 mmd->new_vss_status_flags &= (~VSS_NEXT);
285                 gettimeofday(&now, NULL);
286                 tv_add(&now, &announce_tv, &data_send_barrier);
287
288                 goto free;
289         }
290         PARA_ERROR_LOG("%s", "no valid files found\n");
291 err_out:
292         mmd->new_vss_status_flags = VSS_NEXT;
293 free:
294         if (sl) {
295                 for (i = 0; sl[i]; i++)
296                         free(sl[i]);
297                 free(sl);
298         }
299 }
300
301 static int chk_barrier(const char *bname, const struct timeval *now,
302                 const struct timeval *barrier, struct timeval *diff,
303                 int print_log)
304 {
305         long ms;
306
307         if (tv_diff(now, barrier, diff) > 0)
308                 return 1;
309         ms = tv2ms(diff);
310         if (print_log && ms)
311                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
312         return -1;
313 }
314
315 static void vss_next_chunk_time(struct timeval *due)
316 {
317         struct timeval tmp;
318
319         tv_scale(mmd->chunks_sent, &afl[mmd->audio_format].chunk_tv, &tmp);
320         tv_add(&tmp, &mmd->stream_start, due);
321 }
322
323 /*
324  * != NULL: timeout for next chunk
325  * NULL: nothing to do
326  */
327 static struct timeval *vss_compute_timeout(void)
328 {
329         static struct timeval the_timeout;
330         struct timeval now, next_chunk;
331
332         if (vss_next() && mmd->audio_format >= 0) {
333                 /* only sleep a bit, nec*/
334                 the_timeout.tv_sec = 0;
335                 the_timeout.tv_usec = 100;
336                 return &the_timeout;
337         }
338         gettimeofday(&now, NULL);
339         if (chk_barrier("autoplay_delay", &now, &autoplay_barrier,
340                         &the_timeout, 1) < 0)
341                 return &the_timeout;
342         if (chk_barrier("eof", &now, &eof_barrier, &the_timeout, 1) < 0)
343                 return &the_timeout;
344         if (chk_barrier("data send", &now, &data_send_barrier,
345                         &the_timeout, 1) < 0)
346                 return &the_timeout;
347         if (mmd->audio_format < 0 || !vss_playing() || !audio_file)
348                 return NULL;
349         vss_next_chunk_time(&next_chunk);
350         if (chk_barrier(afl[mmd->audio_format].name, &now, &next_chunk,
351                         &the_timeout, 0) < 0)
352                 return &the_timeout;
353         /* chunk is due or bof */
354         the_timeout.tv_sec = 0;
355         the_timeout.tv_usec = 0;
356         return &the_timeout;
357 }
358
359 static void vss_eof(struct audio_format_handler *af)
360 {
361         struct timeval now;
362         int i;
363         char *tmp;
364
365         if (!af || !audio_file) {
366                 for (i = 0; senders[i].name; i++)
367                         senders[i].shutdown_clients();
368                 return;
369         }
370         gettimeofday(&now, NULL);
371         tv_add(&af->eof_tv, &now, &eof_barrier);
372         af->close_audio_file();
373         audio_file = NULL;
374         mmd->audio_format = -1;
375         af = NULL;
376         mmd->chunks_sent = 0;
377         mmd->offset = 0;
378         mmd->seconds_total = 0;
379         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_INFO1],
380                 status_item_list[SI_AUDIO_INFO2], status_item_list[SI_AUDIO_INFO3]);
381         strcpy(mmd->audio_file_info, tmp);
382         free(tmp);
383         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_DBINFO1],
384                 status_item_list[SI_DBINFO2], status_item_list[SI_DBINFO3]);
385         strcpy(mmd->selector_info, tmp);
386         free(tmp);
387         mmd->filename[0] = '\0';
388         mmd->size = 0;
389         mmd->events++;
390 }
391
392 /**
393  * get the header and of the current audio file
394  *
395  * \param header_len the length of the header is stored here
396  *
397  * \return a pointer to a buffer containing the header, or NULL, if no audio
398  * file is selected or if the current audio format does not need special header
399  * treamtment.
400  *
401  */
402 char *vss_get_header(int *header_len)
403 {
404         *header_len = 0;
405         if (mmd->audio_format < 0)
406                 return NULL;
407         if (!afl[mmd->audio_format].get_header_info)
408                 return NULL;
409         return afl[mmd->audio_format].get_header_info(header_len);
410 }
411
412 /**
413  * get the list of all supported audio formats
414  *
415  * \return a space separated list of all supported audio formats
416  * It is not allocated at runtime, i.e. there is no need to free
417  * the returned string in the caller.
418  */
419 const char *supported_audio_formats(void)
420 {
421         return SUPPORTED_AUDIO_FORMATS;
422 }
423
424 /**
425  * get the chunk time of the current audio file
426  *
427  * \return a pointer to a struct containing the chunk time, or NULL,
428  * if currently no audio file is selected.
429  */
430 struct timeval *vss_chunk_time(void)
431 {
432         if (mmd->audio_format < 0)
433                 return NULL;
434         return &afl[mmd->audio_format].chunk_tv;
435 }
436
437 /**
438  * compute the timeout for para_server's main select-loop
439  *
440  * This function gets called from para_server to determine the timeout value
441  * for its main select loop.
442  *
443  * Before the timeout is computed, the current vss status flags are evaluated
444  * and acted upon by calling appropriate functions from the lower layers.
445  * Possible actions include
446  *
447  *      - request a new file list from the current audio file selector
448  *      - shutdown of all senders (stop/pause command)
449  *      - reposition the stream (ff/jmp command)
450  *
451  * \return A pointer to a struct timeval containing the timeout for the next
452  * chunk of data to be sent, or NULL if we're not sending right now.
453  */
454 struct timeval *vss_preselect(void)
455 {
456         struct audio_format_handler *af = NULL;
457         int i, format;
458         struct timeval *ret;
459 again:
460         format = mmd->audio_format;
461         if (format >= 0)
462                 af = afl + format;
463         else
464                 for (i = 0; senders[i].name; i++)
465                         senders[i].shutdown_clients();
466         if (vss_next() && af) {
467                 vss_eof(af);
468                 return vss_compute_timeout();
469         }
470         if (vss_paused() || vss_repos()) {
471                 for (i = 0; senders[i].name; i++)
472                         senders[i].shutdown_clients();
473                 if (af) {
474                         struct timeval now;
475                         gettimeofday(&now, NULL);
476                         if (!vss_paused() || mmd->chunks_sent)
477                                 tv_add(&af->eof_tv, &now, &eof_barrier);
478                         if (vss_repos())
479                                 tv_add(&now, &announce_tv, &data_send_barrier);
480                         if (mmd->new_vss_status_flags & VSS_NOMORE)
481                                 mmd->new_vss_status_flags = VSS_NEXT;
482                 }
483                 mmd->chunks_sent = 0;
484         }
485         if (af && vss_repos() && mmd->current_chunk != mmd->repos_request)
486                 af->reposition_stream(mmd->repos_request);
487         if (vss_repos()) {
488                 mmd->new_vss_status_flags &= ~(VSS_REPOS);
489                 mmd->current_chunk = mmd->repos_request;
490         }
491         ret = vss_compute_timeout();
492         if (!ret && !audio_file && vss_playing() &&
493                         !(mmd->new_vss_status_flags & VSS_NOMORE)) {
494                 PARA_DEBUG_LOG("%s", "ready and playing, but no audio file\n");
495                 get_song();
496                 goto again;
497         }
498         return ret;
499 }
500
501 /**
502  * main sending function
503  *
504  * This function gets called from para_server as soon as the next chunk of
505  * data should be pushed out. It first calls the read_chunk() function of
506  * the current audio format handler to obtain a pointer to the data to be
507  * sent out as well as its length. This information is then passed to each
508  * supported sender's send() function which does the actual sending.
509  *
510  * Return value: Positive return value on success, zero on eof and negative
511  * on errors.
512  */
513
514 void vss_send_chunk(void)
515 {
516         int i;
517         struct audio_format_handler *af;
518         char *buf;
519         ssize_t ret;
520         struct timeval now, due;
521
522         if (mmd->audio_format < 0 || !audio_file || !vss_playing())
523                 return;
524         af = &afl[mmd->audio_format];
525         gettimeofday(&now, NULL);
526         vss_next_chunk_time(&due);
527         if (tv_diff(&due, &now, NULL) > 0)
528                 return;
529         if (chk_barrier("eof", &now, &eof_barrier, &due, 1) < 0)
530                 return;
531         if (chk_barrier("data send", &now, &data_send_barrier,
532                         &due, 1) < 0)
533                 return;
534         buf = af->read_chunk(mmd->current_chunk, &ret);
535         mmd->new_vss_status_flags &= ~VSS_REPOS;
536         if (!buf) {
537                 if (ret < 0)
538                         mmd->new_vss_status_flags = VSS_NEXT;
539                 else
540                         mmd->new_vss_status_flags |= VSS_NEXT;
541                 vss_eof(af);
542                 return;
543         }
544         if (!mmd->chunks_sent) {
545                 struct timeval tmp;
546                 gettimeofday(&mmd->stream_start, NULL);
547                 tv_scale(mmd->current_chunk, &af->chunk_tv, &tmp);
548                 mmd->offset = tv2ms(&tmp);
549                 mmd->events++;
550         }
551         for (i = 0; senders[i].name; i++)
552                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, ret);
553         mmd->new_vss_status_flags |= VSS_PLAYING;
554         mmd->chunks_sent++;
555         mmd->current_chunk++;
556 }