Allow for video files to be opened as well as
[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
252         if (filename[0] == '/')
253                 asprintf(&fn, "%s.%s", filename, ext);
254         else
255                 asprintf(&fn, "%s/sounds/%s.%s",
256                         ast_config_AST_DATA_DIR, filename, ext);
257         return fn;
258 }
259
260 /* compare type against the list 'exts' */
261 /* XXX need a better algorithm */
262 static int exts_compare(const char *exts, const char *type)
263 {
264         char tmp[256];
265         char *stringp = tmp, *ext;
266
267         ast_copy_string(tmp, exts, sizeof(tmp));
268         while ((ext = strsep(&stringp, "|"))) {
269                 if (!strcmp(ext, type))
270                         return 1;
271         }
272
273         return 0;
274 }
275
276 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
277 {
278         struct ast_filestream *s;
279
280         int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;    /* total allocation size */
281         if ( (s = ast_calloc(1, l)) == NULL)
282                 return NULL;
283         s->fmt = fmt;
284         s->f = bfile;
285
286         if (fmt->desc_size)
287                 s->_private = ((char *)(s + 1)) + fmt->buf_size;
288         if (fmt->buf_size)
289                 s->buf = (char *)(s + 1);
290         s->fr.src = fmt->name;
291         return s;
292 }
293
294 /*
295  * Default implementations of open and rewrite.
296  * Only use them if you don't have expensive stuff to do.
297  */
298 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
299
300 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
301 {
302         struct ast_format *f = s->fmt;
303         int ret = -1;
304
305         if (mode == WRAP_OPEN && f->open && f->open(s))
306                 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
307         else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
308                 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
309         else {
310                 /* preliminary checks succeed. update usecount */
311                 ast_module_ref(f->module);
312                 ret = 0;
313         }
314         return ret;
315 }
316
317 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
318 {
319         return fn_wrapper(s, comment, WRAP_REWRITE);
320 }
321
322 static int open_wrapper(struct ast_filestream *s)
323 {
324         return fn_wrapper(s, NULL, WRAP_OPEN);
325 }
326
327 enum file_action {
328         ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
329         ACTION_DELETE,  /* delete file, return 0 on success, -1 on error */
330         ACTION_RENAME,  /* rename file. return 0 on success, -1 on error */
331         ACTION_OPEN,
332         ACTION_COPY     /* copy file. return 0 on success, -1 on error */
333 };
334
335 /*!
336  * \brief perform various actions on a file. Second argument
337  * arg2 depends on the command:
338  *      unused for EXISTS and DELETE
339  *      destination file name (const char *) for COPY and RENAME
340  *      struct ast_channel * for OPEN
341  * if fmt is NULL, OPEN will return the first matching entry,
342  * whereas other functions will run on all matching entries.
343  */
344 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
345 {
346         struct ast_format *f;
347         int res = (action == ACTION_EXISTS) ? 0 : -1;
348
349         AST_RWLIST_RDLOCK(&formats);
350         /* Check for a specific format */
351         AST_RWLIST_TRAVERSE(&formats, f, list) {
352                 char *stringp, *ext = NULL;
353
354                 if (fmt && !exts_compare(f->exts, fmt))
355                         continue;
356
357                 /* Look for a file matching the supported extensions.
358                  * The file must exist, and for OPEN, must match
359                  * one of the formats supported by the channel.
360                  */
361                 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
362                 while ( (ext = strsep(&stringp, "|")) ) {
363                         struct stat st;
364                         char *fn = build_filename(filename, ext);
365
366                         if (fn == NULL)
367                                 continue;
368
369                         if ( stat(fn, &st) ) { /* file not existent */
370                                 ast_free(fn);
371                                 continue;
372                         }
373                         /* for 'OPEN' we need to be sure that the format matches
374                          * what the channel can process
375                          */
376                         if (action == ACTION_OPEN) {
377                                 struct ast_channel *chan = (struct ast_channel *)arg2;
378                                 FILE *bfile;
379                                 struct ast_filestream *s;
380
381                                 if ( !(chan->writeformat & f->format) &&
382                                      !((f->format & AST_FORMAT_AUDIO_MASK && fmt) ||
383                                           (f->format & AST_FORMAT_VIDEO_MASK && fmt))) {
384                                         ast_free(fn);
385                                         continue;       /* not a supported format */
386                                 }
387                                 if ( (bfile = fopen(fn, "r")) == NULL) {
388                                         ast_free(fn);
389                                         continue;       /* cannot open file */
390                                 }
391                                 s = get_filestream(f, bfile);
392                                 if (!s) {
393                                         fclose(bfile);
394                                         ast_free(fn);   /* cannot allocate descriptor */
395                                         continue;
396                                 }
397                                 if (open_wrapper(s)) {
398                                         fclose(bfile);
399                                         ast_free(fn);
400                                         ast_free(s);
401                                         continue;       /* cannot run open on file */
402                                 }
403                                 /* ok this is good for OPEN */
404                                 res = 1;        /* found */
405                                 s->lasttimeout = -1;
406                                 s->fmt = f;
407                                 s->trans = NULL;
408                                 s->filename = NULL;
409                                 if (s->fmt->format & AST_FORMAT_AUDIO_MASK) {
410                                         if (chan->stream)
411                                                 ast_closestream(chan->stream);
412                                         chan->stream = s;
413                                 } else {
414                                         if (chan->vstream)
415                                                 ast_closestream(chan->vstream);
416                                         chan->vstream = s;
417                                 }
418                                 ast_free(fn);
419                                 break;
420                         }
421                         switch (action) {
422                         case ACTION_OPEN:
423                                 break;  /* will never get here */
424
425                         case ACTION_EXISTS:     /* return the matching format */
426                                 res |= f->format;
427                                 break;
428
429                         case ACTION_DELETE:
430                                 if ( (res = unlink(fn)) )
431                                         ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
432                                 break;
433
434                         case ACTION_RENAME:
435                         case ACTION_COPY: {
436                                 char *nfn = build_filename((const char *)arg2, ext);
437                                 if (!nfn)
438                                         ast_log(LOG_WARNING, "Out of memory\n");
439                                 else {
440                                         res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
441                                         if (res)
442                                                 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
443                                                         action == ACTION_COPY ? "copy" : "rename",
444                                                          fn, nfn, strerror(errno));
445                                         ast_free(nfn);
446                                 }
447                             }
448                                 break;
449
450                         default:
451                                 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
452                         }
453                         ast_free(fn);
454                 }
455         }
456         AST_RWLIST_UNLOCK(&formats);
457         return res;
458 }
459
460 static int is_absolute_path(const char *filename)
461 {
462         return filename[0] == '/';
463 }
464
465 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
466                            char *buf, int buflen)
467 {
468         if (buf == NULL) {
469                 return -1;
470         }
471
472         if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
473                 if (lang) {
474                         snprintf(buf, buflen, "%s/%s", lang, filename);
475                 } else {
476                         snprintf(buf, buflen, "%s", filename);
477                 }
478         } else { /* old layout */
479                 strcpy(buf, filename);  /* first copy the full string */
480                 if (lang) {
481                         /* insert the language and suffix if needed */
482                         const char *c = strrchr(filename, '/');
483                         int offset = c ? c - filename + 1 : 0;  /* points right after the last '/' */
484                         snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
485                 }
486         }
487
488         return ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
489 }
490
491 /*!
492  * \brief helper routine to locate a file with a given format
493  * and language preference.
494  * Try preflang, preflang with stripped '_' suffix, or NULL.
495  * In the standard asterisk, language goes just before the last component.
496  * In an alternative configuration, the language should be a prefix
497  * to the actual filename.
498  *
499  * The last parameter(s) point to a buffer of sufficient size,
500  * which on success is filled with the matching filename.
501  */
502 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
503                            char *buf, int buflen)
504 {
505         int res = -1;
506         char *lang = NULL;
507
508         if (buf == NULL) {
509                 return -1;
510         }
511
512         /* We try languages in the following order:
513          *    preflang (may include dialect)
514          *    lang (preflang without dialect - if any)
515          *    <none>
516          *    default (unless the same as preflang or lang without dialect)
517          */
518
519         /* Try preferred language */
520         if (!ast_strlen_zero(preflang)) {
521                 /* try the preflang exactly as it was requested */
522                 if ((res = fileexists_test(filename, fmt, preflang, buf, buflen)) > 0) {
523                         return res;
524                 } else {
525                         /* try without a dialect */
526                         char *postfix = NULL;
527                         postfix = lang = ast_strdupa(preflang);
528
529                         strsep(&postfix, "_");
530                         if (postfix) {
531                                 if ((res = fileexists_test(filename, fmt, lang, buf, buflen)) > 0) {
532                                         return res;
533                                 }
534                         }
535                 }
536         }
537
538         /* Try without any language */
539         if ((res = fileexists_test(filename, fmt, NULL, buf, buflen)) > 0) {
540                 return res;
541         }
542
543         /* Finally try the default language unless it was already tried before */
544         if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
545                 if ((res = fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen)) > 0) {
546                         return res;
547                 }
548         }
549
550         return 0;
551 }
552
553 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
554 {
555         return ast_openstream_full(chan, filename, preflang, 0);
556 }
557
558 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
559 {
560         /* 
561          * Use fileexists_core() to find a file in a compatible
562          * language and format, set up a suitable translator,
563          * and open the stream.
564          */
565         int fmts, res, buflen;
566         char *buf;
567
568         if (!asis) {
569                 /* do this first, otherwise we detect the wrong writeformat */
570                 ast_stopstream(chan);
571                 if (chan->generator)
572                         ast_deactivate_generator(chan);
573         }
574         if (preflang == NULL)
575                 preflang = "";
576         buflen = strlen(preflang) + strlen(filename) + 4;
577         buf = alloca(buflen);
578         if (buf == NULL)
579                 return NULL;
580         fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
581         if (fmts > 0)
582                 fmts &= AST_FORMAT_AUDIO_MASK;
583         if (fmts < 1) {
584                 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
585                 return NULL;
586         }
587         chan->oldwriteformat = chan->writeformat;
588         /* Set the channel to a format we can work with */
589         res = ast_set_write_format(chan, fmts);
590         res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
591         if (res >= 0)
592                 return chan->stream;
593         return NULL;
594 }
595
596 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
597 {
598         /* As above, but for video. But here we don't have translators
599          * so we must enforce a format.
600          */
601         unsigned int format;
602         char *buf;
603         int buflen;
604
605         if (preflang == NULL)
606                 preflang = "";
607         buflen = strlen(preflang) + strlen(filename) + 4;
608         buf = alloca(buflen);
609         if (buf == NULL)
610                 return NULL;
611
612         for (format = AST_FORMAT_AUDIO_MASK + 1; format <= AST_FORMAT_VIDEO_MASK; format = format << 1) {
613                 int fd;
614                 const char *fmt;
615
616                 if (!(chan->nativeformats & format))
617                         continue;
618                 fmt = ast_getformatname(format);
619                 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
620                         continue;
621                 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
622                 if (fd >= 0)
623                         return chan->vstream;
624                 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
625         }
626         return NULL;
627 }
628
629 struct ast_frame *ast_readframe(struct ast_filestream *s)
630 {
631         struct ast_frame *f = NULL;
632         int whennext = 0;       
633         if (s && s->fmt)
634                 f = s->fmt->read(s, &whennext);
635         return f;
636 }
637
638 enum fsread_res {
639         FSREAD_FAILURE,
640         FSREAD_SUCCESS_SCHED,
641         FSREAD_SUCCESS_NOSCHED,
642 };
643
644 static int ast_fsread_audio(const void *data);
645
646 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
647 {
648         int whennext = 0;
649
650         while (!whennext) {
651                 struct ast_frame *fr;
652                 
653                 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name))
654                         goto return_failure;
655                 
656                 fr = s->fmt->read(s, &whennext);
657                 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
658                         if (fr)
659                                 ast_log(LOG_WARNING, "Failed to write frame\n");
660                         goto return_failure;
661                 }
662         }
663         if (whennext != s->lasttimeout) {
664                 if (s->owner->timingfd > -1) {
665                         float samp_rate = (float) ast_format_rate(s->fmt->format);
666                         unsigned int rate;
667
668                         rate = (unsigned int) roundf(samp_rate / ((float) whennext));
669
670                         ast_settimeout(s->owner, rate, ast_fsread_audio, s);
671                 } else {
672                         s->owner->streamid = ast_sched_add(s->owner->sched, 
673                                 whennext / (ast_format_rate(s->fmt->format) / 1000), ast_fsread_audio, s);
674                 }
675                 s->lasttimeout = whennext;
676                 return FSREAD_SUCCESS_NOSCHED;
677         }
678         return FSREAD_SUCCESS_SCHED;
679
680 return_failure:
681         s->owner->streamid = -1;
682         ast_settimeout(s->owner, 0, NULL, NULL);
683         return FSREAD_FAILURE;
684 }
685
686 static int ast_fsread_audio(const void *data)
687 {
688         struct ast_filestream *fs = (struct ast_filestream *)data;
689         enum fsread_res res;
690
691         res = ast_readaudio_callback(fs);
692
693         if (res == FSREAD_SUCCESS_SCHED)
694                 return 1;
695         
696         return 0;
697 }
698
699 static int ast_fsread_video(const void *data);
700
701 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
702 {
703         int whennext = 0;
704
705         while (!whennext) {
706                 struct ast_frame *fr = s->fmt->read(s, &whennext);
707                 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
708                         if (fr)
709                                 ast_log(LOG_WARNING, "Failed to write frame\n");
710                         s->owner->vstreamid = -1;
711                         return FSREAD_FAILURE;
712                 }
713         }
714
715         if (whennext != s->lasttimeout) {
716                 s->owner->vstreamid = ast_sched_add(s->owner->sched, 
717                         whennext / (ast_format_rate(s->fmt->format) / 1000), 
718                         ast_fsread_video, s);
719                 s->lasttimeout = whennext;
720                 return FSREAD_SUCCESS_NOSCHED;
721         }
722
723         return FSREAD_SUCCESS_SCHED;
724 }
725
726 static int ast_fsread_video(const void *data)
727 {
728         struct ast_filestream *fs = (struct ast_filestream *)data;
729         enum fsread_res res;
730
731         res = ast_readvideo_callback(fs);
732
733         if (res == FSREAD_SUCCESS_SCHED)
734                 return 1;
735         
736         return 0;
737 }
738
739 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
740 {
741         s->owner = chan;
742         return 0;
743 }
744
745 int ast_playstream(struct ast_filestream *s)
746 {
747         enum fsread_res res;
748
749         if (s->fmt->format & AST_FORMAT_AUDIO_MASK)
750                 res = ast_readaudio_callback(s);
751         else
752                 res = ast_readvideo_callback(s);
753
754         return (res == FSREAD_FAILURE) ? -1 : 0;
755 }
756
757 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
758 {
759         return fs->fmt->seek(fs, sample_offset, whence);
760 }
761
762 int ast_truncstream(struct ast_filestream *fs)
763 {
764         return fs->fmt->trunc(fs);
765 }
766
767 off_t ast_tellstream(struct ast_filestream *fs)
768 {
769         return fs->fmt->tell(fs);
770 }
771
772 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
773 {
774         return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
775 }
776
777 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
778 {
779         return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
780 }
781
782 int ast_closestream(struct ast_filestream *f)
783 {
784         char *cmd = NULL;
785         size_t size = 0;
786         /* Stop a running stream if there is one */
787         if (f->owner) {
788                 if (f->fmt->format & AST_FORMAT_AUDIO_MASK) {
789                         f->owner->stream = NULL;
790                         AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
791                         ast_settimeout(f->owner, 0, NULL, NULL);
792                 } else {
793                         f->owner->vstream = NULL;
794                         AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
795                 }
796         }
797         /* destroy the translator on exit */
798         if (f->trans)
799                 ast_translator_free_path(f->trans);
800
801         if (f->realfilename && f->filename) {
802                         size = strlen(f->filename) + strlen(f->realfilename) + 15;
803                         cmd = alloca(size);
804                         memset(cmd, 0, size);
805                         snprintf(cmd, size, "/bin/mv -f %s %s", f->filename, f->realfilename);
806                         ast_safe_system(cmd);
807         }
808
809         if (f->fmt->close) {
810                 f->fmt->close(f);
811         }
812         if (f->filename)
813                 ast_free(f->filename);
814         if (f->realfilename)
815                 ast_free(f->realfilename);
816         fclose(f->f);
817         if (f->vfs)
818                 ast_closestream(f->vfs);
819         if (f->orig_chan_name)
820                 free((void *) f->orig_chan_name);
821         if (f->write_buffer) {
822                 ast_free(f->write_buffer);
823         }
824
825         ast_module_unref(f->fmt->module);
826         ast_free(f);
827         return 0;
828 }
829
830
831 /*
832  * Look the various language-specific places where a file could exist.
833  */
834 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
835 {
836         char *buf;
837         int buflen;
838
839         if (preflang == NULL)
840                 preflang = "";
841         buflen = strlen(preflang) + strlen(filename) + 4;       /* room for everything */
842         buf = alloca(buflen);
843         if (buf == NULL)
844                 return 0;
845         return fileexists_core(filename, fmt, preflang, buf, buflen);
846 }
847
848 int ast_filedelete(const char *filename, const char *fmt)
849 {
850         return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
851 }
852
853 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
854 {
855         return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
856 }
857
858 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
859 {
860         return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
861 }
862
863 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
864 {
865         struct ast_filestream *fs;
866         struct ast_filestream *vfs=NULL;
867         char fmt[256];
868
869         fs = ast_openstream(chan, filename, preflang);
870         if (fs)
871                 vfs = ast_openvstream(chan, filename, preflang);
872         if (vfs) {
873                 ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
874         }
875         if (fs){
876                 int res;
877                 if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
878                         fs->orig_chan_name = ast_strdup(chan->name);
879                 if (ast_applystream(chan, fs))
880                         return -1;
881                 if (vfs && ast_applystream(chan, vfs))
882                         return -1;
883                 res = ast_playstream(fs);
884                 if (!res && vfs)
885                         res = ast_playstream(vfs);
886                 ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", chan->name, filename, ast_getformatname(chan->writeformat), preflang ? preflang : "default");
887
888                 return res;
889         }
890         ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
891         return -1;
892 }
893
894 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
895 {
896         FILE *bfile;
897         struct ast_format *f;
898         struct ast_filestream *fs = NULL;
899         char *fn;
900         int format_found = 0;   
901
902         AST_RWLIST_RDLOCK(&formats);
903
904         AST_RWLIST_TRAVERSE(&formats, f, list) {
905                 fs = NULL;
906                 if (!exts_compare(f->exts, type))
907                         continue;
908                 else 
909                         format_found = 1;
910
911                 fn = build_filename(filename, type);
912                 errno = 0;
913                 bfile = fopen(fn, "r");
914
915                 if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
916                         ast_log(LOG_WARNING, "Unable to open %s\n", fn);
917                         if (fs)
918                                 ast_free(fs);
919                         if (bfile)
920                                 fclose(bfile);
921                         ast_free(fn);
922                         break;                          
923                 }
924                 /* found it */
925                 fs->trans = NULL;
926                 fs->fmt = f;
927                 fs->flags = flags;
928                 fs->mode = mode;
929                 fs->filename = ast_strdup(filename);
930                 fs->vfs = NULL;
931                 break;
932         }
933
934         AST_RWLIST_UNLOCK(&formats);
935         if (!format_found)
936                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
937
938         return fs;
939 }
940
941 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
942 {
943         int fd, myflags = 0;
944         /* compiler claims this variable can be used before initialization... */
945         FILE *bfile = NULL;
946         struct ast_format *f;
947         struct ast_filestream *fs = NULL;
948         char *buf = NULL;
949         size_t size = 0;
950         int format_found = 0;
951
952         AST_RWLIST_RDLOCK(&formats);
953
954         /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
955         /* We really can't use O_APPEND as it will break WAV header updates */
956         if (flags & O_APPEND) { 
957                 flags &= ~O_APPEND;
958         } else {
959                 myflags = O_TRUNC;
960         }
961         
962         myflags |= O_WRONLY | O_CREAT;
963
964         /* XXX need to fix this - we should just do the fopen,
965          * not open followed by fdopen()
966          */
967         AST_RWLIST_TRAVERSE(&formats, f, list) {
968                 char *fn, *orig_fn = NULL;
969                 if (fs)
970                         break;
971
972                 if (!exts_compare(f->exts, type))
973                         continue;
974                 else
975                         format_found = 1;
976
977                 fn = build_filename(filename, type);
978                 fd = open(fn, flags | myflags, mode);
979                 if (fd > -1) {
980                         /* fdopen() the resulting file stream */
981                         bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
982                         if (!bfile) {
983                                 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
984                                 close(fd);
985                                 fd = -1;
986                         }
987                 }
988                 
989                 if (ast_opt_cache_record_files && (fd > -1)) {
990                         char *c;
991
992                         fclose(bfile);  /* this also closes fd */
993                         /*
994                           We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
995                           What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
996                         */
997                         orig_fn = ast_strdupa(fn);
998                         for (c = fn; *c; c++)
999                                 if (*c == '/')
1000                                         *c = '_';
1001
1002                         size = strlen(fn) + strlen(record_cache_dir) + 2;
1003                         buf = alloca(size);
1004                         strcpy(buf, record_cache_dir);
1005                         strcat(buf, "/");
1006                         strcat(buf, fn);
1007                         ast_free(fn);
1008                         fn = buf;
1009                         fd = open(fn, flags | myflags, mode);
1010                         if (fd > -1) {
1011                                 /* fdopen() the resulting file stream */
1012                                 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1013                                 if (!bfile) {
1014                                         ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1015                                         close(fd);
1016                                         fd = -1;
1017                                 }
1018                         }
1019                 }
1020                 if (fd > -1) {
1021                         errno = 0;
1022                         fs = get_filestream(f, bfile);
1023                         if (!fs || rewrite_wrapper(fs, comment)) {
1024                                 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1025                                 close(fd);
1026                                 if (orig_fn) {
1027                                         unlink(fn);
1028                                         unlink(orig_fn);
1029                                 }
1030                                 if (fs)
1031                                         ast_free(fs);
1032                                 fs = NULL;
1033                                 continue;
1034                         }
1035                         fs->trans = NULL;
1036                         fs->fmt = f;
1037                         fs->flags = flags;
1038                         fs->mode = mode;
1039                         if (orig_fn) {
1040                                 fs->realfilename = ast_strdup(orig_fn);
1041                                 fs->filename = ast_strdup(fn);
1042                         } else {
1043                                 fs->realfilename = NULL;
1044                                 fs->filename = ast_strdup(filename);
1045                         }
1046                         fs->vfs = NULL;
1047                         /* If truncated, we'll be at the beginning; if not truncated, then append */
1048
1049                         if ((fs->write_buffer = ast_malloc(32768))){
1050                                 setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
1051                         }
1052
1053                         f->seek(fs, 0, SEEK_END);
1054                 } else if (errno != EEXIST) {
1055                         ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1056                         if (orig_fn)
1057                                 unlink(orig_fn);
1058                 }
1059                 /* if buf != NULL then fn is already free and pointing to it */
1060                 if (!buf)
1061                         ast_free(fn);
1062         }
1063
1064         AST_RWLIST_UNLOCK(&formats);
1065
1066         if (!format_found)
1067                 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1068
1069         return fs;
1070 }
1071
1072 /*!
1073  * \brief the core of all waitstream() functions
1074  */
1075 static int waitstream_core(struct ast_channel *c, const char *breakon,
1076         const char *forward, const char *reverse, int skip_ms,
1077         int audiofd, int cmdfd,  const char *context)
1078 {
1079         const char *orig_chan_name = NULL;
1080         int err = 0;
1081
1082         if (!breakon)
1083                 breakon = "";
1084         if (!forward)
1085                 forward = "";
1086         if (!reverse)
1087                 reverse = "";
1088
1089         /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1090         ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1091
1092         if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1093                 orig_chan_name = ast_strdupa(c->name);
1094
1095         while (c->stream) {
1096                 int res;
1097                 int ms;
1098
1099                 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1100                         ast_stopstream(c);
1101                         err = 1;
1102                         break;
1103                 }
1104
1105                 ms = ast_sched_wait(c->sched);
1106
1107                 if (ms < 0 && !c->timingfunc) {
1108                         ast_stopstream(c);
1109                         break;
1110                 }
1111                 if (ms < 0)
1112                         ms = 1000;
1113                 if (cmdfd < 0) {
1114                         res = ast_waitfor(c, ms);
1115                         if (res < 0) {
1116                                 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1117                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1118                                 return res;
1119                         }
1120                 } else {
1121                         int outfd;
1122                         struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1123                         if (!rchan && (outfd < 0) && (ms)) {
1124                                 /* Continue */
1125                                 if (errno == EINTR)
1126                                         continue;
1127                                 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1128                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1129                                 return -1;
1130                         } else if (outfd > -1) { /* this requires cmdfd set */
1131                                 /* The FD we were watching has something waiting */
1132                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1133                                 return 1;
1134                         }
1135                         /* if rchan is set, it is 'c' */
1136                         res = rchan ? 1 : 0; /* map into 'res' values */
1137                 }
1138                 if (res > 0) {
1139                         struct ast_frame *fr = ast_read(c);
1140                         if (!fr) {
1141                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1142                                 return -1;
1143                         }
1144                         switch (fr->frametype) {
1145                         case AST_FRAME_DTMF_END:
1146                                 if (context) {
1147                                         const char exten[2] = { fr->subclass, '\0' };
1148                                         if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1149                                                 res = fr->subclass;
1150                                                 ast_frfree(fr);
1151                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1152                                                 return res;
1153                                         }
1154                                 } else {
1155                                         res = fr->subclass;
1156                                         if (strchr(forward, res)) {
1157                                                 ast_stream_fastforward(c->stream, skip_ms);
1158                                         } else if (strchr(reverse, res)) {
1159                                                 ast_stream_rewind(c->stream, skip_ms);
1160                                         } else if (strchr(breakon, res)) {
1161                                                 ast_frfree(fr);
1162                                                 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1163                                                 return res;
1164                                         }                                       
1165                                 }
1166                                 break;
1167                         case AST_FRAME_CONTROL:
1168                                 switch (fr->subclass) {
1169                                 case AST_CONTROL_HANGUP:
1170                                 case AST_CONTROL_BUSY:
1171                                 case AST_CONTROL_CONGESTION:
1172                                         ast_frfree(fr);
1173                                         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1174                                         return -1;
1175                                 case AST_CONTROL_RINGING:
1176                                 case AST_CONTROL_ANSWER:
1177                                 case AST_CONTROL_VIDUPDATE:
1178                                 case AST_CONTROL_SRCUPDATE:
1179                                 case AST_CONTROL_HOLD:
1180                                 case AST_CONTROL_UNHOLD:
1181                                         /* Unimportant */
1182                                         break;
1183                                 default:
1184                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1185                                 }
1186                                 break;
1187                         case AST_FRAME_VOICE:
1188                                 /* Write audio if appropriate */
1189                                 if (audiofd > -1)
1190                                         write(audiofd, fr->data.ptr, fr->datalen);
1191                         default:
1192                                 /* Ignore all others */
1193                                 break;
1194                         }
1195                         ast_frfree(fr);
1196                 }
1197                 ast_sched_runq(c->sched);
1198         }
1199
1200         ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1201
1202         return (err || c->_softhangup) ? -1 : 0;
1203 }
1204
1205 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
1206 {
1207         return waitstream_core(c, breakon, forward, reverse, ms,
1208                 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1209 }
1210
1211 int ast_waitstream(struct ast_channel *c, const char *breakon)
1212 {
1213         return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1214 }
1215
1216 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1217 {
1218         return waitstream_core(c, breakon, NULL, NULL, 0,
1219                 audiofd, cmdfd, NULL /* no context */);
1220 }
1221
1222 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1223 {
1224         /* Waitstream, with return in the case of a valid 1 digit extension */
1225         /* in the current or specified context being pressed */
1226
1227         if (!context)
1228                 context = c->context;
1229         return waitstream_core(c, NULL, NULL, NULL, 0,
1230                 -1, -1, context);
1231 }
1232
1233 /*
1234  * if the file name is non-empty, try to play it.
1235  * Return 0 if success, -1 if error, digit if interrupted by a digit.
1236  * If digits == "" then we can simply check for non-zero.
1237  */
1238 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
1239 {
1240         int res = 0;
1241         if (!ast_strlen_zero(file)) {
1242                 res = ast_streamfile(chan, file, chan->language);
1243                 if (!res) {
1244                         res = ast_waitstream(chan, digits);
1245                 }
1246         }
1247         return res;
1248
1249
1250 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1251 {
1252 #define FORMAT "%-10s %-10s %-20s\n"
1253 #define FORMAT2 "%-10s %-10s %-20s\n"
1254         struct ast_format *f;
1255         int count_fmt = 0;
1256
1257         switch (cmd) {
1258         case CLI_INIT:
1259                 e->command = "core show file formats";
1260                 e->usage =
1261                         "Usage: core show file formats\n"
1262                         "       Displays currently registered file formats (if any).\n";
1263                 return NULL;
1264         case CLI_GENERATE:
1265                 return NULL;
1266         }
1267
1268         if (a->argc != 4)
1269                 return CLI_SHOWUSAGE;
1270
1271         ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
1272         ast_cli(a->fd, FORMAT, "------", "----", "----------");
1273
1274         AST_RWLIST_RDLOCK(&formats);
1275         AST_RWLIST_TRAVERSE(&formats, f, list) {
1276                 ast_cli(a->fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1277                 count_fmt++;
1278         }
1279         AST_RWLIST_UNLOCK(&formats);
1280         ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
1281         return CLI_SUCCESS;
1282 #undef FORMAT
1283 #undef FORMAT2
1284 }
1285
1286 struct ast_cli_entry cli_file[] = {
1287         AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
1288 };
1289
1290 int ast_file_init(void)
1291 {
1292         ast_cli_register_multiple(cli_file, sizeof(cli_file) / sizeof(struct ast_cli_entry));
1293         return 0;
1294 }