alsa_writer: use non-blocking open mode.
[paraslash.git] / afs.c
1 /*
2  * Copyright (C) 1997-2006 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 afs.c audio file sending functions
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 "afs.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
41 extern struct misc_meta_data *mmd;
42 extern struct audio_file_selector selectors[];
43 extern struct sender senders[];
44 extern struct gengetopt_args_info conf;
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 #define FOR_EACH_AUDIO_FORMAT(i) for (i = 0; afl[i].name; i++)
86
87 /**
88  * check if audio file sender is playing
89  *
90  * \return greater than zero if playing, zero otherwise.
91  *
92  */
93 unsigned int afs_playing(void)
94 {
95         return mmd->new_afs_status_flags & AFS_PLAYING;
96 }
97
98 /**
99  * check if 'next' flag is set afs_status_flags
100  *
101  * \return greater than zero if set, zero if not.
102  *
103  */
104 unsigned int afs_next(void)
105 {
106         return mmd->new_afs_status_flags & AFS_NEXT;
107 }
108
109 /**
110  * check if a reposition request is pending
111  *
112  * \return greater than zero if true, zero otherwise.
113  *
114  */
115 unsigned int afs_repos(void)
116 {
117         return mmd->new_afs_status_flags & AFS_REPOS;
118 }
119
120 /**
121  * check if audio file sender is paused
122  *
123  * \return greater than zero if paused, zero otherwise.
124  *
125  */
126 unsigned int afs_paused(void)
127 {
128         return !(mmd->new_afs_status_flags & AFS_NEXT)
129                 && !(mmd->new_afs_status_flags & AFS_PLAYING);
130 }
131
132 /**
133  * get the name of the given audio format
134  * \param i the audio format number
135  *
136  * This returns a pointer to statically allocated memory so it
137  * must not be freed by the caller.
138  */
139 const char *audio_format_name(int i)
140 {
141         return i >= 0?  afl[i].name : "(none)";
142 }
143
144 /**
145  * initialize the audio file sender
146  *
147  * Call the init functions of all supported audio format handlers and
148  * initialize all supported senders.
149  */
150 void afs_init(void)
151 {
152         int i;
153         char *hn = para_hostname(), *home = para_homedir();
154
155         PARA_DEBUG_LOG("supported audio formats: %s\n",
156                 SUPPORTED_AUDIO_FORMATS);
157         for (i = 0; afl[i].name; i++) {
158                 PARA_NOTICE_LOG("initializing %s handler\n",
159                         afl[i].name);
160                 afl[i].init(&afl[i]);
161         }
162         ms2tv(conf.announce_time_arg, &announce_tv);
163         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&announce_tv));
164         for (i = 0; senders[i].name; i++) {
165                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
166                 senders[i].init(&senders[i]);
167         }
168         free(hn);
169         free(home);
170 }
171
172 static int get_file_info(int i)
173 {
174         return  afl[i].get_file_info(audio_file, mmd->audio_file_info,
175                 &mmd->chunks_total, &mmd->seconds_total);
176 }
177
178 /**
179  * guess the audio format judging from filename
180  *
181  * \param name the filename
182  *
183  * \return This function returns -1 if it has no idea what kind of audio
184  * file this might be. Otherwise the (non-negative) number of the audio format
185  * is returned.
186  */
187 int guess_audio_format(const char *name)
188 {
189         int i,j, len = strlen(name);
190
191         FOR_EACH_AUDIO_FORMAT(i) {
192                 for (j = 0; afl[i].suffixes[j]; j++) {
193                         const char *p = afl[i].suffixes[j];
194                         int plen = strlen(p);
195                         if (len < plen + 1)
196                                 continue;
197                         if (name[len - plen - 1] != '.')
198                                 continue;
199                         if (strcasecmp(name + len - plen, p))
200                                 continue;
201                         PARA_DEBUG_LOG("might be %s\n", audio_format_name(i));
202                         return i;
203                 }
204         }
205         return -1;
206 }
207
208 static int get_audio_format(int omit)
209 {
210         int i;
211
212         FOR_EACH_AUDIO_FORMAT(i) {
213                 if (i == omit || !afl[i].get_file_info)
214                         continue;
215                 rewind(audio_file);
216                 if (get_file_info(i) > 0)
217                         return i;
218                 rewind(audio_file);
219         }
220         return -E_AUDIO_FORMAT;
221 }
222
223 /*
224  * upddate shared mem
225  */
226 static int update_mmd(void)
227 {
228         int i;
229         struct stat file_status;
230
231         i = guess_audio_format(mmd->filename);
232         if (i < 0 || get_file_info(i) < 0)
233                 i = get_audio_format(i);
234         if (i < 0)
235                 return i;
236         mmd->audio_format = i;
237         mmd->chunks_sent = 0;
238         mmd->current_chunk = 0;
239         mmd->offset = 0;
240         if (fstat(fileno(audio_file), &file_status) == -1)
241                 return -E_FSTAT;
242         mmd->size = file_status.st_size;
243         mmd->mtime = file_status.st_mtime;
244         mmd->events++;
245         PARA_NOTICE_LOG("next audio file: %s\n", mmd->filename);
246         return 1;
247 }
248
249 static void get_song(void)
250 {
251         char **sl = selectors[mmd->selector_num].get_audio_file_list(10);
252         int i;
253
254         if (!sl)
255                 goto err_out;
256         for (i = 0; sl[i]; i++) {
257                 struct timeval now;
258                 PARA_INFO_LOG("trying %s\n", sl[i]);
259                 if (strlen(sl[i]) >= _POSIX_PATH_MAX)
260                         continue;
261                 audio_file = fopen(sl[i], "r");
262                 if (!audio_file)
263                         continue;
264                 strcpy(mmd->filename, sl[i]);
265                 if (update_mmd() < 0) {
266                         fclose(audio_file);
267                         audio_file = NULL;
268                         continue;
269                 }
270                 mmd->num_played++;
271                 if (selectors[mmd->selector_num].update_audio_file)
272                         selectors[mmd->selector_num].update_audio_file(sl[i]);
273                 PARA_DEBUG_LOG("%s", "success\n");
274                 mmd->new_afs_status_flags &= (~AFS_NEXT);
275                 gettimeofday(&now, NULL);
276                 tv_add(&now, &announce_tv, &data_send_barrier);
277
278                 goto free;
279         }
280         PARA_ERROR_LOG("%s", "no valid files found\n");
281 err_out:
282         mmd->new_afs_status_flags = AFS_NEXT;
283 free:
284         if (sl) {
285                 for (i = 0; sl[i]; i++)
286                         free(sl[i]);
287                 free(sl);
288         }
289 }
290
291 static int chk_barrier(const char *bname, const struct timeval *now,
292                 const struct timeval *barrier, struct timeval *diff, int log)
293 {
294         long ms;
295
296         if (tv_diff(now, barrier, diff) > 0)
297                 return 1;
298         ms = tv2ms(diff);
299         if (log && ms)
300                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
301         return -1;
302 }
303
304 static void afs_next_chunk_time(struct timeval *due)
305 {
306         struct timeval tmp;
307
308         tv_scale(mmd->chunks_sent, &afl[mmd->audio_format].chunk_tv, &tmp);
309         tv_add(&tmp, &mmd->stream_start, due);
310 }
311
312 /*
313  * != NULL: timeout for next chunk
314  * NULL: nothing to do
315  */
316 static struct timeval *afs_compute_timeout(void)
317 {
318         static struct timeval the_timeout;
319         struct timeval now, next_chunk;
320
321         if (afs_next() && mmd->audio_format >= 0) {
322                 /* only sleep a bit, nec*/
323                 the_timeout.tv_sec = 0;
324                 the_timeout.tv_usec = 100;
325                 return &the_timeout;
326         }
327         gettimeofday(&now, NULL);
328         if (chk_barrier("eof", &now, &eof_barrier, &the_timeout, 1) < 0)
329                 return &the_timeout;
330         if (chk_barrier("data send", &now, &data_send_barrier,
331                         &the_timeout, 1) < 0)
332                 return &the_timeout;
333         if (mmd->audio_format < 0 || !afs_playing() || !audio_file)
334                 return NULL;
335         afs_next_chunk_time(&next_chunk);
336         if (chk_barrier(afl[mmd->audio_format].name, &now, &next_chunk,
337                         &the_timeout, 0) < 0)
338                 return &the_timeout;
339         /* chunk is due or bof */
340         the_timeout.tv_sec = 0;
341         the_timeout.tv_usec = 0;
342         return &the_timeout;
343 }
344
345 static void afs_eof(struct audio_format_handler *af)
346 {
347         struct timeval now;
348         int i;
349         char *tmp;
350
351         if (!af || !audio_file) {
352                 for (i = 0; senders[i].name; i++)
353                         senders[i].shutdown_clients();
354                 return;
355         }
356         gettimeofday(&now, NULL);
357         tv_add(&af->eof_tv, &now, &eof_barrier);
358         af->close_audio_file();
359         audio_file = NULL;
360         mmd->audio_format = -1;
361         af = NULL;
362         mmd->chunks_sent = 0;
363         mmd->offset = 0;
364         mmd->seconds_total = 0;
365         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_AUDIO_INFO1],
366                 status_item_list[SI_AUDIO_INFO2], status_item_list[SI_AUDIO_INFO3]);
367         strcpy(mmd->audio_file_info, tmp);
368         free(tmp);
369         tmp  = make_message("%s:\n%s:\n%s:\n", status_item_list[SI_DBINFO1],
370                 status_item_list[SI_DBINFO2], status_item_list[SI_DBINFO3]);
371         strcpy(mmd->selector_info, tmp);
372         free(tmp);
373         mmd->filename[0] = '\0';
374         mmd->size = 0;
375         mmd->events++;
376 }
377
378 /**
379  * get the header and of the current audio file
380  *
381  * \param header_len the length of the header is stored here
382  *
383  * \return a pointer to a buffer containing the header, or NULL, if no audio
384  * file is selected or if the current audio format does not need special header
385  * treamtment.
386  *
387  */
388 char *afs_get_header(int *header_len)
389 {
390         *header_len = 0;
391         if (mmd->audio_format < 0)
392                 return NULL;
393         if (!afl[mmd->audio_format].get_header_info)
394                 return NULL;
395         return afl[mmd->audio_format].get_header_info(header_len);
396 }
397 const char *supported_audio_formats(void)
398 {
399         return SUPPORTED_AUDIO_FORMATS;
400 }
401
402 /**
403  * get the chunk time of the current audio file
404  *
405  * \return a pointer to a struct containing the chunk time, or NULL,
406  * if currently no audio file is selected.
407  */
408 struct timeval *afs_chunk_time(void)
409 {
410         if (mmd->audio_format < 0)
411                 return NULL;
412         return &afl[mmd->audio_format].chunk_tv;
413 }
414
415 /**
416  * compute the timeout for para_server's main select-loop
417  *
418  * This function gets called from para_server to determine the timeout value
419  * for its main select loop.
420  *
421  * Before the timeout is computed, the current afs status flags are evaluated
422  * and acted upon by calling appropriate functions from the lower layers.
423  * Possible actions include
424  *
425  *      - request a new file list from the current audio file selector
426  *      - shutdown of all senders (stop/pause command)
427  *      - reposition the stream (ff/jmp command)
428  *
429  * \return A pointer to a struct timeval containing the timeout for the next
430  * chunk of data to be sent, or NULL if we're not sending right now.
431  */
432 struct timeval *afs_preselect(void)
433 {
434         struct audio_format_handler *af = NULL;
435         int i, format;
436         struct timeval *ret;
437 again:
438         format = mmd->audio_format;
439         if (format >= 0)
440                 af = afl + format;
441         else
442                 for (i = 0; senders[i].name; i++)
443                         senders[i].shutdown_clients();
444         if (afs_next() && af) {
445                 afs_eof(af);
446                 return afs_compute_timeout();
447         }
448         if (afs_paused() || afs_repos()) {
449                 for (i = 0; senders[i].name; i++)
450                         senders[i].shutdown_clients();
451                 if (af) {
452                         struct timeval now;
453                         gettimeofday(&now, NULL);
454                         if (!afs_paused() || mmd->chunks_sent)
455                                 tv_add(&af->eof_tv, &now, &eof_barrier);
456                         if (afs_repos())
457                                 tv_add(&now, &announce_tv, &data_send_barrier);
458                         if (mmd->new_afs_status_flags & AFS_NOMORE)
459                                 mmd->new_afs_status_flags = AFS_NEXT;
460                 }
461                 mmd->chunks_sent = 0;
462         }
463         if (af && afs_repos() && mmd->current_chunk != mmd->repos_request)
464                 af->reposition_stream(mmd->repos_request);
465         if (afs_repos()) {
466                 mmd->new_afs_status_flags &= ~(AFS_REPOS);
467                 mmd->current_chunk = mmd->repos_request;
468         }
469         ret = afs_compute_timeout();
470         if (!ret && !audio_file && afs_playing() &&
471                         !(mmd->new_afs_status_flags & AFS_NOMORE)) {
472                 PARA_DEBUG_LOG("%s", "ready and playing, but no audio file\n");
473                 get_song();
474                 goto again;
475         }
476         return ret;
477 }
478
479 /**
480  * afs_send_chunk - paraslash's main sending function
481  *
482  * This function gets called from para_server as soon as the next chunk of
483  * data should be pushed out. It first calls the read_chunk() function of
484  * the current audio format handler to obtain a pointer to the data to be
485  * sent out as well as its length. This information is then passed to each
486  * supported sender's send() function which does the actual sending.
487  *
488  * Return value: Positive return value on success, zero on eof and negative
489  * on errors.
490  */
491
492 void afs_send_chunk(void)
493 {
494         int i;
495         struct audio_format_handler *af;
496         char *buf;
497         ssize_t ret;
498         struct timeval now, due;
499
500         if (mmd->audio_format < 0 || !audio_file || !afs_playing())
501                 return;
502         af = &afl[mmd->audio_format];
503         gettimeofday(&now, NULL);
504         afs_next_chunk_time(&due);
505         if (tv_diff(&due, &now, NULL) > 0)
506                 return;
507         if (chk_barrier("eof", &now, &eof_barrier, &due, 1) < 0)
508                 return;
509         if (chk_barrier("data send", &now, &data_send_barrier,
510                         &due, 1) < 0)
511                 return;
512         buf = af->read_chunk(mmd->current_chunk, &ret);
513         mmd->new_afs_status_flags &= ~AFS_REPOS;
514         if (!buf) {
515                 if (ret < 0)
516                         mmd->new_afs_status_flags = AFS_NEXT;
517                 else
518                         mmd->new_afs_status_flags |= AFS_NEXT;
519                 afs_eof(af);
520                 return;
521         }
522         if (!mmd->chunks_sent) {
523                 struct timeval tmp;
524                 gettimeofday(&mmd->stream_start, NULL);
525                 tv_scale(mmd->current_chunk, &af->chunk_tv, &tmp);
526                 mmd->offset = tv2ms(&tmp);
527                 mmd->events++;
528         }
529         for (i = 0; senders[i].name; i++)
530                 senders[i].send(mmd->current_chunk, mmd->chunks_sent, buf, ret);
531         mmd->new_afs_status_flags |= AFS_PLAYING;
532         mmd->chunks_sent++;
533         mmd->current_chunk++;
534 }