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