Merged revisions 111125 via svnmerge from
[asterisk-bristuff.git] / main / file.c
blob842c4a69885a65b744c16dba60ca9a0ec22b12fe
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Generic File Format Support.
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <sys/types.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
41 #include "asterisk/frame.h"
42 #include "asterisk/file.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/logger.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/sched.h"
47 #include "asterisk/options.h"
48 #include "asterisk/translate.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/app.h"
52 #include "asterisk/pbx.h"
53 #include "asterisk/linkedlists.h"
54 #include "asterisk/module.h"
57 * The following variable controls the layout of localized sound files.
58 * If 0, use the historical layout with prefix just before the filename
59 * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
60 * if 1 put the prefix at the beginning of the filename
61 * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
62 * The latter permits a language to be entirely in one directory.
64 int ast_language_is_prefix;
66 static AST_LIST_HEAD_STATIC(formats, ast_format);
68 int __ast_format_register(const struct ast_format *f, struct ast_module *mod)
70 struct ast_format *tmp;
72 if (AST_LIST_LOCK(&formats)) {
73 ast_log(LOG_WARNING, "Unable to lock format list\n");
74 return -1;
76 AST_LIST_TRAVERSE(&formats, tmp, list) {
77 if (!strcasecmp(f->name, tmp->name)) {
78 AST_LIST_UNLOCK(&formats);
79 ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
80 return -1;
83 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
84 AST_LIST_UNLOCK(&formats);
85 return -1;
87 *tmp = *f;
88 tmp->module = mod;
89 if (tmp->buf_size) {
91 * Align buf_size properly, rounding up to the machine-specific
92 * alignment for pointers.
94 struct _test_align { void *a, *b; } p;
95 int align = (char *)&p.b - (char *)&p.a;
96 tmp->buf_size = ((f->buf_size + align - 1)/align)*align;
99 memset(&tmp->list, 0, sizeof(tmp->list));
101 AST_LIST_INSERT_HEAD(&formats, tmp, list);
102 AST_LIST_UNLOCK(&formats);
103 if (option_verbose > 1)
104 ast_verbose( VERBOSE_PREFIX_2 "Registered file format %s, extension(s) %s\n", f->name, f->exts);
106 return 0;
109 int ast_format_unregister(const char *name)
111 struct ast_format *tmp;
112 int res = -1;
114 if (AST_LIST_LOCK(&formats)) {
115 ast_log(LOG_WARNING, "Unable to lock format list\n");
116 return -1;
118 AST_LIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
119 if (!strcasecmp(name, tmp->name)) {
120 AST_LIST_REMOVE_CURRENT(&formats, list);
121 free(tmp);
122 res = 0;
125 AST_LIST_TRAVERSE_SAFE_END
126 AST_LIST_UNLOCK(&formats);
128 if (!res) {
129 if (option_verbose > 1)
130 ast_verbose( VERBOSE_PREFIX_2 "Unregistered format %s\n", name);
131 } else
132 ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
134 return res;
137 int ast_stopstream(struct ast_channel *tmp)
139 ast_channel_lock(tmp);
141 /* Stop a running stream if there is one */
142 if (tmp->stream) {
143 ast_closestream(tmp->stream);
144 tmp->stream = NULL;
145 if (tmp->oldwriteformat && ast_set_write_format(tmp, tmp->oldwriteformat))
146 ast_log(LOG_WARNING, "Unable to restore format back to %d\n", tmp->oldwriteformat);
148 /* Stop the video stream too */
149 if (tmp->vstream != NULL) {
150 ast_closestream(tmp->vstream);
151 tmp->vstream = NULL;
154 ast_channel_unlock(tmp);
156 return 0;
159 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
161 int res = -1;
162 int alt = 0;
163 if (f->frametype == AST_FRAME_VIDEO) {
164 if (fs->fmt->format < AST_FORMAT_MAX_AUDIO) {
165 /* This is the audio portion. Call the video one... */
166 if (!fs->vfs && fs->filename) {
167 const char *type = ast_getformatname(f->subclass & ~0x1);
168 fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
169 ast_log(LOG_DEBUG, "Opened video output file\n");
171 if (fs->vfs)
172 return ast_writestream(fs->vfs, f);
173 /* else ignore */
174 return 0;
175 } else {
176 /* Might / might not have mark set */
177 alt = 1;
179 } else if (f->frametype != AST_FRAME_VOICE) {
180 ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
181 return -1;
183 if (((fs->fmt->format | alt) & f->subclass) == f->subclass) {
184 res = fs->fmt->write(fs, f);
185 if (res < 0)
186 ast_log(LOG_WARNING, "Natural write failed\n");
187 else if (res > 0)
188 ast_log(LOG_WARNING, "Huh??\n");
189 } else {
190 /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
191 the one we've setup a translator for, we do the "wrong thing" XXX */
192 if (fs->trans && f->subclass != fs->lastwriteformat) {
193 ast_translator_free_path(fs->trans);
194 fs->trans = NULL;
196 if (!fs->trans)
197 fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass);
198 if (!fs->trans)
199 ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
200 fs->fmt->name, ast_getformatname(f->subclass));
201 else {
202 struct ast_frame *trf;
203 fs->lastwriteformat = f->subclass;
204 /* Get the translated frame but don't consume the original in case they're using it on another stream */
205 trf = ast_translate(fs->trans, f, 0);
206 if (trf) {
207 res = fs->fmt->write(fs, trf);
208 ast_frfree(trf);
209 if (res)
210 ast_log(LOG_WARNING, "Translated frame write failed\n");
211 } else
212 res = 0;
215 return res;
218 static int copy(const char *infile, const char *outfile)
220 int ifd, ofd, len;
221 char buf[4096]; /* XXX make it lerger. */
223 if ((ifd = open(infile, O_RDONLY)) < 0) {
224 ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
225 return -1;
227 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) {
228 ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
229 close(ifd);
230 return -1;
232 while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
233 int res;
234 if (len < 0) {
235 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
236 break;
238 /* XXX handle partial writes */
239 res = write(ofd, buf, len);
240 if (res != len) {
241 ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
242 len = -1; /* error marker */
243 break;
246 close(ifd);
247 close(ofd);
248 if (len < 0) {
249 unlink(outfile);
250 return -1; /* error */
252 return 0; /* success */
256 * \brief construct a filename. Absolute pathnames are preserved,
257 * relative names are prefixed by the sounds/ directory.
258 * The wav49 suffix is replaced by 'WAV'.
259 * Returns a malloc'ed string to be freed by the caller.
261 static char *build_filename(const char *filename, const char *ext)
263 char *fn = NULL;
265 if (!strcmp(ext, "wav49"))
266 ext = "WAV";
268 if (filename[0] == '/')
269 asprintf(&fn, "%s.%s", filename, ext);
270 else
271 asprintf(&fn, "%s/sounds/%s.%s",
272 ast_config_AST_DATA_DIR, filename, ext);
273 return fn;
276 /* compare type against the list 'exts' */
277 /* XXX need a better algorithm */
278 static int exts_compare(const char *exts, const char *type)
280 char tmp[256];
281 char *stringp = tmp, *ext;
283 ast_copy_string(tmp, exts, sizeof(tmp));
284 while ((ext = strsep(&stringp, "|"))) {
285 if (!strcmp(ext, type))
286 return 1;
289 return 0;
292 static struct ast_filestream *get_filestream(struct ast_format *fmt, FILE *bfile)
294 struct ast_filestream *s;
296 int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
297 if ( (s = ast_calloc(1, l)) == NULL)
298 return NULL;
299 s->fmt = fmt;
300 s->f = bfile;
302 if (fmt->desc_size)
303 s->_private = ((char *)(s+1)) + fmt->buf_size;
304 if (fmt->buf_size)
305 s->buf = (char *)(s+1);
306 s->fr.src = fmt->name;
307 return s;
311 * Default implementations of open and rewrite.
312 * Only use them if you don't have expensive stuff to do.
314 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
316 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
318 struct ast_format *f = s->fmt;
319 int ret = -1;
321 if (mode == WRAP_OPEN && f->open && f->open(s))
322 ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
323 else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
324 ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
325 else {
326 /* preliminary checks succeed. update usecount */
327 ast_module_ref(f->module);
328 ret = 0;
330 return ret;
333 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
335 return fn_wrapper(s, comment, WRAP_REWRITE);
338 static int open_wrapper(struct ast_filestream *s)
340 return fn_wrapper(s, NULL, WRAP_OPEN);
343 enum file_action {
344 ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
345 ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
346 ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
347 ACTION_OPEN,
348 ACTION_COPY /* copy file. return 0 on success, -1 on error */
352 * \brief perform various actions on a file. Second argument
353 * arg2 depends on the command:
354 * unused for EXISTS and DELETE
355 * destination file name (const char *) for COPY and RENAME
356 * struct ast_channel * for OPEN
357 * if fmt is NULL, OPEN will return the first matching entry,
358 * whereas other functions will run on all matching entries.
360 static int ast_filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
362 struct ast_format *f;
363 int res = (action == ACTION_EXISTS) ? 0 : -1;
365 if (AST_LIST_LOCK(&formats)) {
366 ast_log(LOG_WARNING, "Unable to lock format list\n");
367 return res;
369 /* Check for a specific format */
370 AST_LIST_TRAVERSE(&formats, f, list) {
371 char *stringp, *ext = NULL;
373 if (fmt && !exts_compare(f->exts, fmt))
374 continue;
376 /* Look for a file matching the supported extensions.
377 * The file must exist, and for OPEN, must match
378 * one of the formats supported by the channel.
380 stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
381 while ( (ext = strsep(&stringp, "|")) ) {
382 struct stat st;
383 char *fn = build_filename(filename, ext);
385 if (fn == NULL)
386 continue;
388 if ( stat(fn, &st) ) { /* file not existent */
389 free(fn);
390 continue;
392 /* for 'OPEN' we need to be sure that the format matches
393 * what the channel can process
395 if (action == ACTION_OPEN) {
396 struct ast_channel *chan = (struct ast_channel *)arg2;
397 FILE *bfile;
398 struct ast_filestream *s;
400 if ( !(chan->writeformat & f->format) &&
401 !(f->format >= AST_FORMAT_MAX_AUDIO && fmt)) {
402 free(fn);
403 continue; /* not a supported format */
405 if ( (bfile = fopen(fn, "r")) == NULL) {
406 free(fn);
407 continue; /* cannot open file */
409 s = get_filestream(f, bfile);
410 if (!s) {
411 fclose(bfile);
412 free(fn); /* cannot allocate descriptor */
413 continue;
415 if (open_wrapper(s)) {
416 fclose(bfile);
417 free(fn);
418 free(s);
419 continue; /* cannot run open on file */
421 /* ok this is good for OPEN */
422 res = 1; /* found */
423 s->lasttimeout = -1;
424 s->fmt = f;
425 s->trans = NULL;
426 s->filename = NULL;
427 if (s->fmt->format < AST_FORMAT_MAX_AUDIO) {
428 if (chan->stream)
429 ast_closestream(chan->stream);
430 chan->stream = s;
431 } else {
432 if (chan->vstream)
433 ast_closestream(chan->vstream);
434 chan->vstream = s;
436 free(fn);
437 break;
439 switch (action) {
440 case ACTION_OPEN:
441 break; /* will never get here */
443 case ACTION_EXISTS: /* return the matching format */
444 res |= f->format;
445 break;
447 case ACTION_DELETE:
448 if ( (res = unlink(fn)) )
449 ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
450 break;
452 case ACTION_RENAME:
453 case ACTION_COPY: {
454 char *nfn = build_filename((const char *)arg2, ext);
455 if (!nfn)
456 ast_log(LOG_WARNING, "Out of memory\n");
457 else {
458 res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
459 if (res)
460 ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
461 action == ACTION_COPY ? "copy" : "rename",
462 fn, nfn, strerror(errno));
463 free(nfn);
466 break;
468 default:
469 ast_log(LOG_WARNING, "Unknown helper %d\n", action);
471 free(fn);
474 AST_LIST_UNLOCK(&formats);
475 return res;
478 static int is_absolute_path(const char *filename)
480 return filename[0] == '/';
483 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
484 char *buf, int buflen)
486 if (buf == NULL) {
487 return -1;
490 if (ast_language_is_prefix) { /* new layout */
491 if (lang) {
492 snprintf(buf, buflen, "%s/%s", lang, filename);
493 } else {
494 snprintf(buf, buflen, "%s", filename);
496 } else { /* old layout */
497 strcpy(buf, filename); /* first copy the full string */
498 if (lang) {
499 /* insert the language and suffix if needed */
500 const char *c = strrchr(filename, '/');
501 int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
502 snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
506 return ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
510 * \brief helper routine to locate a file with a given format
511 * and language preference.
512 * Try preflang, preflang with stripped '_' suffix, or NULL.
513 * In the standard asterisk, language goes just before the last component.
514 * In an alternative configuration, the language should be a prefix
515 * to the actual filename.
517 * The last parameter(s) point to a buffer of sufficient size,
518 * which on success is filled with the matching filename.
520 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
521 char *buf, int buflen)
523 int res = -1;
524 char *lang = NULL;
526 if (buf == NULL) {
527 return -1;
530 if (is_absolute_path(filename)) {
531 ast_copy_string(buf, filename, buflen);
532 return ast_filehelper(buf, NULL, fmt, ACTION_EXISTS);
535 /* We try languages in the following order:
536 * preflang (may include dialect)
537 * lang (preflang without dialect - if any)
538 * <none>
539 * default (unless the same as preflang or lang without dialect)
542 /* Try preferred language */
543 if (!ast_strlen_zero(preflang)) {
544 /* try the preflang exactly as it was requested */
545 if ((res = fileexists_test(filename, fmt, preflang, buf, buflen)) > 0) {
546 return res;
547 } else {
548 /* try without a dialect */
549 char *postfix = NULL;
550 postfix = lang = ast_strdupa(preflang);
552 strsep(&postfix, "_");
553 if (postfix) {
554 if ((res = fileexists_test(filename, fmt, lang, buf, buflen)) > 0) {
555 return res;
561 /* Try without any language */
562 if ((res = fileexists_test(filename, fmt, NULL, buf, buflen)) > 0) {
563 return res;
566 /* Finally try the default language unless it was already tried before */
567 if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
568 if ((res = fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen)) > 0) {
569 return res;
573 return 0;
576 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
578 return ast_openstream_full(chan, filename, preflang, 0);
581 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
584 * Use fileexists_core() to find a file in a compatible
585 * language and format, set up a suitable translator,
586 * and open the stream.
588 int fmts, res, buflen;
589 char *buf;
591 if (!asis) {
592 /* do this first, otherwise we detect the wrong writeformat */
593 ast_stopstream(chan);
594 if (chan->generator)
595 ast_deactivate_generator(chan);
597 if (preflang == NULL)
598 preflang = "";
599 buflen = strlen(preflang) + strlen(filename) + 4;
600 buf = alloca(buflen);
601 if (buf == NULL)
602 return NULL;
603 fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
604 if (fmts > 0)
605 fmts &= AST_FORMAT_AUDIO_MASK;
606 if (fmts < 1) {
607 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
608 return NULL;
610 chan->oldwriteformat = chan->writeformat;
611 /* Set the channel to a format we can work with */
612 res = ast_set_write_format(chan, fmts);
613 res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
614 if (res >= 0)
615 return chan->stream;
616 return NULL;
619 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
621 /* As above, but for video. But here we don't have translators
622 * so we must enforce a format.
624 unsigned int format;
625 char *buf;
626 int buflen;
628 if (preflang == NULL)
629 preflang = "";
630 buflen = strlen(preflang) + strlen(filename) + 4;
631 buf = alloca(buflen);
632 if (buf == NULL)
633 return NULL;
635 for (format = AST_FORMAT_MAX_AUDIO << 1; format <= AST_FORMAT_MAX_VIDEO; format = format << 1) {
636 int fd;
637 const char *fmt;
639 if (!(chan->nativeformats & format))
640 continue;
641 fmt = ast_getformatname(format);
642 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
643 continue;
644 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
645 if (fd >= 0)
646 return chan->vstream;
647 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
649 return NULL;
652 struct ast_frame *ast_readframe(struct ast_filestream *s)
654 struct ast_frame *f = NULL;
655 int whennext = 0;
656 if (s && s->fmt)
657 f = s->fmt->read(s, &whennext);
658 return f;
661 enum fsread_res {
662 FSREAD_FAILURE,
663 FSREAD_SUCCESS_SCHED,
664 FSREAD_SUCCESS_NOSCHED,
667 static int ast_fsread_audio(const void *data);
669 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
671 int whennext = 0;
673 while (!whennext) {
674 struct ast_frame *fr;
676 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name))
677 goto return_failure;
679 fr = s->fmt->read(s, &whennext);
680 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
681 if (fr)
682 ast_log(LOG_WARNING, "Failed to write frame\n");
683 goto return_failure;
686 if (whennext != s->lasttimeout) {
687 #ifdef HAVE_ZAPTEL
688 if (s->owner->timingfd > -1)
689 ast_settimeout(s->owner, whennext, ast_fsread_audio, s);
690 else
691 #endif
692 s->owner->streamid = ast_sched_add(s->owner->sched, whennext/8, ast_fsread_audio, s);
693 s->lasttimeout = whennext;
694 return FSREAD_SUCCESS_NOSCHED;
696 return FSREAD_SUCCESS_SCHED;
698 return_failure:
699 s->owner->streamid = -1;
700 #ifdef HAVE_ZAPTEL
701 ast_settimeout(s->owner, 0, NULL, NULL);
702 #endif
703 return FSREAD_FAILURE;
706 static int ast_fsread_audio(const void *data)
708 struct ast_filestream *fs = (struct ast_filestream *)data;
709 enum fsread_res res;
711 res = ast_readaudio_callback(fs);
713 if (res == FSREAD_SUCCESS_SCHED)
714 return 1;
716 return 0;
719 static int ast_fsread_video(const void *data);
721 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
723 int whennext = 0;
725 while (!whennext) {
726 struct ast_frame *fr = s->fmt->read(s, &whennext);
727 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
728 if (fr)
729 ast_log(LOG_WARNING, "Failed to write frame\n");
730 s->owner->vstreamid = -1;
731 return FSREAD_FAILURE;
735 if (whennext != s->lasttimeout) {
736 s->owner->vstreamid = ast_sched_add(s->owner->sched, whennext / 8,
737 ast_fsread_video, s);
738 s->lasttimeout = whennext;
739 return FSREAD_SUCCESS_NOSCHED;
742 return FSREAD_SUCCESS_SCHED;
745 static int ast_fsread_video(const void *data)
747 struct ast_filestream *fs = (struct ast_filestream *)data;
748 enum fsread_res res;
750 res = ast_readvideo_callback(fs);
752 if (res == FSREAD_SUCCESS_SCHED)
753 return 1;
755 return 0;
758 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
760 s->owner = chan;
761 return 0;
764 int ast_playstream(struct ast_filestream *s)
766 enum fsread_res res;
768 if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
769 res = ast_readaudio_callback(s);
770 else
771 res = ast_readvideo_callback(s);
773 return (res == FSREAD_FAILURE) ? -1 : 0;
776 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
778 return fs->fmt->seek(fs, sample_offset, whence);
781 int ast_truncstream(struct ast_filestream *fs)
783 return fs->fmt->trunc(fs);
786 off_t ast_tellstream(struct ast_filestream *fs)
788 return fs->fmt->tell(fs);
791 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
793 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
796 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
798 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
801 int ast_closestream(struct ast_filestream *f)
803 char *cmd = NULL;
804 size_t size = 0;
805 /* Stop a running stream if there is one */
806 if (f->owner) {
807 if (f->fmt->format < AST_FORMAT_MAX_AUDIO) {
808 f->owner->stream = NULL;
809 AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
810 #ifdef HAVE_ZAPTEL
811 ast_settimeout(f->owner, 0, NULL, NULL);
812 #endif
813 } else {
814 f->owner->vstream = NULL;
815 AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
818 /* destroy the translator on exit */
819 if (f->trans)
820 ast_translator_free_path(f->trans);
822 if (f->realfilename && f->filename) {
823 size = strlen(f->filename) + strlen(f->realfilename) + 15;
824 cmd = alloca(size);
825 memset(cmd,0,size);
826 snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
827 ast_safe_system(cmd);
830 if (f->filename)
831 free(f->filename);
832 if (f->realfilename)
833 free(f->realfilename);
834 if (f->fmt->close)
835 f->fmt->close(f);
836 fclose(f->f);
837 if (f->vfs)
838 ast_closestream(f->vfs);
839 if (f->orig_chan_name)
840 free((void *) f->orig_chan_name);
841 ast_module_unref(f->fmt->module);
842 free(f);
843 return 0;
848 * Look the various language-specific places where a file could exist.
850 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
852 char *buf;
853 int buflen;
855 if (preflang == NULL)
856 preflang = "";
857 buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
858 buf = alloca(buflen);
859 if (buf == NULL)
860 return 0;
861 return fileexists_core(filename, fmt, preflang, buf, buflen);
864 int ast_filedelete(const char *filename, const char *fmt)
866 return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
869 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
871 return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
874 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
876 return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
879 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
881 struct ast_filestream *fs;
882 struct ast_filestream *vfs=NULL;
883 char fmt[256];
885 fs = ast_openstream(chan, filename, preflang);
886 if (fs)
887 vfs = ast_openvstream(chan, filename, preflang);
888 if (vfs)
889 ast_log(LOG_DEBUG, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
890 if (fs){
891 int res;
892 if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
893 fs->orig_chan_name = ast_strdup(chan->name);
894 if (ast_applystream(chan, fs))
895 return -1;
896 if (vfs && ast_applystream(chan, vfs))
897 return -1;
898 res = ast_playstream(fs);
899 if (!res && vfs)
900 res = ast_playstream(vfs);
901 if (option_verbose > 2)
902 ast_verbose(VERBOSE_PREFIX_3 "<%s> Playing '%s' (language '%s')\n", chan->name, filename, preflang ? preflang : "default");
904 return res;
906 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
907 return -1;
910 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
912 FILE *bfile;
913 struct ast_format *f;
914 struct ast_filestream *fs = NULL;
915 char *fn;
917 if (AST_LIST_LOCK(&formats)) {
918 ast_log(LOG_WARNING, "Unable to lock format list\n");
919 return NULL;
922 AST_LIST_TRAVERSE(&formats, f, list) {
923 fs = NULL;
924 if (!exts_compare(f->exts, type))
925 continue;
927 fn = build_filename(filename, type);
928 errno = 0;
929 bfile = fopen(fn, "r");
930 if (!bfile || (fs = get_filestream(f, bfile)) == NULL ||
931 open_wrapper(fs) ) {
932 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
933 if (fs)
934 ast_free(fs);
935 if (bfile)
936 fclose(bfile);
937 free(fn);
938 continue;
940 /* found it */
941 fs->trans = NULL;
942 fs->fmt = f;
943 fs->flags = flags;
944 fs->mode = mode;
945 fs->filename = strdup(filename);
946 fs->vfs = NULL;
947 break;
950 AST_LIST_UNLOCK(&formats);
951 if (!fs)
952 ast_log(LOG_WARNING, "No such format '%s'\n", type);
954 return fs;
957 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
959 int fd, myflags = 0;
960 /* compiler claims this variable can be used before initialization... */
961 FILE *bfile = NULL;
962 struct ast_format *f;
963 struct ast_filestream *fs = NULL;
964 char *buf = NULL;
965 size_t size = 0;
966 int format_found = 0;
968 if (AST_LIST_LOCK(&formats)) {
969 ast_log(LOG_WARNING, "Unable to lock format list\n");
970 return NULL;
973 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
974 /* We really can't use O_APPEND as it will break WAV header updates */
975 if (flags & O_APPEND) {
976 flags &= ~O_APPEND;
977 } else {
978 myflags = O_TRUNC;
981 myflags |= O_WRONLY | O_CREAT;
983 /* XXX need to fix this - we should just do the fopen,
984 * not open followed by fdopen()
986 AST_LIST_TRAVERSE(&formats, f, list) {
987 char *fn, *orig_fn = NULL;
988 if (fs)
989 break;
991 if (!exts_compare(f->exts, type))
992 continue;
993 else
994 format_found = 1;
996 fn = build_filename(filename, type);
997 fd = open(fn, flags | myflags, mode);
998 if (fd > -1) {
999 /* fdopen() the resulting file stream */
1000 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1001 if (!bfile) {
1002 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1003 close(fd);
1004 fd = -1;
1008 if (ast_opt_cache_record_files && (fd > -1)) {
1009 char *c;
1011 fclose(bfile); /* this also closes fd */
1013 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1014 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1016 orig_fn = ast_strdupa(fn);
1017 for (c = fn; *c; c++)
1018 if (*c == '/')
1019 *c = '_';
1021 size = strlen(fn) + strlen(record_cache_dir) + 2;
1022 buf = alloca(size);
1023 strcpy(buf, record_cache_dir);
1024 strcat(buf, "/");
1025 strcat(buf, fn);
1026 free(fn);
1027 fn = buf;
1028 fd = open(fn, flags | myflags, mode);
1029 if (fd > -1) {
1030 /* fdopen() the resulting file stream */
1031 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1032 if (!bfile) {
1033 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1034 close(fd);
1035 fd = -1;
1039 if (fd > -1) {
1040 errno = 0;
1041 fs = get_filestream(f, bfile);
1042 if (!fs || rewrite_wrapper(fs, comment)) {
1043 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1044 close(fd);
1045 if (orig_fn) {
1046 unlink(fn);
1047 unlink(orig_fn);
1049 if (fs)
1050 ast_free(fs);
1051 fs = NULL;
1052 continue;
1054 fs->trans = NULL;
1055 fs->fmt = f;
1056 fs->flags = flags;
1057 fs->mode = mode;
1058 if (orig_fn) {
1059 fs->realfilename = strdup(orig_fn);
1060 fs->filename = strdup(fn);
1061 } else {
1062 fs->realfilename = NULL;
1063 fs->filename = strdup(filename);
1065 fs->vfs = NULL;
1066 /* If truncated, we'll be at the beginning; if not truncated, then append */
1067 f->seek(fs, 0, SEEK_END);
1068 } else if (errno != EEXIST) {
1069 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1070 if (orig_fn)
1071 unlink(orig_fn);
1073 /* if buf != NULL then fn is already free and pointing to it */
1074 if (!buf)
1075 free(fn);
1078 AST_LIST_UNLOCK(&formats);
1080 if (!format_found)
1081 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1083 return fs;
1087 * \brief the core of all waitstream() functions
1089 static int waitstream_core(struct ast_channel *c, const char *breakon,
1090 const char *forward, const char *rewind, int skip_ms,
1091 int audiofd, int cmdfd, const char *context)
1093 const char *orig_chan_name = NULL;
1094 int err = 0;
1096 if (!breakon)
1097 breakon = "";
1098 if (!forward)
1099 forward = "";
1100 if (!rewind)
1101 rewind = "";
1103 /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1104 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1106 if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1107 orig_chan_name = ast_strdupa(c->name);
1109 while (c->stream) {
1110 int res;
1111 int ms;
1113 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1114 ast_stopstream(c);
1115 err = 1;
1116 break;
1119 ms = ast_sched_wait(c->sched);
1121 if (ms < 0 && !c->timingfunc) {
1122 ast_stopstream(c);
1123 break;
1125 if (ms < 0)
1126 ms = 1000;
1127 if (cmdfd < 0) {
1128 res = ast_waitfor(c, ms);
1129 if (res < 0) {
1130 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1131 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1132 return res;
1134 } else {
1135 int outfd;
1136 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1137 if (!rchan && (outfd < 0) && (ms)) {
1138 /* Continue */
1139 if (errno == EINTR)
1140 continue;
1141 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1142 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1143 return -1;
1144 } else if (outfd > -1) { /* this requires cmdfd set */
1145 /* The FD we were watching has something waiting */
1146 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1147 return 1;
1149 /* if rchan is set, it is 'c' */
1150 res = rchan ? 1 : 0; /* map into 'res' values */
1152 if (res > 0) {
1153 struct ast_frame *fr = ast_read(c);
1154 if (!fr) {
1155 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1156 return -1;
1158 switch(fr->frametype) {
1159 case AST_FRAME_DTMF_END:
1160 if (context) {
1161 const char exten[2] = { fr->subclass, '\0' };
1162 if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1163 res = fr->subclass;
1164 ast_frfree(fr);
1165 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1166 return res;
1168 } else {
1169 res = fr->subclass;
1170 if (strchr(forward,res)) {
1171 ast_stream_fastforward(c->stream, skip_ms);
1172 } else if (strchr(rewind,res)) {
1173 ast_stream_rewind(c->stream, skip_ms);
1174 } else if (strchr(breakon, res)) {
1175 ast_frfree(fr);
1176 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1177 return res;
1180 break;
1181 case AST_FRAME_CONTROL:
1182 switch(fr->subclass) {
1183 case AST_CONTROL_HANGUP:
1184 case AST_CONTROL_BUSY:
1185 case AST_CONTROL_CONGESTION:
1186 ast_frfree(fr);
1187 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1188 return -1;
1189 case AST_CONTROL_RINGING:
1190 case AST_CONTROL_ANSWER:
1191 case AST_CONTROL_VIDUPDATE:
1192 case AST_CONTROL_SRCUPDATE:
1193 case AST_CONTROL_HOLD:
1194 case AST_CONTROL_UNHOLD:
1195 /* Unimportant */
1196 break;
1197 default:
1198 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1200 break;
1201 case AST_FRAME_VOICE:
1202 /* Write audio if appropriate */
1203 if (audiofd > -1)
1204 write(audiofd, fr->data, fr->datalen);
1205 default:
1206 /* Ignore all others */
1207 break;
1209 ast_frfree(fr);
1211 ast_sched_runq(c->sched);
1214 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1216 return (err || c->_softhangup) ? -1 : 0;
1219 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *rewind, int ms)
1221 return waitstream_core(c, breakon, forward, rewind, ms,
1222 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1225 int ast_waitstream(struct ast_channel *c, const char *breakon)
1227 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1230 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1232 return waitstream_core(c, breakon, NULL, NULL, 0,
1233 audiofd, cmdfd, NULL /* no context */);
1236 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1238 /* Waitstream, with return in the case of a valid 1 digit extension */
1239 /* in the current or specified context being pressed */
1241 if (!context)
1242 context = c->context;
1243 return waitstream_core(c, NULL, NULL, NULL, 0,
1244 -1, -1, context);
1248 * if the file name is non-empty, try to play it.
1249 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1250 * If digits == "" then we can simply check for non-zero.
1252 int ast_stream_and_wait(struct ast_channel *chan, const char *file,
1253 const char *language, const char *digits)
1255 int res = 0;
1256 if (!ast_strlen_zero(file)) {
1257 res = ast_streamfile(chan, file, language);
1258 if (!res)
1259 res = ast_waitstream(chan, digits);
1261 return res;
1264 static int show_file_formats(int fd, int argc, char *argv[])
1266 #define FORMAT "%-10s %-10s %-20s\n"
1267 #define FORMAT2 "%-10s %-10s %-20s\n"
1268 struct ast_format *f;
1269 int count_fmt = 0;
1271 if (argc != 4)
1272 return RESULT_SHOWUSAGE;
1273 ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1275 if (AST_LIST_LOCK(&formats)) {
1276 ast_log(LOG_WARNING, "Unable to lock format list\n");
1277 return -1;
1280 AST_LIST_TRAVERSE(&formats, f, list) {
1281 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1282 count_fmt++;
1284 AST_LIST_UNLOCK(&formats);
1285 ast_cli(fd, "%d file formats registered.\n", count_fmt);
1286 return RESULT_SUCCESS;
1287 #undef FORMAT
1288 #undef FORMAT2
1291 static int show_file_formats_deprecated(int fd, int argc, char *argv[])
1293 #define FORMAT "%-10s %-10s %-20s\n"
1294 #define FORMAT2 "%-10s %-10s %-20s\n"
1295 struct ast_format *f;
1296 int count_fmt = 0;
1298 if (argc != 3)
1299 return RESULT_SHOWUSAGE;
1300 ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1302 if (AST_LIST_LOCK(&formats)) {
1303 ast_log(LOG_WARNING, "Unable to lock format list\n");
1304 return -1;
1307 AST_LIST_TRAVERSE(&formats, f, list) {
1308 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1309 count_fmt++;
1311 AST_LIST_UNLOCK(&formats);
1312 ast_cli(fd, "%d file formats registered.\n", count_fmt);
1313 return RESULT_SUCCESS;
1314 #undef FORMAT
1315 #undef FORMAT2
1318 char show_file_formats_usage[] =
1319 "Usage: core show file formats\n"
1320 " Displays currently registered file formats (if any)\n";
1322 struct ast_cli_entry cli_show_file_formats_deprecated = {
1323 { "show", "file", "formats" },
1324 show_file_formats_deprecated, NULL,
1325 NULL };
1327 struct ast_cli_entry cli_file[] = {
1328 { { "core", "show", "file", "formats" },
1329 show_file_formats, "Displays file formats",
1330 show_file_formats_usage, NULL, &cli_show_file_formats_deprecated },
1333 int ast_file_init(void)
1335 ast_cli_register_multiple(cli_file, sizeof(cli_file) / sizeof(struct ast_cli_entry));
1336 return 0;