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