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