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