fix a flaw found while experimenting with structure alignment and padding; low-fence...
[asterisk-bristuff.git] / main / file.c
bloba3f14fbe61f2b102250b11bedf92375520528ebd
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 && !is_absolute_path(filename)) { /* 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 /* We try languages in the following order:
531 * preflang (may include dialect)
532 * lang (preflang without dialect - if any)
533 * <none>
534 * default (unless the same as preflang or lang without dialect)
537 /* Try preferred language */
538 if (!ast_strlen_zero(preflang)) {
539 /* try the preflang exactly as it was requested */
540 if ((res = fileexists_test(filename, fmt, preflang, buf, buflen)) > 0) {
541 return res;
542 } else {
543 /* try without a dialect */
544 char *postfix = NULL;
545 postfix = lang = ast_strdupa(preflang);
547 strsep(&postfix, "_");
548 if (postfix) {
549 if ((res = fileexists_test(filename, fmt, lang, buf, buflen)) > 0) {
550 return res;
556 /* Try without any language */
557 if ((res = fileexists_test(filename, fmt, NULL, buf, buflen)) > 0) {
558 return res;
561 /* Finally try the default language unless it was already tried before */
562 if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
563 if ((res = fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen)) > 0) {
564 return res;
568 return 0;
571 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
573 return ast_openstream_full(chan, filename, preflang, 0);
576 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
579 * Use fileexists_core() to find a file in a compatible
580 * language and format, set up a suitable translator,
581 * and open the stream.
583 int fmts, res, buflen;
584 char *buf;
586 if (!asis) {
587 /* do this first, otherwise we detect the wrong writeformat */
588 ast_stopstream(chan);
589 if (chan->generator)
590 ast_deactivate_generator(chan);
592 if (preflang == NULL)
593 preflang = "";
594 buflen = strlen(preflang) + strlen(filename) + 4;
595 buf = alloca(buflen);
596 if (buf == NULL)
597 return NULL;
598 fmts = fileexists_core(filename, NULL, preflang, buf, buflen);
599 if (fmts > 0)
600 fmts &= AST_FORMAT_AUDIO_MASK;
601 if (fmts < 1) {
602 ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
603 return NULL;
605 chan->oldwriteformat = chan->writeformat;
606 /* Set the channel to a format we can work with */
607 res = ast_set_write_format(chan, fmts);
608 res = ast_filehelper(buf, chan, NULL, ACTION_OPEN);
609 if (res >= 0)
610 return chan->stream;
611 return NULL;
614 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
616 /* As above, but for video. But here we don't have translators
617 * so we must enforce a format.
619 unsigned int format;
620 char *buf;
621 int buflen;
623 if (preflang == NULL)
624 preflang = "";
625 buflen = strlen(preflang) + strlen(filename) + 4;
626 buf = alloca(buflen);
627 if (buf == NULL)
628 return NULL;
630 for (format = AST_FORMAT_MAX_AUDIO << 1; format <= AST_FORMAT_MAX_VIDEO; format = format << 1) {
631 int fd;
632 const char *fmt;
634 if (!(chan->nativeformats & format))
635 continue;
636 fmt = ast_getformatname(format);
637 if ( fileexists_core(filename, fmt, preflang, buf, buflen) < 1) /* no valid format */
638 continue;
639 fd = ast_filehelper(buf, chan, fmt, ACTION_OPEN);
640 if (fd >= 0)
641 return chan->vstream;
642 ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
644 return NULL;
647 struct ast_frame *ast_readframe(struct ast_filestream *s)
649 struct ast_frame *f = NULL;
650 int whennext = 0;
651 if (s && s->fmt)
652 f = s->fmt->read(s, &whennext);
653 return f;
656 enum fsread_res {
657 FSREAD_FAILURE,
658 FSREAD_SUCCESS_SCHED,
659 FSREAD_SUCCESS_NOSCHED,
662 static int ast_fsread_audio(const void *data);
664 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
666 int whennext = 0;
668 while (!whennext) {
669 struct ast_frame *fr;
671 if (s->orig_chan_name && strcasecmp(s->owner->name, s->orig_chan_name))
672 goto return_failure;
674 fr = s->fmt->read(s, &whennext);
675 if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
676 if (fr)
677 ast_log(LOG_WARNING, "Failed to write frame\n");
678 goto return_failure;
681 if (whennext != s->lasttimeout) {
682 #ifdef HAVE_DAHDI
683 if (s->owner->timingfd > -1) {
684 int zap_timer_samples = whennext;
685 int rate;
686 /* whennext is in samples, but zaptel timers operate in 8 kHz samples. */
687 if ((rate = ast_format_rate(s->fmt->format)) != 8000) {
688 float factor;
689 factor = ((float) rate) / ((float) 8000.0);
690 zap_timer_samples = (int) ( ((float) zap_timer_samples) / factor );
692 ast_settimeout(s->owner, zap_timer_samples, ast_fsread_audio, s);
693 } else
694 #endif
695 s->owner->streamid = ast_sched_add(s->owner->sched,
696 whennext / (ast_format_rate(s->fmt->format) / 1000),
697 ast_fsread_audio, s);
698 s->lasttimeout = whennext;
699 return FSREAD_SUCCESS_NOSCHED;
701 return FSREAD_SUCCESS_SCHED;
703 return_failure:
704 s->owner->streamid = -1;
705 #ifdef HAVE_DAHDI
706 ast_settimeout(s->owner, 0, NULL, NULL);
707 #endif
708 return FSREAD_FAILURE;
711 static int ast_fsread_audio(const void *data)
713 struct ast_filestream *fs = (struct ast_filestream *)data;
714 enum fsread_res res;
716 res = ast_readaudio_callback(fs);
718 if (res == FSREAD_SUCCESS_SCHED)
719 return 1;
721 return 0;
724 static int ast_fsread_video(const void *data);
726 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
728 int whennext = 0;
730 while (!whennext) {
731 struct ast_frame *fr = s->fmt->read(s, &whennext);
732 if (!fr || ast_write(s->owner, fr)) { /* no stream or error, as above */
733 if (fr)
734 ast_log(LOG_WARNING, "Failed to write frame\n");
735 s->owner->vstreamid = -1;
736 return FSREAD_FAILURE;
740 if (whennext != s->lasttimeout) {
741 s->owner->vstreamid = ast_sched_add(s->owner->sched,
742 whennext / (ast_format_rate(s->fmt->format) / 1000),
743 ast_fsread_video, s);
744 s->lasttimeout = whennext;
745 return FSREAD_SUCCESS_NOSCHED;
748 return FSREAD_SUCCESS_SCHED;
751 static int ast_fsread_video(const void *data)
753 struct ast_filestream *fs = (struct ast_filestream *)data;
754 enum fsread_res res;
756 res = ast_readvideo_callback(fs);
758 if (res == FSREAD_SUCCESS_SCHED)
759 return 1;
761 return 0;
764 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
766 s->owner = chan;
767 return 0;
770 int ast_playstream(struct ast_filestream *s)
772 enum fsread_res res;
774 if (s->fmt->format < AST_FORMAT_MAX_AUDIO)
775 res = ast_readaudio_callback(s);
776 else
777 res = ast_readvideo_callback(s);
779 return (res == FSREAD_FAILURE) ? -1 : 0;
782 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
784 return fs->fmt->seek(fs, sample_offset, whence);
787 int ast_truncstream(struct ast_filestream *fs)
789 return fs->fmt->trunc(fs);
792 off_t ast_tellstream(struct ast_filestream *fs)
794 return fs->fmt->tell(fs);
797 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
799 return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
802 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
804 return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
807 int ast_closestream(struct ast_filestream *f)
809 char *cmd = NULL;
810 size_t size = 0;
811 /* Stop a running stream if there is one */
812 if (f->owner) {
813 if (f->fmt->format < AST_FORMAT_MAX_AUDIO) {
814 f->owner->stream = NULL;
815 AST_SCHED_DEL(f->owner->sched, f->owner->streamid);
816 #ifdef HAVE_DAHDI
817 ast_settimeout(f->owner, 0, NULL, NULL);
818 #endif
819 } else {
820 f->owner->vstream = NULL;
821 AST_SCHED_DEL(f->owner->sched, f->owner->vstreamid);
824 /* destroy the translator on exit */
825 if (f->trans)
826 ast_translator_free_path(f->trans);
828 if (f->realfilename && f->filename) {
829 size = strlen(f->filename) + strlen(f->realfilename) + 15;
830 cmd = alloca(size);
831 memset(cmd,0,size);
832 snprintf(cmd,size,"/bin/mv -f %s %s",f->filename,f->realfilename);
833 ast_safe_system(cmd);
836 if (f->filename)
837 free(f->filename);
838 if (f->realfilename)
839 free(f->realfilename);
840 if (f->fmt->close)
841 f->fmt->close(f);
842 fclose(f->f);
843 if (f->vfs)
844 ast_closestream(f->vfs);
845 if (f->orig_chan_name)
846 free((void *) f->orig_chan_name);
847 ast_module_unref(f->fmt->module);
848 free(f);
849 return 0;
854 * Look the various language-specific places where a file could exist.
856 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
858 char *buf;
859 int buflen;
861 if (preflang == NULL)
862 preflang = "";
863 buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
864 buf = alloca(buflen);
865 if (buf == NULL)
866 return 0;
867 return fileexists_core(filename, fmt, preflang, buf, buflen);
870 int ast_filedelete(const char *filename, const char *fmt)
872 return ast_filehelper(filename, NULL, fmt, ACTION_DELETE);
875 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
877 return ast_filehelper(filename, filename2, fmt, ACTION_RENAME);
880 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
882 return ast_filehelper(filename, filename2, fmt, ACTION_COPY);
885 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
887 struct ast_filestream *fs;
888 struct ast_filestream *vfs=NULL;
889 char fmt[256];
891 fs = ast_openstream(chan, filename, preflang);
892 if (fs)
893 vfs = ast_openvstream(chan, filename, preflang);
894 if (vfs)
895 ast_log(LOG_DEBUG, "Ooh, found a video stream, too, format %s\n", ast_getformatname(vfs->fmt->format));
896 if (fs){
897 int res;
898 if (ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM))
899 fs->orig_chan_name = ast_strdup(chan->name);
900 if (ast_applystream(chan, fs))
901 return -1;
902 if (vfs && ast_applystream(chan, vfs))
903 return -1;
904 res = ast_playstream(fs);
905 if (!res && vfs)
906 res = ast_playstream(vfs);
907 if (option_verbose > 2)
908 ast_verbose(VERBOSE_PREFIX_3 "<%s> Playing '%s' (language '%s')\n", chan->name, filename, preflang ? preflang : "default");
910 return res;
912 ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), chan->nativeformats), strerror(errno));
913 return -1;
916 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
918 FILE *bfile;
919 struct ast_format *f;
920 struct ast_filestream *fs = NULL;
921 char *fn;
923 if (AST_LIST_LOCK(&formats)) {
924 ast_log(LOG_WARNING, "Unable to lock format list\n");
925 return NULL;
928 AST_LIST_TRAVERSE(&formats, f, list) {
929 fs = NULL;
930 if (!exts_compare(f->exts, type))
931 continue;
933 fn = build_filename(filename, type);
934 errno = 0;
935 bfile = fopen(fn, "r");
936 if (!bfile || (fs = get_filestream(f, bfile)) == NULL ||
937 open_wrapper(fs) ) {
938 ast_log(LOG_WARNING, "Unable to open %s\n", fn);
939 if (fs)
940 ast_free(fs);
941 if (bfile)
942 fclose(bfile);
943 free(fn);
944 continue;
946 /* found it */
947 fs->trans = NULL;
948 fs->fmt = f;
949 fs->flags = flags;
950 fs->mode = mode;
951 fs->filename = strdup(filename);
952 fs->vfs = NULL;
953 break;
956 AST_LIST_UNLOCK(&formats);
957 if (!fs)
958 ast_log(LOG_WARNING, "No such format '%s'\n", type);
960 return fs;
963 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
965 int fd, myflags = 0;
966 /* compiler claims this variable can be used before initialization... */
967 FILE *bfile = NULL;
968 struct ast_format *f;
969 struct ast_filestream *fs = NULL;
970 char *buf = NULL;
971 size_t size = 0;
972 int format_found = 0;
974 if (AST_LIST_LOCK(&formats)) {
975 ast_log(LOG_WARNING, "Unable to lock format list\n");
976 return NULL;
979 /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
980 /* We really can't use O_APPEND as it will break WAV header updates */
981 if (flags & O_APPEND) {
982 flags &= ~O_APPEND;
983 } else {
984 myflags = O_TRUNC;
987 myflags |= O_WRONLY | O_CREAT;
989 /* XXX need to fix this - we should just do the fopen,
990 * not open followed by fdopen()
992 AST_LIST_TRAVERSE(&formats, f, list) {
993 char *fn, *orig_fn = NULL;
994 if (fs)
995 break;
997 if (!exts_compare(f->exts, type))
998 continue;
999 else
1000 format_found = 1;
1002 fn = build_filename(filename, type);
1003 fd = open(fn, flags | myflags, mode);
1004 if (fd > -1) {
1005 /* fdopen() the resulting file stream */
1006 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1007 if (!bfile) {
1008 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1009 close(fd);
1010 fd = -1;
1014 if (ast_opt_cache_record_files && (fd > -1)) {
1015 char *c;
1017 fclose(bfile); /* this also closes fd */
1019 We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
1020 What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
1022 orig_fn = ast_strdupa(fn);
1023 for (c = fn; *c; c++)
1024 if (*c == '/')
1025 *c = '_';
1027 size = strlen(fn) + strlen(record_cache_dir) + 2;
1028 buf = alloca(size);
1029 strcpy(buf, record_cache_dir);
1030 strcat(buf, "/");
1031 strcat(buf, fn);
1032 free(fn);
1033 fn = buf;
1034 fd = open(fn, flags | myflags, mode);
1035 if (fd > -1) {
1036 /* fdopen() the resulting file stream */
1037 bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
1038 if (!bfile) {
1039 ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
1040 close(fd);
1041 fd = -1;
1045 if (fd > -1) {
1046 errno = 0;
1047 fs = get_filestream(f, bfile);
1048 if (!fs || rewrite_wrapper(fs, comment)) {
1049 ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
1050 close(fd);
1051 if (orig_fn) {
1052 unlink(fn);
1053 unlink(orig_fn);
1055 if (fs)
1056 ast_free(fs);
1057 fs = NULL;
1058 continue;
1060 fs->trans = NULL;
1061 fs->fmt = f;
1062 fs->flags = flags;
1063 fs->mode = mode;
1064 if (orig_fn) {
1065 fs->realfilename = strdup(orig_fn);
1066 fs->filename = strdup(fn);
1067 } else {
1068 fs->realfilename = NULL;
1069 fs->filename = strdup(filename);
1071 fs->vfs = NULL;
1072 /* If truncated, we'll be at the beginning; if not truncated, then append */
1073 f->seek(fs, 0, SEEK_END);
1074 } else if (errno != EEXIST) {
1075 ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
1076 if (orig_fn)
1077 unlink(orig_fn);
1079 /* if buf != NULL then fn is already free and pointing to it */
1080 if (!buf)
1081 free(fn);
1084 AST_LIST_UNLOCK(&formats);
1086 if (!format_found)
1087 ast_log(LOG_WARNING, "No such format '%s'\n", type);
1089 return fs;
1093 * \brief the core of all waitstream() functions
1095 static int waitstream_core(struct ast_channel *c, const char *breakon,
1096 const char *forward, const char *rewind, int skip_ms,
1097 int audiofd, int cmdfd, const char *context)
1099 const char *orig_chan_name = NULL;
1100 int err = 0;
1102 if (!breakon)
1103 breakon = "";
1104 if (!forward)
1105 forward = "";
1106 if (!rewind)
1107 rewind = "";
1109 /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
1110 ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
1112 if (ast_test_flag(c, AST_FLAG_MASQ_NOSTREAM))
1113 orig_chan_name = ast_strdupa(c->name);
1115 while (c->stream) {
1116 int res;
1117 int ms;
1119 if (orig_chan_name && strcasecmp(orig_chan_name, c->name)) {
1120 ast_stopstream(c);
1121 err = 1;
1122 break;
1125 ms = ast_sched_wait(c->sched);
1127 if (ms < 0 && !c->timingfunc) {
1128 ast_stopstream(c);
1129 break;
1131 if (ms < 0)
1132 ms = 1000;
1133 if (cmdfd < 0) {
1134 res = ast_waitfor(c, ms);
1135 if (res < 0) {
1136 ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
1137 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1138 return res;
1140 } else {
1141 int outfd;
1142 struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1143 if (!rchan && (outfd < 0) && (ms)) {
1144 /* Continue */
1145 if (errno == EINTR)
1146 continue;
1147 ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1148 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1149 return -1;
1150 } else if (outfd > -1) { /* this requires cmdfd set */
1151 /* The FD we were watching has something waiting */
1152 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1153 return 1;
1155 /* if rchan is set, it is 'c' */
1156 res = rchan ? 1 : 0; /* map into 'res' values */
1158 if (res > 0) {
1159 struct ast_frame *fr = ast_read(c);
1160 if (!fr) {
1161 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1162 return -1;
1164 switch(fr->frametype) {
1165 case AST_FRAME_DTMF_END:
1166 if (context) {
1167 const char exten[2] = { fr->subclass, '\0' };
1168 if (ast_exists_extension(c, context, exten, 1, c->cid.cid_num)) {
1169 res = fr->subclass;
1170 ast_frfree(fr);
1171 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1172 return res;
1174 } else {
1175 res = fr->subclass;
1176 if (strchr(forward,res)) {
1177 ast_stream_fastforward(c->stream, skip_ms);
1178 } else if (strchr(rewind,res)) {
1179 ast_stream_rewind(c->stream, skip_ms);
1180 } else if (strchr(breakon, res)) {
1181 ast_frfree(fr);
1182 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1183 return res;
1186 break;
1187 case AST_FRAME_CONTROL:
1188 switch(fr->subclass) {
1189 case AST_CONTROL_HANGUP:
1190 case AST_CONTROL_BUSY:
1191 case AST_CONTROL_CONGESTION:
1192 ast_frfree(fr);
1193 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1194 return -1;
1195 case AST_CONTROL_RINGING:
1196 case AST_CONTROL_ANSWER:
1197 case AST_CONTROL_VIDUPDATE:
1198 case AST_CONTROL_SRCUPDATE:
1199 case AST_CONTROL_HOLD:
1200 case AST_CONTROL_UNHOLD:
1201 /* Unimportant */
1202 break;
1203 default:
1204 ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass);
1206 break;
1207 case AST_FRAME_VOICE:
1208 /* Write audio if appropriate */
1209 if (audiofd > -1)
1210 write(audiofd, fr->data, fr->datalen);
1211 default:
1212 /* Ignore all others */
1213 break;
1215 ast_frfree(fr);
1217 ast_sched_runq(c->sched);
1220 ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
1222 return (err || c->_softhangup) ? -1 : 0;
1225 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *rewind, int ms)
1227 return waitstream_core(c, breakon, forward, rewind, ms,
1228 -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */);
1231 int ast_waitstream(struct ast_channel *c, const char *breakon)
1233 return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL);
1236 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
1238 return waitstream_core(c, breakon, NULL, NULL, 0,
1239 audiofd, cmdfd, NULL /* no context */);
1242 int ast_waitstream_exten(struct ast_channel *c, const char *context)
1244 /* Waitstream, with return in the case of a valid 1 digit extension */
1245 /* in the current or specified context being pressed */
1247 if (!context)
1248 context = c->context;
1249 return waitstream_core(c, NULL, NULL, NULL, 0,
1250 -1, -1, context);
1254 * if the file name is non-empty, try to play it.
1255 * Return 0 if success, -1 if error, digit if interrupted by a digit.
1256 * If digits == "" then we can simply check for non-zero.
1258 int ast_stream_and_wait(struct ast_channel *chan, const char *file,
1259 const char *language, const char *digits)
1261 int res = 0;
1262 if (!ast_strlen_zero(file)) {
1263 res = ast_streamfile(chan, file, language);
1264 if (!res)
1265 res = ast_waitstream(chan, digits);
1267 return res;
1270 static int show_file_formats(int fd, int argc, char *argv[])
1272 #define FORMAT "%-10s %-10s %-20s\n"
1273 #define FORMAT2 "%-10s %-10s %-20s\n"
1274 struct ast_format *f;
1275 int count_fmt = 0;
1277 if (argc != 4)
1278 return RESULT_SHOWUSAGE;
1279 ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1281 if (AST_LIST_LOCK(&formats)) {
1282 ast_log(LOG_WARNING, "Unable to lock format list\n");
1283 return -1;
1286 AST_LIST_TRAVERSE(&formats, f, list) {
1287 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1288 count_fmt++;
1290 AST_LIST_UNLOCK(&formats);
1291 ast_cli(fd, "%d file formats registered.\n", count_fmt);
1292 return RESULT_SUCCESS;
1293 #undef FORMAT
1294 #undef FORMAT2
1297 static int show_file_formats_deprecated(int fd, int argc, char *argv[])
1299 #define FORMAT "%-10s %-10s %-20s\n"
1300 #define FORMAT2 "%-10s %-10s %-20s\n"
1301 struct ast_format *f;
1302 int count_fmt = 0;
1304 if (argc != 3)
1305 return RESULT_SHOWUSAGE;
1306 ast_cli(fd, FORMAT, "Format", "Name", "Extensions");
1308 if (AST_LIST_LOCK(&formats)) {
1309 ast_log(LOG_WARNING, "Unable to lock format list\n");
1310 return -1;
1313 AST_LIST_TRAVERSE(&formats, f, list) {
1314 ast_cli(fd, FORMAT2, ast_getformatname(f->format), f->name, f->exts);
1315 count_fmt++;
1317 AST_LIST_UNLOCK(&formats);
1318 ast_cli(fd, "%d file formats registered.\n", count_fmt);
1319 return RESULT_SUCCESS;
1320 #undef FORMAT
1321 #undef FORMAT2
1324 char show_file_formats_usage[] =
1325 "Usage: core show file formats\n"
1326 " Displays currently registered file formats (if any)\n";
1328 struct ast_cli_entry cli_show_file_formats_deprecated = {
1329 { "show", "file", "formats" },
1330 show_file_formats_deprecated, NULL,
1331 NULL };
1333 struct ast_cli_entry cli_file[] = {
1334 { { "core", "show", "file", "formats" },
1335 show_file_formats, "Displays file formats",
1336 show_file_formats_usage, NULL, &cli_show_file_formats_deprecated },
1339 int ast_file_init(void)
1341 ast_cli_register_multiple(cli_file, sizeof(cli_file) / sizeof(struct ast_cli_entry));
1342 return 0;