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