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