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