Fudges for wav16, just like wav49
[asterisk/asterisk.git] / main / file.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Generic File Format Support.
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <dirent.h>
31 #include <sys/stat.h>
32 #include <math.h>
33
34 #include "asterisk/_private.h"  /* declare ast_file_init() */
35 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
36 #include "asterisk/mod_format.h"
37 #include "asterisk/cli.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/sched.h"
40 #include "asterisk/translate.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/app.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/linkedlists.h"
46 #include "asterisk/module.h"
47
48 /*
49  * The following variable controls the layout of localized sound files.
50  * If 0, use the historical layout with prefix just before the filename
51  * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
52  * if 1 put the prefix at the beginning of the filename
53  * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
54  * The latter permits a language to be entirely in one directory.
55  */
56 int ast_language_is_prefix = 1;
57
58 static AST_RWLIST_HEAD_STATIC(formats, ast_format);
59
60 int __ast_format_register(const struct ast_format *f, struct ast_module *mod)
61 {
62         struct ast_format *tmp;
63
64         AST_RWLIST_WRLOCK(&formats);
65         AST_RWLIST_TRAVERSE(&formats, tmp, list) {
66                 if (!strcasecmp(f->name, tmp->name)) {
67                         AST_RWLIST_UNLOCK(&formats);
68                         ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
69                         return -1;
70                 }
71         }
72         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
73                 AST_RWLIST_UNLOCK(&formats);
74                 return -1;
75         }
76         *tmp = *f;
77         tmp->module = mod;
78         if (tmp->buf_size) {
79                 /*
80                  * Align buf_size properly, rounding up to the machine-specific
81                  * alignment for pointers.
82                  */
83                 struct _test_align { void *a, *b; } p;
84                 int align = (char *)&p.b - (char *)&p.a;
85                 tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
86         }
87         
88         memset(&tmp->list, 0, sizeof(tmp->list));
89
90         AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
91         AST_RWLIST_UNLOCK(&formats);
92         ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
93
94         return 0;
95 }
96
97 int ast_format_unregister(const char *name)
98 {
99         struct ast_format *tmp;
100         int res = -1;
101
102         AST_RWLIST_WRLOCK(&formats);
103         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
104                 if (!strcasecmp(name, tmp->name)) {
105                         AST_RWLIST_REMOVE_CURRENT(list);
106                         ast_free(tmp);
107                         res = 0;
108                 }
109         }
110         AST_RWLIST_TRAVERSE_SAFE_END;
111         AST_RWLIST_UNLOCK(&formats);
112
113         if (!res)
114                 ast_verb(2, "Unregistered format %s\n", name);
115         else
116                 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
117
118         return res;
119 }
120
121 int ast_stopstream(struct ast_channel *tmp)
122 {
123         ast_channel_lock(tmp);
124
125         /* Stop a running stream if there is one */
126         if (tmp->stream) {
127                 ast_closestream(tmp->stream);
128                 tmp->stream = NULL;
129                 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
130                         ast_log(LOG_WARNING, "Unable to restore format back to %d\n", tmp->oldwriteformat);
131         }
132         /* Stop the video stream too */
133         if (tmp->vstream != NULL) {
134                 ast_closestream(tmp->vstream);
135                 tmp->vstream = NULL;
136         }
137
138         ast_channel_unlock(tmp);
139
140         return 0;
141 }
142
143 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
144 {
145         int res = -1;
146         int alt = 0;
147         if (f->frametype == AST_FRAME_VIDEO) {
148                 if (fs->fmt->format & AST_FORMAT_AUDIO_MASK) {
149                         /* This is the audio portion.  Call the video one... */
150                         if (!fs->vfs && fs->filename) {
151                                 const char *type = ast_getformatname(f->subclass & ~0x1);
152                                 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
153                                 ast_debug(1, "Opened video output file\n");
154                         }
155                         if (fs->vfs)
156                                 return ast_writestream(fs->vfs, f);
157                         /* else ignore */
158                         return 0;                               
159                 } else {
160                         /* Might / might not have mark set */
161                         alt = 1;
162                 }
163         } else if (f->frametype != AST_FRAME_VOICE) {
164                 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
165                 return -1;
166         }
167         if (((fs->fmt->format | alt) & f->subclass) == f->subclass) {
168                 res =  fs->fmt->write(fs, f);
169                 if (res < 0) 
170                         ast_log(LOG_WARNING, "Natural write failed\n");
171                 else if (res > 0)
172                         ast_log(LOG_WARNING, "Huh??\n");
173         } else {
174                 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
175                        the one we've setup a translator for, we do the "wrong thing" XXX */
176                 if (fs->trans && f->subclass != fs->lastwriteformat) {
177                         ast_translator_free_path(fs->trans);
178                         fs->trans = NULL;
179                 }
180                 if (!fs->trans) 
181                         fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass);
182                 if (!fs->trans)
183                         ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
184                                 fs->fmt->name, ast_getformatname(f->subclass));
185                 else {
186                         struct ast_frame *trf;
187                         fs->lastwriteformat = f->subclass;
188                         /* Get the translated frame but don't consume the original in case they're using it on another stream */
189                         trf = ast_translate(fs->trans, f, 0);
190                         if (trf) {
191                                 res = fs->fmt->write(fs, trf);
192                                 ast_frfree(trf);
193                                 if (res) 
194                                         ast_log(LOG_WARNING, "Translated frame write failed\n");
195                         } else
196                                 res = 0;
197                 }
198         }
199         return res;
200 }
201
202 static int copy(const char *infile, const char *outfile)
203 {
204         int ifd, ofd, len;
205         char buf[4096]; /* XXX make it lerger. */
206
207         if ((ifd = open(infile, O_RDONLY)) < 0) {
208                 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
209                 return -1;
210         }
211         if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
212                 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
213                 close(ifd);
214                 return -1;
215         }
216         while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
217                 int res;
218                 if (len < 0) {
219                         ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
220                         break;
221                 }
222                 /* XXX handle partial writes */
223                 res = write(ofd, buf, len);
224                 if (res != len) {
225                         ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
226                         len = -1; /* error marker */
227                         break;
228                 }
229         }
230         close(ifd);
231         close(ofd);
232         if (len < 0) {
233                 unlink(outfile);
234                 return -1; /* error */
235         }
236         return 0;       /* success */
237 }
238
239 /*!
240  * \brief construct a filename. Absolute pathnames are preserved,
241  * relative names are prefixed by the sounds/ directory.
242  * The wav49 suffix is replaced by 'WAV'.
243  * Returns a malloc'ed string to be freed by the caller.
244  */
245 static char *build_filename(const char *filename, const char *ext)
246 {
247         char *fn = NULL;
248
249         if (!strcmp(ext, "wav49"))
250                 ext = "WAV";
251         if (!strcmp(ext, "wav16"))
252                 ext = "Wav";
253
254         if (filename[0] == '/')
255                 asprintf(&fn, "%s.%s", filename, ext);
256         else
257                 asprintf(&fn, "%s/sounds/%s.%s",
258                         ast_config_AST_DATA_DIR, filename, ext);
259         return fn;
260 }
261
262 /* compare type against the list 'exts' */
263 /* XXX need a better algorithm */
264 static int exts_compare(const char *exts, const char *type)
265 {
266         char tmp[256];
267         char *stringp = tmp, *ext;
268
269         ast_copy_string(tmp, exts, sizeof(tmp));
270         while ((ext = strsep(&stringp, "|"))) {
271                 if (!strcmp(ext, type))
272                         return 1;
273         }
274
275         return 0;
276 }
277
278 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
279 {
280         struct ast_filestream *s;
281
282         int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;    /* total allocation size */
283         if ( (s = ast_calloc(1, l)) == NULL)
284                 return NULL;
285         s->fmt = fmt;
286         s->f = bfile;
287
288         if (fmt->desc_size)
289                 s->_private = ((char *)(s + 1)) + fmt->buf_size;
290         if (fmt->buf_size)
291                 s->buf = (char *)(s + 1);
292         s->fr.src = fmt->name;
293         return s;
294 }
295
296 /*
297  * Default implementations of open and rewrite.
298  * Only use them if you don't have expensive stuff to do.
299  */
300 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
301
302 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
303 {
304         struct ast_format *f = s->fmt;
305         int ret = -1;
306
307         if (mode == WRAP_OPEN && f->open && f->open(s))
308                 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
309         else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
310                 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
311         else {
312                 /* preliminary checks succeed. update usecount */
313                 ast_module_ref(f->module);
314                 ret = 0;
315         }
316         return ret;
317 }
318
319 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
320 {
321         return fn_wrapper(s, comment, WRAP_REWRITE);
322 }
323
324 static int open_wrapper(struct ast_filestream *s)
325 {
326         return fn_wrapper(s, NULL, WRAP_OPEN);
327 }
328
329 enum file_action {
330         ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
331         ACTION_DELETE,  /* delete file, return 0 on success, -1 on error */
332         ACTION_RENAME,  /* rename file. return 0 on success, -1 on error */
333         ACTION_OPEN,
334         ACTION_COPY     /* copy file. return 0 on success, -1 on error */
335 };
336
337 /*!
338  * \brief perform various actions on a file. Second argument
339  * arg2 depends on the command:
340  *      unused for EXISTS and DELETE
341  *      destination file name (const char *) for COPY and RENAME
342  *      struct ast_channel * for OPEN
343  * if fmt is NULL, OPEN will return the first matching entry,
344  * whereas other functions will run on all matching entries.
345  */
346 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
347 {
348         struct ast_format *f;
349         int res = (action == ACTION_EXISTS) ? 0 : -1;
350
351         AST_RWLIST_RDLOCK(&formats);
352         /* Check for a specific format */
353         AST_RWLIST_TRAVERSE(&formats, f, list) {
354                 char *stringp, *ext = NULL;
355
356                 if (fmt && !exts_compare(f->exts, fmt))
357                         continue;
358
359                 /* Look for a file matching the supported extensions.
360                  * The file must exist, and for OPEN, must match
361                  * one of the formats supported by the channel.
362                  */
363                 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
364                 while ( (ext = strsep(&stringp, "|")) ) {
365                         struct stat st;
366                         char *fn = build_filename(filename, ext);
367
368                         if (fn == NULL)
369                                 continue;
370
371                         if ( stat(fn, &st) ) { /* file not existent */
372                                 ast_free(fn);
373                                 continue;
374                         }
375                         /* for 'OPEN' we need to be sure that the format matches
376                          * what the channel can process
377                          */
378                         if (action == ACTION_OPEN) {
379                                 struct ast_channel *chan = (struct ast_channel *)arg2;
380                                 FILE *bfile;
381                                 struct ast_filestream *s;
382
383                                 if ( !(chan->writeformat & f->format) &&
384                                      !((f->format & AST_FORMAT_AUDIO_MASK && fmt) ||
385                                           (f->format & AST_FORMAT_VIDEO_MASK && fmt))) {
386                                         ast_free(fn);
387                                         continue;       /* not a supported format */
388                                 }
389                                 if ( (bfile = fopen(fn, "r")) == NULL) {
390                                         ast_free(fn);
391                                         continue;       /* cannot open file */
392                                 }
393                                 s = get_filestream(f, bfile);
394                                 if (!s) {
395                                         fclose(bfile);
396                                         ast_free(fn);   /* cannot allocate descriptor */
397                                         continue;
398                                 }
399                                 if (open_wrapper(s)) {
400                                         fclose(bfile);
401                                         ast_free(fn);
402                                         ast_free(s);
403                                         continue;       /* cannot run open on file */
404                                 }
405                                 /* ok this is good for OPEN */
406                                 res = 1;        /* found */
407                                 s->lasttimeout = -1;
408                                 s->fmt = f;
409                                 s->trans = NULL;
410                                 s->filename = NULL;
411                                 if (s->fmt->format & AST_FORMAT_AUDIO_MASK) {
412                                         if (chan->stream)
413                                                 ast_closestream(chan->stream);
414                                         chan->stream = s;
415                                 } else {
416                                         if (chan->vstream)
417                                                 ast_closestream(chan->vstream);
418                                         chan->vstream = s;
419                                 }
420                                 ast_free(fn);
421                                 break;
422                         }
423                         switch (action) {
424                         case ACTION_OPEN:
425                                 break;  /* will never get here */
426
427                         case ACTION_EXISTS:     /* return the matching format */
428                                 res |= f->format;
429                                 break;
430
431                         case ACTION_DELETE:
432                                 if ( (res = unlink(fn)) )
433                                         ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
434                                 break;
435
436                         case ACTION_RENAME:
437                         case ACTION_COPY: {
438                                 char *nfn = build_filename((const char *)arg2, ext);
439                                 if (!nfn)
440                                         ast_log(LOG_WARNING, "Out of memory\n");
441                                 else {
442                                         res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
443                                         if (res)
444                                                 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
445                                                         action == ACTION_COPY ? "copy" : "rename",
446                                                          fn, nfn, strerror(errno));
447                                         ast_free(nfn);
448                                 }
449                             }
450                                 break;
451
452                         default:
453                                 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
454                         }
455                         ast_free(fn);
456                 }
457         }
458         AST_RWLIST_UNLOCK(&formats);
459         return res;
460 }
461
462 static int is_absolute_path(const char *filename)
463 {
464         return filename[0] == '/';
465 }
466
467 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
468                            char *buf, int buflen)
469 {
470         if (buf == NULL) {
471                 return -1;
472         }
473
474         if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
475                 if (lang) {
476                         snprintf(buf, buflen, "%s/%s", lang, filename);
477                 } else {
478                         snprintf(buf, buflen, "%s", filename);
479                 }
480         } else { /* old layout */
481                 strcpy(buf, filename);  /* first copy the full string */
482                 if (lang) {
483                         /* insert the language and suffix if needed */
484                         const char *c = strrchr(filename, '/');
485                         int offset = c ? c - filename + 1 : 0;  /* points right after the last '/' */
486                         snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
487                 }
488         }
489
490         return ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
491 }
492
493 /*!
494  * \brief helper routine to locate a file with a given format
495  * and language preference.
496  * Try preflang, preflang with stripped '_' suffix, or NULL.
497  * In the standard asterisk, language goes just before the last component.
498  * In an alternative configuration, the language should be a prefix
499  * to the actual filename.
500  *
501  * The last parameter(s) point to a buffer of sufficient size,
502  * which on success is filled with the matching filename.
503  */
504 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
505                            char *buf, int buflen)
506 {
507         int res = -1;
508         char *lang = NULL;
509
510         if (buf == NULL) {
511                 return -1;
512         }
513
514         /* We try languages in the following order:
515          *    preflang (may include dialect)
516          *    lang (preflang without dialect - if any)
517          *    <none>
518          *    default (unless the same as preflang or lang without dialect)
519          */
520
521         /* Try preferred language */
522         if (!ast_strlen_zero(preflang)) {
523                 /* try the preflang exactly as it was requested */
524                 if ((res = fileexists_test(filename, fmt, preflang, buf, buflen)) > 0) {
525                         return res;
526                 } else {
527                         /* try without a dialect */
528                         char *postfix = NULL;
529                         postfix = lang = ast_strdupa(preflang);
530
531                         strsep(&postfix, "_");
532                         if (postfix) {
533                                 if ((res = fileexists_test(filename, fmt, lang, buf, buflen)) > 0) {
534                                         return res;
535                                 }
536                         }
537                 }
538         }
539
540         /* Try without any language */
541         if ((res = fileexists_test(filename, fmt, NULL, buf, buflen)) > 0) {
542                 return res;
543         }
544
545         /* Finally try the default language unless it was already tried before */
546         if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
547                 if ((res = fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen)) > 0) {
548                         return res;
549                 }
550         }
551
552         return 0;
553 }
554
555 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
556 {
557         return ast_openstream_full(chan, filename, preflang, 0);
558 }
559
560 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
561 {
562         /* 
563          * Use fileexists_core() to find a file in a compatible
564          * language and format, set up a suitable translator,
565          * and open the stream.
566          */
567         int fmts, res, buflen;
568         char *buf;
569
570         if (!asis) {
571                 /* do this first, otherwise we detect the wrong writeformat */
572                 ast_stopstream(chan);
573                 if (chan->generator)
574                         ast_deactivate_generator(chan);
575         }
576         if (preflang == NULL)
577                 preflang = "";
578         buflen = strlen(preflang) + strlen(filename) + 4;
579         buf = alloca(buflen);
580         if (buf == NULL)
581                 return NULL;
582         fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
583         if (fmts > 0)
584                 fmts &= AST_FORMAT_AUDIO_MASK;
585         if (fmts < 1) {
586                 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
587                 return NULL;
588         }
589         chan->oldwriteformat = chan->writeformat;
590         /* Set the channel to a format we can work with */
591         res = ast_set_write_format(chan, fmts);
592         res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
593         if (res >= 0)
594                 return chan->stream;
595         return NULL;
596 }
597
598 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
599 {
600         /* As above, but for video. But here we don't have translators
601          * so we must enforce a format.
602          */
603         unsigned int format;
604         char *buf;
605         int buflen;
606
607         if (preflang == NULL)
608                 preflang = "";
609         buflen = strlen(preflang) + strlen(filename) + 4;
610         buf = alloca(buflen);
611         if (buf == NULL)
612                 return NULL;
613
614         for (format = AST_FORMAT_AUDIO_MASK + 1; format <= AST_FORMAT_VIDEO_MASK; format = format << 1) {
615                 int fd;
616                 const char *fmt;
617
618                 if (!(chan->nativeformats & format))
619                         continue;
620                 fmt = ast_getformatname(format);
621                 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
622                         continue;
623                 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
624                 if (fd >= 0)
625                         return chan->vstream;
626                 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
627         }
628         return NULL;
629 }
630
631 struct ast_frame *ast_readframe(struct ast_filestream *s)
632 {
633         struct ast_frame *f = NULL;
634         int whennext = 0;       
635         if (s && s->fmt)
636                 f = s->fmt->read(s, &whennext);
637         return f;
638 }
639
640 enum fsread_res {
641         FSREAD_FAILURE,
642         FSREAD_SUCCESS_SCHED,
643         FSREAD_SUCCESS_NOSCHED,
644 };
645
646 static int ast_fsread_audio(const void *data);
647
648 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
649 {
650         int whennext = 0;
651
652         while (!whennext) {
653                 struct ast_frame *fr;
654                 
655                 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name))
656                         goto return_failure;
657                 
658                 fr = s->fmt->read(s, &whennext);
659                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
660                         if (fr)
661                                 ast_log(LOG_WARNING, "Failed to write frame\n");
662                         goto return_failure;
663                 }
664         }
665         if (whennext != s->lasttimeout) {
666                 if (s->owner->timingfd > -1) {
667                         float samp_rate = (float) ast_format_rate(s->fmt->format);
668                         unsigned int rate;
669
670                         rate = (unsigned int) roundf(samp_rate / ((float) whennext));
671
672                         ast_settimeout(s->owner, rate, ast_fsread_audio, s);
673                 } else {
674                         s->owner->streamid = ast_sched_add(s->owner->sched, 
675                                 whennext / (ast_format_rate(s->fmt->format) / 1000), ast_fsread_audio, s);
676                 }
677                 s->lasttimeout = whennext;
678                 return FSREAD_SUCCESS_NOSCHED;
679         }
680         return FSREAD_SUCCESS_SCHED;
681
682 return_failure:
683         s->owner->streamid = -1;
684         ast_settimeout(s->owner, 0, NULL, NULL);
685         return FSREAD_FAILURE;
686 }
687
688 static int ast_fsread_audio(const void *data)
689 {
690         struct ast_filestream *fs = (struct ast_filestream *)data;
691         enum fsread_res res;
692
693         res = ast_readaudio_callback(fs);
694
695         if (res == FSREAD_SUCCESS_SCHED)
696                 return 1;
697         
698         return 0;
699 }
700
701 static int ast_fsread_video(const void *data);
702
703 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
704 {
705         int whennext = 0;
706
707         while (!whennext) {
708                 struct ast_frame *fr = s->fmt->read(s, &whennext);
709                 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
710                         if (fr)
711                                 ast_log(LOG_WARNING, "Failed to write frame\n");
712                         s->owner->vstreamid = -1;
713                         return FSREAD_FAILURE;
714                 }
715         }
716
717         if (whennext != s->lasttimeout) {
718                 s->owner->vstreamid = ast_sched_add(s->owner->sched, 
719                         whennext / (ast_format_rate(s->fmt->format) / 1000), 
720                         ast_fsread_video, s);
721                 s->lasttimeout = whennext;
722                 return FSREAD_SUCCESS_NOSCHED;
723         }
724
725         return FSREAD_SUCCESS_SCHED;
726 }
727
728 static int ast_fsread_video(const void *data)
729 {
730         struct ast_filestream *fs = (struct ast_filestream *)data;
731         enum fsread_res res;
732
733         res = ast_readvideo_callback(fs);
734
735         if (res == FSREAD_SUCCESS_SCHED)
736                 return 1;
737         
738         return 0;
739 }
740
741 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
742 {
743         s->owner = chan;
744         return 0;
745 }
746
747 int ast_playstream(struct ast_filestream *s)
748 {
749         enum fsread_res res;
750
751         if (s->fmt->format & AST_FORMAT_AUDIO_MASK)
752                 res = ast_readaudio_callback(s);
753         else
754                 res = ast_readvideo_callback(s);
755
756         return (res == FSREAD_FAILURE) ? -1 : 0;
757 }
758
759 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
760 {
761         return fs->fmt->seek(fs, sample_offset, whence);
762 }
763
764 int ast_truncstream(struct ast_filestream *fs)
765 {
766         return fs->fmt->trunc(fs);
767 }
768
769 off_t ast_tellstream(struct ast_filestream *fs)
770 {
771         return fs->fmt->tell(fs);
772 }
773
774 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
775 {
776         return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
777 }
778
779 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
780 {
781         return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
782 }
783
784 int ast_closestream(struct ast_filestream *f)
785 {
786         char *cmd = NULL;
787         size_t size = 0;
788         /* Stop a running stream if there is one */
789         if (f->owner) {
790                 if (f->fmt->format & AST_FORMAT_AUDIO_MASK) {
791                         f->owner->stream = NULL;
792                         AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
793                         ast_settimeout(f->owner, 0, NULL, NULL);
794                 } else {
795                         f->owner->vstream = NULL;
796                         AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
797                 }
798         }
799         /* destroy the translator on exit */
800         if (f->trans)
801                 ast_translator_free_path(f->trans);
802
803         if (f->realfilename && f->filename) {
804                         size = strlen(f->filename) + strlen(f->realfilename) + 15;
805                         cmd = alloca(size);
806                         memset(cmd, 0, size);
807                         snprintf(cmd, size, "/bin/mv -f %s %s", f->filename, f->realfilename);
808                         ast_safe_system(cmd);
809         }
810
811         if (f->fmt->close) {
812                 f->fmt->close(f);
813         }
814         if (f->filename)
815                 ast_free(f->filename);
816         if (f->realfilename)
817                 ast_free(f->realfilename);
818         fclose(f->f);
819         if (f->vfs)
820                 ast_closestream(f->vfs);
821         if (f->orig_chan_name)
822                 free((void *) f->orig_chan_name);
823         if (f->write_buffer) {
824                 ast_free(f->write_buffer);
825         }
826
827         ast_module_unref(f->fmt->module);
828         ast_free(f);
829         return 0;
830 }
831
832
833 /*
834  * Look the various language-specific places where a file could exist.
835  */
836 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
837 {
838         char *buf;
839         int buflen;
840
841         if (preflang == NULL)
842                 preflang = "";
843         buflen = strlen(preflang) + strlen(filename) + 4;       /* room for everything */
844         buf = alloca(buflen);
845         if (buf == NULL)
846                 return 0;
847         return fileexists_core(filename, fmt, preflang, buf, buflen);
848 }
849
850 int ast_filedelete(const char *filename, const char *fmt)
851 {
852         return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
853 }
854
855 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
856 {
857         return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
858 }
859
860 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
861 {
862         return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
863 }
864
865 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
866 {
867         struct ast_filestream *fs;
868         struct ast_filestream *vfs=NULL;
869         char fmt[256];
870
871         fs = ast_openstream(chan, filename, preflang);
872         if (fs)
873                 vfs = ast_openvstream(chan, filename, preflang);
874         if (vfs) {
875                 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
876         }
877         if (fs){
878                 int res;
879                 if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
880                         fs->orig_chan_name = ast_strdup(chan->name);
881                 if (ast_applystream(chan, fs))
882                         return -1;
883                 if (vfs && ast_applystream(chan, vfs))
884                         return -1;
885                 res = ast_playstream(fs);
886                 if (!res && vfs)
887                         res = ast_playstream(vfs);
888                 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", chan->name, filename, ast_getformatname(chan->writeformat), preflang ? preflang : "default");
889
890                 return res;
891         }
892         ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
893         return -1;
894 }
895
896 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
897 {
898         FILE *bfile;
899         struct ast_format *f;
900         struct ast_filestream *fs = NULL;
901         char *fn;
902         int format_found = 0;   
903
904         AST_RWLIST_RDLOCK(&formats);
905
906         AST_RWLIST_TRAVERSE(&formats, f, list) {
907                 fs = NULL;
908                 if (!exts_compare(f->exts, type))
909                         continue;
910                 else 
911                         format_found = 1;
912
913                 fn = build_filename(filename, type);
914                 errno = 0;
915                 bfile = fopen(fn, "r");
916
917                 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
918                         ast_log(LOG_WARNING, "Unable to open %s\n", fn);
919                         if (fs)
920                                 ast_free(fs);
921                         fs = NULL;
922                         if (bfile)
923                                 fclose(bfile);
924                         ast_free(fn);
925                         break;                          
926                 }
927                 /* found it */
928                 fs->trans = NULL;
929                 fs->fmt = f;
930                 fs->flags = flags;
931                 fs->mode = mode;
932                 fs->filename = ast_strdup(filename);
933                 fs->vfs = NULL;
934                 break;
935         }
936
937         AST_RWLIST_UNLOCK(&formats);
938         if (!format_found)
939                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
940
941         return fs;
942 }
943
944 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
945 {
946         int fd, myflags = 0;
947         /* compiler claims this variable can be used before initialization... */
948         FILE *bfile = NULL;
949         struct ast_format *f;
950         struct ast_filestream *fs = NULL;
951         char *buf = NULL;
952         size_t size = 0;
953         int format_found = 0;
954
955         AST_RWLIST_RDLOCK(&formats);
956
957         /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
958         /* We really can't use O_APPEND as it will break WAV header updates */
959         if (flags & O_APPEND) { 
960                 flags &= ~O_APPEND;
961         } else {
962                 myflags = O_TRUNC;
963         }
964         
965         myflags |= O_WRONLY | O_CREAT;
966
967         /* XXX need to fix this - we should just do the fopen,
968          * not open followed by fdopen()
969          */
970         AST_RWLIST_TRAVERSE(&formats, f, list) {
971                 char *fn, *orig_fn = NULL;
972                 if (fs)
973                         break;
974
975                 if (!exts_compare(f->exts, type))
976                         continue;
977                 else
978                         format_found = 1;
979
980                 fn = build_filename(filename, type);
981                 fd = open(fn, flags | myflags, mode);
982                 if (fd > -1) {
983                         /* fdopen() the resulting file stream */
984                         bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
985                         if (!bfile) {
986                                 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
987                                 close(fd);
988                                 fd = -1;
989                         }
990                 }
991                 
992                 if (ast_opt_cache_record_files && (fd > -1)) {
993                         char *c;
994
995                         fclose(bfile);  /* this also closes fd */
996                         /*
997                           We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
998                           What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
999                         */
1000                         orig_fn = ast_strdupa(fn);
1001                         for (c = fn; *c; c++)
1002                                 if (*c == '/')
1003                                         *c = '_';
1004
1005                         size = strlen(fn) + strlen(record_cache_dir) + 2;
1006                         buf = alloca(size);
1007                         strcpy(buf, record_cache_dir);
1008                         strcat(buf, "/");
1009                         strcat(buf, fn);
1010                         ast_free(fn);
1011                         fn = buf;
1012                         fd = open(fn, flags | myflags, mode);
1013                         if (fd > -1) {
1014                                 /* fdopen() the resulting file stream */
1015                                 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1016                                 if (!bfile) {
1017                                         ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1018                                         close(fd);
1019                                         fd = -1;
1020                                 }
1021                         }
1022                 }
1023                 if (fd > -1) {
1024                         errno = 0;
1025                         fs = get_filestream(f, bfile);
1026                         if (!fs || rewrite_wrapper(fs, comment)) {
1027                                 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1028                                 close(fd);
1029                                 if (orig_fn) {
1030                                         unlink(fn);
1031                                         unlink(orig_fn);
1032                                 }
1033                                 if (fs)
1034                                         ast_free(fs);
1035                                 fs = NULL;
1036                                 continue;
1037                         }
1038                         fs->trans = NULL;
1039                         fs->fmt = f;
1040                         fs->flags = flags;
1041                         fs->mode = mode;
1042                         if (orig_fn) {
1043                                 fs->realfilename = ast_strdup(orig_fn);
1044                                 fs->filename = ast_strdup(fn);
1045                         } else {
1046                                 fs->realfilename = NULL;
1047                                 fs->filename = ast_strdup(filename);
1048                         }
1049                         fs->vfs = NULL;
1050                         /* If truncated, we'll be at the beginning; if not truncated, then append */
1051
1052                         if ((fs->write_buffer = ast_malloc(32768))){
1053                                 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1054                         }
1055
1056                         f->seek(fs, 0, SEEK_END);
1057                 } else if (errno != EEXIST) {
1058                         ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1059                         if (orig_fn)
1060                                 unlink(orig_fn);
1061                 }
1062                 /* if buf != NULL then fn is already free and pointing to it */
1063                 if (!buf)
1064                         ast_free(fn);
1065         }
1066
1067         AST_RWLIST_UNLOCK(&formats);
1068
1069         if (!format_found)
1070                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1071
1072         return fs;
1073 }
1074
1075 /*!
1076  * \brief the core of all waitstream() functions
1077  */
1078 static int waitstream_core(struct ast_channel *c, const char *breakon,
1079         const char *forward, const char *reverse, int skip_ms,
1080         int audiofd, int cmdfd,  const char *context)
1081 {
1082         const char *orig_chan_name = NULL;
1083         int err = 0;
1084
1085         if (!breakon)
1086                 breakon = "";
1087         if (!forward)
1088                 forward = "";
1089         if (!reverse)
1090                 reverse = "";
1091
1092         /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1093         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1094
1095         if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1096                 orig_chan_name = ast_strdupa(c->name);
1097
1098         while (c->stream) {
1099                 int res;
1100                 int ms;
1101
1102                 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1103                         ast_stopstream(c);
1104                         err = 1;
1105                         break;
1106                 }
1107
1108                 ms = ast_sched_wait(c->sched);
1109
1110                 if (ms < 0 && !c->timingfunc) {
1111                         ast_stopstream(c);
1112                         break;
1113                 }
1114                 if (ms < 0)
1115                         ms = 1000;
1116                 if (cmdfd < 0) {
1117                         res = ast_waitfor(c, ms);
1118                         if (res < 0) {
1119                                 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1120                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1121                                 return res;
1122                         }
1123                 } else {
1124                         int outfd;
1125                         struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1126                         if (!rchan && (outfd < 0) && (ms)) {
1127                                 /* Continue */
1128                                 if (errno == EINTR)
1129                                         continue;
1130                                 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1131                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1132                                 return -1;
1133                         } else if (outfd > -1) { /* this requires cmdfd set */
1134                                 /* The FD we were watching has something waiting */
1135                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1136                                 return 1;
1137                         }
1138                         /* if rchan is set, it is 'c' */
1139                         res = rchan ? 1 : 0; /* map into 'res' values */
1140                 }
1141                 if (res > 0) {
1142                         struct ast_frame *fr = ast_read(c);
1143                         if (!fr) {
1144                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1145                                 return -1;
1146                         }
1147                         switch (fr->frametype) {
1148                         case AST_FRAME_DTMF_END:
1149                                 if (context) {
1150                                         const char exten[2] = { fr->subclass, '\0' };
1151                                         if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1152                                                 res = fr->subclass;
1153                                                 ast_frfree(fr);
1154                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1155                                                 return res;
1156                                         }
1157                                 } else {
1158                                         res = fr->subclass;
1159                                         if (strchr(forward, res)) {
1160                                                 ast_stream_fastforward(c->stream, skip_ms);
1161                                         } else if (strchr(reverse, res)) {
1162                                                 ast_stream_rewind(c->stream, skip_ms);
1163                                         } else if (strchr(breakon, res)) {
1164                                                 ast_frfree(fr);
1165                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1166                                                 return res;
1167                                         }                                       
1168                                 }
1169                                 break;
1170                         case AST_FRAME_CONTROL:
1171                                 switch (fr->subclass) {
1172                                 case AST_CONTROL_HANGUP:
1173                                 case AST_CONTROL_BUSY:
1174                                 case AST_CONTROL_CONGESTION:
1175                                         ast_frfree(fr);
1176                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1177                                         return -1;
1178                                 case AST_CONTROL_RINGING:
1179                                 case AST_CONTROL_ANSWER:
1180                                 case AST_CONTROL_VIDUPDATE:
1181                                 case AST_CONTROL_SRCUPDATE:
1182                                 case AST_CONTROL_HOLD:
1183                                 case AST_CONTROL_UNHOLD:
1184                                         /* Unimportant */
1185                                         break;
1186                                 default:
1187                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1188                                 }
1189                                 break;
1190                         case AST_FRAME_VOICE:
1191                                 /* Write audio if appropriate */
1192                                 if (audiofd > -1)
1193                                         write(audiofd, fr->data.ptr, fr->datalen);
1194                         default:
1195                                 /* Ignore all others */
1196                                 break;
1197                         }
1198                         ast_frfree(fr);
1199                 }
1200                 ast_sched_runq(c->sched);
1201         }
1202
1203         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1204
1205         return (err || c->_softhangup) ? -1 : 0;
1206 }
1207
1208 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1209 {
1210         return waitstream_core(c, breakon, forward, reverse, ms,
1211                 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1212 }
1213
1214 int ast_waitstream(struct ast_channel *c, const char *breakon)
1215 {
1216         return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1217 }
1218
1219 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1220 {
1221         return waitstream_core(c, breakon, NULL, NULL, 0,
1222                 audiofd, cmdfd, NULL /* no context */);
1223 }
1224
1225 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1226 {
1227         /* Waitstream, with return in the case of a valid 1 digit extension */
1228         /* in the current or specified context being pressed */
1229
1230         if (!context)
1231                 context = c->context;
1232         return waitstream_core(c, NULL, NULL, NULL, 0,
1233                 -1, -1, context);
1234 }
1235
1236 /*
1237  * if the file name is non-empty, try to play it.
1238  * Return 0 if success, -1 if error, digit if interrupted by a digit.
1239  * If digits == "" then we can simply check for non-zero.
1240  */
1241 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1242 {
1243         int res = 0;
1244         if (!ast_strlen_zero(file)) {
1245                 res = ast_streamfile(chan, file, chan->language);
1246                 if (!res) {
1247                         res = ast_waitstream(chan, digits);
1248                 }
1249         }
1250         return res;
1251
1252
1253 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1254 {
1255 #define FORMAT "%-10s %-10s %-20s\n"
1256 #define FORMAT2 "%-10s %-10s %-20s\n"
1257         struct ast_format *f;
1258         int count_fmt = 0;
1259
1260         switch (cmd) {
1261         case CLI_INIT:
1262                 e->command = "core show file formats";
1263                 e->usage =
1264                         "Usage: core show file formats\n"
1265                         "       Displays currently registered file formats (if any).\n";
1266                 return NULL;
1267         case CLI_GENERATE:
1268                 return NULL;
1269         }
1270
1271         if (a->argc != 4)
1272                 return CLI_SHOWUSAGE;
1273
1274         ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1275         ast_cli(a->fd, FORMAT, "------", "----", "----------");
1276
1277         AST_RWLIST_RDLOCK(&formats);
1278         AST_RWLIST_TRAVERSE(&formats, f, list) {
1279                 ast_cli(a->fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1280                 count_fmt++;
1281         }
1282         AST_RWLIST_UNLOCK(&formats);
1283         ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1284         return CLI_SUCCESS;
1285 #undef FORMAT
1286 #undef FORMAT2
1287 }
1288
1289 struct ast_cli_entry cli_file[] = {
1290         AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1291 };
1292
1293 int ast_file_init(void)
1294 {
1295         ast_cli_register_multiple(cli_file, sizeof(cli_file) / sizeof(struct ast_cli_entry));
1296         return 0;
1297 }