removed GAIN preprocessor definition, removed needsgain from struct wav_desc, removed...
[asterisk/asterisk.git] / formats / format_wav.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, 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 Work with WAV in the proprietary Microsoft format.
22  * Microsoft WAV format (8000hz Signed Linear)
23  * \arg File name extension: wav (lower case)
24  * \ingroup formats
25  */
26  
27 #include "asterisk.h"
28
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30
31 #include <unistd.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <stdlib.h>
35 #include <sys/time.h>
36 #include <stdio.h>
37 #include <errno.h>
38 #include <string.h>
39
40 #include "asterisk/lock.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/file.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/module.h"
46 #include "asterisk/endian.h"
47
48 /* Some Ideas for this code came from makewave.c by Jeffrey Chilton */
49
50 /* Portions of the conversion code are by guido@sienanet.it */
51
52 #define WAV_BUF_SIZE    320
53
54 struct wav_desc {       /* format-specific parameters */
55         int bytes;
56         int lasttimeout;
57         int maxlen;
58         struct timeval last;
59 };
60
61 #define BLOCKSIZE 160
62
63 #if __BYTE_ORDER == __LITTLE_ENDIAN
64 #define htoll(b) (b)
65 #define htols(b) (b)
66 #define ltohl(b) (b)
67 #define ltohs(b) (b)
68 #else
69 #if __BYTE_ORDER == __BIG_ENDIAN
70 #define htoll(b)  \
71           (((((b)      ) & 0xFF) << 24) | \
72                ((((b) >>  8) & 0xFF) << 16) | \
73                    ((((b) >> 16) & 0xFF) <<  8) | \
74                    ((((b) >> 24) & 0xFF)      ))
75 #define htols(b) \
76           (((((b)      ) & 0xFF) << 8) | \
77                    ((((b) >> 8) & 0xFF)      ))
78 #define ltohl(b) htoll(b)
79 #define ltohs(b) htols(b)
80 #else
81 #error "Endianess not defined"
82 #endif
83 #endif
84
85
86 static int check_header(FILE *f)
87 {
88         int type, size, formtype;
89         int fmt, hsize;
90         short format, chans, bysam, bisam;
91         int bysec;
92         int freq;
93         int data;
94         if (fread(&type, 1, 4, f) != 4) {
95                 ast_log(LOG_WARNING, "Read failed (type)\n");
96                 return -1;
97         }
98         if (fread(&size, 1, 4, f) != 4) {
99                 ast_log(LOG_WARNING, "Read failed (size)\n");
100                 return -1;
101         }
102         size = ltohl(size);
103         if (fread(&formtype, 1, 4, f) != 4) {
104                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
105                 return -1;
106         }
107         if (memcmp(&type, "RIFF", 4)) {
108                 ast_log(LOG_WARNING, "Does not begin with RIFF\n");
109                 return -1;
110         }
111         if (memcmp(&formtype, "WAVE", 4)) {
112                 ast_log(LOG_WARNING, "Does not contain WAVE\n");
113                 return -1;
114         }
115         if (fread(&fmt, 1, 4, f) != 4) {
116                 ast_log(LOG_WARNING, "Read failed (fmt)\n");
117                 return -1;
118         }
119         if (memcmp(&fmt, "fmt ", 4)) {
120                 ast_log(LOG_WARNING, "Does not say fmt\n");
121                 return -1;
122         }
123         if (fread(&hsize, 1, 4, f) != 4) {
124                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
125                 return -1;
126         }
127         if (ltohl(hsize) < 16) {
128                 ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
129                 return -1;
130         }
131         if (fread(&format, 1, 2, f) != 2) {
132                 ast_log(LOG_WARNING, "Read failed (format)\n");
133                 return -1;
134         }
135         if (ltohs(format) != 1) {
136                 ast_log(LOG_WARNING, "Not a wav file %d\n", ltohs(format));
137                 return -1;
138         }
139         if (fread(&chans, 1, 2, f) != 2) {
140                 ast_log(LOG_WARNING, "Read failed (format)\n");
141                 return -1;
142         }
143         if (ltohs(chans) != 1) {
144                 ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
145                 return -1;
146         }
147         if (fread(&freq, 1, 4, f) != 4) {
148                 ast_log(LOG_WARNING, "Read failed (freq)\n");
149                 return -1;
150         }
151         if (ltohl(freq) != DEFAULT_SAMPLE_RATE) {
152                 ast_log(LOG_WARNING, "Unexpected freqency %d\n", ltohl(freq));
153                 return -1;
154         }
155         /* Ignore the byte frequency */
156         if (fread(&bysec, 1, 4, f) != 4) {
157                 ast_log(LOG_WARNING, "Read failed (BYTES_PER_SECOND)\n");
158                 return -1;
159         }
160         /* Check bytes per sample */
161         if (fread(&bysam, 1, 2, f) != 2) {
162                 ast_log(LOG_WARNING, "Read failed (BYTES_PER_SAMPLE)\n");
163                 return -1;
164         }
165         if (ltohs(bysam) != 2) {
166                 ast_log(LOG_WARNING, "Can only handle 16bits per sample: %d\n", ltohs(bysam));
167                 return -1;
168         }
169         if (fread(&bisam, 1, 2, f) != 2) {
170                 ast_log(LOG_WARNING, "Read failed (Bits Per Sample): %d\n", ltohs(bisam));
171                 return -1;
172         }
173         /* Skip any additional header */
174         if (fseek(f,ltohl(hsize)-16,SEEK_CUR) == -1 ) {
175                 ast_log(LOG_WARNING, "Failed to skip remaining header bytes: %d\n", ltohl(hsize)-16 );
176                 return -1;
177         }
178         /* Skip any facts and get the first data block */
179         for(;;)
180         { 
181                 char buf[4];
182             
183             /* Begin data chunk */
184             if (fread(&buf, 1, 4, f) != 4) {
185                         ast_log(LOG_WARNING, "Read failed (data)\n");
186                         return -1;
187             }
188             /* Data has the actual length of data in it */
189             if (fread(&data, 1, 4, f) != 4) {
190                         ast_log(LOG_WARNING, "Read failed (data)\n");
191                         return -1;
192             }
193             data = ltohl(data);
194             if(memcmp(buf, "data", 4) == 0 ) 
195                         break;
196             if(memcmp(buf, "fact", 4) != 0 ) {
197                         ast_log(LOG_WARNING, "Unknown block - not fact or data\n");
198                         return -1;
199             }
200             if (fseek(f,data,SEEK_CUR) == -1 ) {
201                         ast_log(LOG_WARNING, "Failed to skip fact block: %d\n", data );
202                         return -1;
203             }
204         }
205 #if 0
206         curpos = lseek(fd, 0, SEEK_CUR);
207         truelength = lseek(fd, 0, SEEK_END);
208         lseek(fd, curpos, SEEK_SET);
209         truelength -= curpos;
210 #endif  
211         return data;
212 }
213
214 static int update_header(FILE *f)
215 {
216         off_t cur,end;
217         int datalen,filelen,bytes;
218         
219         cur = ftello(f);
220         fseek(f, 0, SEEK_END);
221         end = ftello(f);
222         /* data starts 44 bytes in */
223         bytes = end - 44;
224         datalen = htoll(bytes);
225         /* chunk size is bytes of data plus 36 bytes of header */
226         filelen = htoll(36 + bytes);
227         
228         if (cur < 0) {
229                 ast_log(LOG_WARNING, "Unable to find our position\n");
230                 return -1;
231         }
232         if (fseek(f, 4, SEEK_SET)) {
233                 ast_log(LOG_WARNING, "Unable to set our position\n");
234                 return -1;
235         }
236         if (fwrite(&filelen, 1, 4, f) != 4) {
237                 ast_log(LOG_WARNING, "Unable to set write file size\n");
238                 return -1;
239         }
240         if (fseek(f, 40, SEEK_SET)) {
241                 ast_log(LOG_WARNING, "Unable to set our position\n");
242                 return -1;
243         }
244         if (fwrite(&datalen, 1, 4, f) != 4) {
245                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
246                 return -1;
247         }
248         if (fseeko(f, cur, SEEK_SET)) {
249                 ast_log(LOG_WARNING, "Unable to return to position\n");
250                 return -1;
251         }
252         return 0;
253 }
254
255 static int write_header(FILE *f)
256 {
257         unsigned int hz=htoll(8000);
258         unsigned int bhz = htoll(16000);
259         unsigned int hs = htoll(16);
260         unsigned short fmt = htols(1);
261         unsigned short chans = htols(1);
262         unsigned short bysam = htols(2);
263         unsigned short bisam = htols(16);
264         unsigned int size = htoll(0);
265         /* Write a wav header, ignoring sizes which will be filled in later */
266         fseek(f,0,SEEK_SET);
267         if (fwrite("RIFF", 1, 4, f) != 4) {
268                 ast_log(LOG_WARNING, "Unable to write header\n");
269                 return -1;
270         }
271         if (fwrite(&size, 1, 4, f) != 4) {
272                 ast_log(LOG_WARNING, "Unable to write header\n");
273                 return -1;
274         }
275         if (fwrite("WAVEfmt ", 1, 8, f) != 8) {
276                 ast_log(LOG_WARNING, "Unable to write header\n");
277                 return -1;
278         }
279         if (fwrite(&hs, 1, 4, f) != 4) {
280                 ast_log(LOG_WARNING, "Unable to write header\n");
281                 return -1;
282         }
283         if (fwrite(&fmt, 1, 2, f) != 2) {
284                 ast_log(LOG_WARNING, "Unable to write header\n");
285                 return -1;
286         }
287         if (fwrite(&chans, 1, 2, f) != 2) {
288                 ast_log(LOG_WARNING, "Unable to write header\n");
289                 return -1;
290         }
291         if (fwrite(&hz, 1, 4, f) != 4) {
292                 ast_log(LOG_WARNING, "Unable to write header\n");
293                 return -1;
294         }
295         if (fwrite(&bhz, 1, 4, f) != 4) {
296                 ast_log(LOG_WARNING, "Unable to write header\n");
297                 return -1;
298         }
299         if (fwrite(&bysam, 1, 2, f) != 2) {
300                 ast_log(LOG_WARNING, "Unable to write header\n");
301                 return -1;
302         }
303         if (fwrite(&bisam, 1, 2, f) != 2) {
304                 ast_log(LOG_WARNING, "Unable to write header\n");
305                 return -1;
306         }
307         if (fwrite("data", 1, 4, f) != 4) {
308                 ast_log(LOG_WARNING, "Unable to write header\n");
309                 return -1;
310         }
311         if (fwrite(&size, 1, 4, f) != 4) {
312                 ast_log(LOG_WARNING, "Unable to write header\n");
313                 return -1;
314         }
315         return 0;
316 }
317
318 static int wav_open(struct ast_filestream *s)
319 {
320         /* We don't have any header to read or anything really, but
321            if we did, it would go here.  We also might want to check
322            and be sure it's a valid file.  */
323         struct wav_desc *tmp = (struct wav_desc *)s->private;
324         if ((tmp->maxlen = check_header(s->f)) < 0)
325                 return -1;
326         return 0;
327 }
328
329 static int wav_rewrite(struct ast_filestream *s, const char *comment)
330 {
331         /* We don't have any header to read or anything really, but
332            if we did, it would go here.  We also might want to check
333            and be sure it's a valid file.  */
334
335         if (write_header(s->f))
336                 return -1;
337         return 0;
338 }
339
340 static void wav_close(struct ast_filestream *s)
341 {
342         char zero = 0;
343         struct wav_desc *fs = (struct wav_desc *)s->private;
344         /* Pad to even length */
345         if (fs->bytes & 0x1)
346                 fwrite(&zero, 1, 1, s->f);
347 }
348
349 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
350 {
351         int res;
352         int samples;    /* actual samples read */
353         int x;
354         short *tmp;
355         int bytes = WAV_BUF_SIZE;       /* in bytes */
356         off_t here;
357         /* Send a frame from the file to the appropriate channel */
358         struct wav_desc *fs = (struct wav_desc *)s->private;
359
360         here = ftello(s->f);
361         if (fs->maxlen - here < bytes)          /* truncate if necessary */
362                 bytes = fs->maxlen - here;
363         if (bytes < 0)
364                 bytes = 0;
365 /*      ast_log(LOG_DEBUG, "here: %d, maxlen: %d, bytes: %d\n", here, s->maxlen, bytes); */
366         s->fr.frametype = AST_FRAME_VOICE;
367         s->fr.subclass = AST_FORMAT_SLINEAR;
368         s->fr.mallocd = 0;
369         AST_FRAME_SET_BUFFER(&s->fr, s->buf, AST_FRIENDLY_OFFSET, bytes);
370         
371         if ( (res = fread(s->fr.data, 1, s->fr.datalen, s->f)) <= 0 ) {
372                 if (res)
373                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
374                 return NULL;
375         }
376         s->fr.datalen = res;
377         s->fr.samples = samples = res / 2;
378
379         tmp = (short *)(s->fr.data);
380 #if __BYTE_ORDER == __BIG_ENDIAN
381         /* file format is little endian so we need to swap */
382         for( x = 0; x < samples; x++)
383                 tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
384 #endif
385
386         *whennext = samples;
387         return &s->fr;
388 }
389
390 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
391 {
392         int x;
393 #if __BYTE_ORDER == __BIG_ENDIAN
394         short tmp[8000], *tmpi;
395 #endif
396         struct wav_desc *s = (struct wav_desc *)fs->private;
397         int res;
398
399         if (f->frametype != AST_FRAME_VOICE) {
400                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
401                 return -1;
402         }
403         if (f->subclass != AST_FORMAT_SLINEAR) {
404                 ast_log(LOG_WARNING, "Asked to write non-SLINEAR frame (%d)!\n", f->subclass);
405                 return -1;
406         }
407         if (!f->datalen)
408                 return -1;
409
410 #if __BYTE_ORDER == __BIG_ENDIAN
411         /* swap and write */
412         if (f->datalen > sizeof(tmp)) {
413                 ast_log(LOG_WARNING, "Data length is too long\n");
414                 return -1;
415         }
416         tmpi = f->data;
417         for (x=0; x < f->datalen/2; x++) 
418                 tmp[x] = (tmpi[x] << 8) | ((tmpi[x] & 0xff00) >> 8);
419
420         if ((res = fwrite(tmp, 1, f->datalen, fs->f)) != f->datalen ) {
421 #else
422         /* just write */
423         if ((res = fwrite(f->data, 1, f->datalen, fs->f)) != f->datalen ) {
424 #endif
425                 ast_log(LOG_WARNING, "Bad write (%d): %s\n", res, strerror(errno));
426                 return -1;
427         }
428
429         s->bytes += f->datalen;
430         update_header(fs->f);
431                 
432         return 0;
433
434 }
435
436 static int wav_seek(struct ast_filestream *fs, off_t sample_offset, int whence)
437 {
438         off_t min, max, cur, offset = 0, samples;
439
440         samples = sample_offset * 2; /* SLINEAR is 16 bits mono, so sample_offset * 2 = bytes */
441         min = 44; /* wav header is 44 bytes */
442         cur = ftello(fs->f);
443         fseeko(fs->f, 0, SEEK_END);
444         max = ftello(fs->f);
445         if (whence == SEEK_SET)
446                 offset = samples + min;
447         else if (whence == SEEK_CUR || whence == SEEK_FORCECUR)
448                 offset = samples + cur;
449         else if (whence == SEEK_END)
450                 offset = max - samples;
451         if (whence != SEEK_FORCECUR) {
452                 offset = (offset > max)?max:offset;
453         }
454         /* always protect the header space. */
455         offset = (offset < min)?min:offset;
456         return fseeko(fs->f, offset, SEEK_SET);
457 }
458
459 static int wav_trunc(struct ast_filestream *fs)
460 {
461         if (ftruncate(fileno(fs->f), ftello(fs->f)))
462                 return -1;
463         return update_header(fs->f);
464 }
465
466 static off_t wav_tell(struct ast_filestream *fs)
467 {
468         off_t offset;
469         offset = ftello(fs->f);
470         /* subtract header size to get samples, then divide by 2 for 16 bit samples */
471         return (offset - 44)/2;
472 }
473
474 static const struct ast_format wav_f = {
475         .name = "wav",
476         .exts = "wav",
477         .format = AST_FORMAT_SLINEAR,
478         .open = wav_open,
479         .rewrite = wav_rewrite,
480         .write = wav_write,
481         .seek = wav_seek,
482         .trunc = wav_trunc,
483         .tell = wav_tell,
484         .read = wav_read,
485         .close = wav_close,
486         .buf_size = WAV_BUF_SIZE + AST_FRIENDLY_OFFSET,
487         .desc_size = sizeof(struct wav_desc),
488 };
489
490 static int load_module(void)
491 {
492         return ast_format_register(&wav_f);
493 }
494
495 static int unload_module(void)
496 {
497         return ast_format_unregister(wav_f.name);
498 }       
499
500 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Microsoft WAV format (8000Hz Signed Linear)");