update MANY more files with proper copyright/license info (thanks Ian!)
[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 /*
20  *
21  * Work with WAV in the proprietary Microsoft format.
22  * 
23  */
24  
25 #include <unistd.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 #include <stdlib.h>
29 #include <sys/time.h>
30 #include <stdio.h>
31 #include <errno.h>
32 #include <string.h>
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/lock.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/file.h"
41 #include "asterisk/logger.h"
42 #include "asterisk/sched.h"
43 #include "asterisk/module.h"
44 #include "asterisk/endian.h"
45
46 /* Some Ideas for this code came from makewave.c by Jeffrey Chilton */
47
48 /* Portions of the conversion code are by guido@sienanet.it */
49
50 struct ast_filestream {
51         void *reserved[AST_RESERVED_POINTERS];
52         /* This is what a filestream means to us */
53         int fd; /* Descriptor */
54         int bytes;
55         int needsgain;
56         struct ast_frame fr;                            /* Frame information */
57         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
58         char empty;                                                     /* Empty character */
59         short buf[160]; 
60         int foffset;
61         int lasttimeout;
62         int maxlen;
63         struct timeval last;
64 };
65
66
67 AST_MUTEX_DEFINE_STATIC(wav_lock);
68 static int glistcnt = 0;
69
70 static char *name = "wav";
71 static char *desc = "Microsoft WAV format (8000hz Signed Linear)";
72 static char *exts = "wav";
73
74 #define BLOCKSIZE 160
75
76 #define GAIN 2          /* 2^GAIN is the multiple to increase the volume by */
77
78 #if __BYTE_ORDER == __LITTLE_ENDIAN
79 #define htoll(b) (b)
80 #define htols(b) (b)
81 #define ltohl(b) (b)
82 #define ltohs(b) (b)
83 #else
84 #if __BYTE_ORDER == __BIG_ENDIAN
85 #define htoll(b)  \
86           (((((b)      ) & 0xFF) << 24) | \
87                ((((b) >>  8) & 0xFF) << 16) | \
88                    ((((b) >> 16) & 0xFF) <<  8) | \
89                    ((((b) >> 24) & 0xFF)      ))
90 #define htols(b) \
91           (((((b)      ) & 0xFF) << 8) | \
92                    ((((b) >> 8) & 0xFF)      ))
93 #define ltohl(b) htoll(b)
94 #define ltohs(b) htols(b)
95 #else
96 #error "Endianess not defined"
97 #endif
98 #endif
99
100
101 static int check_header(int fd)
102 {
103         int type, size, formtype;
104         int fmt, hsize;
105         short format, chans, bysam, bisam;
106         int bysec;
107         int freq;
108         int data;
109         if (read(fd, &type, 4) != 4) {
110                 ast_log(LOG_WARNING, "Read failed (type)\n");
111                 return -1;
112         }
113         if (read(fd, &size, 4) != 4) {
114                 ast_log(LOG_WARNING, "Read failed (size)\n");
115                 return -1;
116         }
117         size = ltohl(size);
118         if (read(fd, &formtype, 4) != 4) {
119                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
120                 return -1;
121         }
122         if (memcmp(&type, "RIFF", 4)) {
123                 ast_log(LOG_WARNING, "Does not begin with RIFF\n");
124                 return -1;
125         }
126         if (memcmp(&formtype, "WAVE", 4)) {
127                 ast_log(LOG_WARNING, "Does not contain WAVE\n");
128                 return -1;
129         }
130         if (read(fd, &fmt, 4) != 4) {
131                 ast_log(LOG_WARNING, "Read failed (fmt)\n");
132                 return -1;
133         }
134         if (memcmp(&fmt, "fmt ", 4)) {
135                 ast_log(LOG_WARNING, "Does not say fmt\n");
136                 return -1;
137         }
138         if (read(fd, &hsize, 4) != 4) {
139                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
140                 return -1;
141         }
142         if (ltohl(hsize) < 16) {
143                 ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
144                 return -1;
145         }
146         if (read(fd, &format, 2) != 2) {
147                 ast_log(LOG_WARNING, "Read failed (format)\n");
148                 return -1;
149         }
150         if (ltohs(format) != 1) {
151                 ast_log(LOG_WARNING, "Not a wav file %d\n", ltohs(format));
152                 return -1;
153         }
154         if (read(fd, &chans, 2) != 2) {
155                 ast_log(LOG_WARNING, "Read failed (format)\n");
156                 return -1;
157         }
158         if (ltohs(chans) != 1) {
159                 ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
160                 return -1;
161         }
162         if (read(fd, &freq, 4) != 4) {
163                 ast_log(LOG_WARNING, "Read failed (freq)\n");
164                 return -1;
165         }
166         if (ltohl(freq) != 8000) {
167                 ast_log(LOG_WARNING, "Unexpected freqency %d\n", ltohl(freq));
168                 return -1;
169         }
170         /* Ignore the byte frequency */
171         if (read(fd, &bysec, 4) != 4) {
172                 ast_log(LOG_WARNING, "Read failed (BYTES_PER_SECOND)\n");
173                 return -1;
174         }
175         /* Check bytes per sample */
176         if (read(fd, &bysam, 2) != 2) {
177                 ast_log(LOG_WARNING, "Read failed (BYTES_PER_SAMPLE)\n");
178                 return -1;
179         }
180         if (ltohs(bysam) != 2) {
181                 ast_log(LOG_WARNING, "Can only handle 16bits per sample: %d\n", ltohs(bysam));
182                 return -1;
183         }
184         if (read(fd, &bisam, 2) != 2) {
185                 ast_log(LOG_WARNING, "Read failed (Bits Per Sample): %d\n", ltohs(bisam));
186                 return -1;
187         }
188         /* Skip any additional header */
189         if ( lseek(fd,ltohl(hsize)-16,SEEK_CUR) == -1 ) {
190                 ast_log(LOG_WARNING, "Failed to skip remaining header bytes: %d\n", ltohl(hsize)-16 );
191                 return -1;
192         }
193         /* Skip any facts and get the first data block */
194         for(;;)
195         { 
196             char buf[4];
197             
198             /* Begin data chunk */
199             if (read(fd, &buf, 4) != 4) {
200                 ast_log(LOG_WARNING, "Read failed (data)\n");
201                 return -1;
202             }
203             /* Data has the actual length of data in it */
204             if (read(fd, &data, 4) != 4) {
205                 ast_log(LOG_WARNING, "Read failed (data)\n");
206                 return -1;
207             }
208             data = ltohl(data);
209             if( memcmp(buf, "data", 4) == 0 ) break;
210             if( memcmp(buf, "fact", 4) != 0 ) {
211                 ast_log(LOG_WARNING, "Unknown block - not fact or data\n");
212                 return -1;
213             }
214             if ( lseek(fd,data,SEEK_CUR) == -1 ) {
215                 ast_log(LOG_WARNING, "Failed to skip fact block: %d\n", data );
216                 return -1;
217             }
218         }
219 #if 0
220         curpos = lseek(fd, 0, SEEK_CUR);
221         truelength = lseek(fd, 0, SEEK_END);
222         lseek(fd, curpos, SEEK_SET);
223         truelength -= curpos;
224 #endif  
225         return data;
226 }
227
228 static int update_header(int fd)
229 {
230         off_t cur,end;
231         int datalen,filelen,bytes;
232         
233         
234         cur = lseek(fd, 0, SEEK_CUR);
235         end = lseek(fd, 0, SEEK_END);
236         /* data starts 44 bytes in */
237         bytes = end - 44;
238         datalen = htoll(bytes);
239         /* chunk size is bytes of data plus 36 bytes of header */
240         filelen = htoll(36 + bytes);
241         
242         if (cur < 0) {
243                 ast_log(LOG_WARNING, "Unable to find our position\n");
244                 return -1;
245         }
246         if (lseek(fd, 4, SEEK_SET) != 4) {
247                 ast_log(LOG_WARNING, "Unable to set our position\n");
248                 return -1;
249         }
250         if (write(fd, &filelen, 4) != 4) {
251                 ast_log(LOG_WARNING, "Unable to set write file size\n");
252                 return -1;
253         }
254         if (lseek(fd, 40, SEEK_SET) != 40) {
255                 ast_log(LOG_WARNING, "Unable to set our position\n");
256                 return -1;
257         }
258         if (write(fd, &datalen, 4) != 4) {
259                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
260                 return -1;
261         }
262         if (lseek(fd, cur, SEEK_SET) != cur) {
263                 ast_log(LOG_WARNING, "Unable to return to position\n");
264                 return -1;
265         }
266         return 0;
267 }
268
269 static int write_header(int fd)
270 {
271         unsigned int hz=htoll(8000);
272         unsigned int bhz = htoll(16000);
273         unsigned int hs = htoll(16);
274         unsigned short fmt = htols(1);
275         unsigned short chans = htols(1);
276         unsigned short bysam = htols(2);
277         unsigned short bisam = htols(16);
278         unsigned int size = htoll(0);
279         /* Write a wav header, ignoring sizes which will be filled in later */
280         lseek(fd,0,SEEK_SET);
281         if (write(fd, "RIFF", 4) != 4) {
282                 ast_log(LOG_WARNING, "Unable to write header\n");
283                 return -1;
284         }
285         if (write(fd, &size, 4) != 4) {
286                 ast_log(LOG_WARNING, "Unable to write header\n");
287                 return -1;
288         }
289         if (write(fd, "WAVEfmt ", 8) != 8) {
290                 ast_log(LOG_WARNING, "Unable to write header\n");
291                 return -1;
292         }
293         if (write(fd, &hs, 4) != 4) {
294                 ast_log(LOG_WARNING, "Unable to write header\n");
295                 return -1;
296         }
297         if (write(fd, &fmt, 2) != 2) {
298                 ast_log(LOG_WARNING, "Unable to write header\n");
299                 return -1;
300         }
301         if (write(fd, &chans, 2) != 2) {
302                 ast_log(LOG_WARNING, "Unable to write header\n");
303                 return -1;
304         }
305         if (write(fd, &hz, 4) != 4) {
306                 ast_log(LOG_WARNING, "Unable to write header\n");
307                 return -1;
308         }
309         if (write(fd, &bhz, 4) != 4) {
310                 ast_log(LOG_WARNING, "Unable to write header\n");
311                 return -1;
312         }
313         if (write(fd, &bysam, 2) != 2) {
314                 ast_log(LOG_WARNING, "Unable to write header\n");
315                 return -1;
316         }
317         if (write(fd, &bisam, 2) != 2) {
318                 ast_log(LOG_WARNING, "Unable to write header\n");
319                 return -1;
320         }
321         if (write(fd, "data", 4) != 4) {
322                 ast_log(LOG_WARNING, "Unable to write header\n");
323                 return -1;
324         }
325         if (write(fd, &size, 4) != 4) {
326                 ast_log(LOG_WARNING, "Unable to write header\n");
327                 return -1;
328         }
329         return 0;
330 }
331
332 static struct ast_filestream *wav_open(int fd)
333 {
334         /* We don't have any header to read or anything really, but
335            if we did, it would go here.  We also might want to check
336            and be sure it's a valid file.  */
337         struct ast_filestream *tmp;
338         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
339                 memset(tmp, 0, sizeof(struct ast_filestream));
340                 if ((tmp->maxlen = check_header(fd)) < 0) {
341                         free(tmp);
342                         return NULL;
343                 }
344                 if (ast_mutex_lock(&wav_lock)) {
345                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
346                         free(tmp);
347                         return NULL;
348                 }
349                 tmp->fd = fd;
350                 tmp->needsgain = 1;
351                 tmp->fr.data = tmp->buf;
352                 tmp->fr.frametype = AST_FRAME_VOICE;
353                 tmp->fr.subclass = AST_FORMAT_SLINEAR;
354                 /* datalen will vary for each frame */
355                 tmp->fr.src = name;
356                 tmp->fr.mallocd = 0;
357                 tmp->bytes = 0;
358                 glistcnt++;
359                 ast_mutex_unlock(&wav_lock);
360                 ast_update_use_count();
361         }
362         return tmp;
363 }
364
365 static struct ast_filestream *wav_rewrite(int fd, const char *comment)
366 {
367         /* We don't have any header to read or anything really, but
368            if we did, it would go here.  We also might want to check
369            and be sure it's a valid file.  */
370         struct ast_filestream *tmp;
371         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
372                 memset(tmp, 0, sizeof(struct ast_filestream));
373                 if (write_header(fd)) {
374                         free(tmp);
375                         return NULL;
376                 }
377                 if (ast_mutex_lock(&wav_lock)) {
378                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
379                         free(tmp);
380                         return NULL;
381                 }
382                 tmp->fd = fd;
383                 glistcnt++;
384                 ast_mutex_unlock(&wav_lock);
385                 ast_update_use_count();
386         } else
387                 ast_log(LOG_WARNING, "Out of memory\n");
388         return tmp;
389 }
390
391 static void wav_close(struct ast_filestream *s)
392 {
393         char zero = 0;
394         if (ast_mutex_lock(&wav_lock)) {
395                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
396                 return;
397         }
398         glistcnt--;
399         ast_mutex_unlock(&wav_lock);
400         ast_update_use_count();
401         /* Pad to even length */
402         if (s->bytes & 0x1)
403                 write(s->fd, &zero, 1);
404         close(s->fd);
405         free(s);
406         s = NULL;
407 }
408
409 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
410 {
411         int res;
412         int delay;
413         int x;
414         short tmp[sizeof(s->buf) / 2];
415         int bytes = sizeof(tmp);
416         off_t here;
417         /* Send a frame from the file to the appropriate channel */
418         here = lseek(s->fd, 0, SEEK_CUR);
419         if ((s->maxlen - here) < bytes)
420                 bytes = s->maxlen - here;
421         if (bytes < 0)
422                 bytes = 0;
423 /*      ast_log(LOG_DEBUG, "here: %d, maxlen: %d, bytes: %d\n", here, s->maxlen, bytes); */
424         
425         if ( (res = read(s->fd, tmp, bytes)) <= 0 ) {
426                 if (res) {
427                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
428                 }
429                 return NULL;
430         }
431
432 #if __BYTE_ORDER == __BIG_ENDIAN
433         for( x = 0; x < sizeof(tmp)/2; x++) tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
434 #endif
435
436         if (s->needsgain) {
437                 for (x=0;x<sizeof(tmp)/2;x++)
438                         if (tmp[x] & ((1 << GAIN) - 1)) {
439                                 /* If it has data down low, then it's not something we've artificially increased gain
440                                    on, so we don't need to gain adjust it */
441                                 s->needsgain = 0;
442                         }
443         }
444         if (s->needsgain) {
445                 for (x=0;x<sizeof(tmp)/2;x++) {
446                         s->buf[x] = tmp[x] >> GAIN;
447                 }
448         } else {
449                 memcpy(s->buf, tmp, sizeof(s->buf));
450         }
451                         
452         delay = res / 2;
453         s->fr.frametype = AST_FRAME_VOICE;
454         s->fr.subclass = AST_FORMAT_SLINEAR;
455         s->fr.offset = AST_FRIENDLY_OFFSET;
456         s->fr.datalen = res;
457         s->fr.data = s->buf;
458         s->fr.mallocd = 0;
459         s->fr.samples = delay;
460         *whennext = delay;
461         return &s->fr;
462 }
463
464 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
465 {
466         int res = 0;
467         int x;
468         short tmp[8000], *tmpi;
469         float tmpf;
470         if (f->frametype != AST_FRAME_VOICE) {
471                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
472                 return -1;
473         }
474         if (f->subclass != AST_FORMAT_SLINEAR) {
475                 ast_log(LOG_WARNING, "Asked to write non-SLINEAR frame (%d)!\n", f->subclass);
476                 return -1;
477         }
478         if (f->datalen > sizeof(tmp)) {
479                 ast_log(LOG_WARNING, "Data length is too long\n");
480                 return -1;
481         }
482         if (!f->datalen)
483                 return -1;
484
485 #if 0
486         printf("Data Length: %d\n", f->datalen);
487 #endif  
488
489         if (fs->buf) {
490                 tmpi = f->data;
491                 /* Volume adjust here to accomodate */
492                 for (x=0;x<f->datalen/2;x++) {
493                         tmpf = ((float)tmpi[x]) * ((float)(1 << GAIN));
494                         if (tmpf > 32767.0)
495                                 tmpf = 32767.0;
496                         if (tmpf < -32768.0)
497                                 tmpf = -32768.0;
498                         tmp[x] = tmpf;
499                         tmp[x] &= ~((1 << GAIN) - 1);
500
501 #if __BYTE_ORDER == __BIG_ENDIAN
502                         tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
503 #endif
504
505                 }
506                 if ((write (fs->fd, tmp, f->datalen) != f->datalen) ) {
507                         ast_log(LOG_WARNING, "Bad write (%d): %s\n", res, strerror(errno));
508                         return -1;
509                 }
510         } else {
511                 ast_log(LOG_WARNING, "Cannot write data to file.\n");
512                 return -1;
513         }
514         
515         fs->bytes += f->datalen;
516         update_header(fs->fd);
517                 
518         return 0;
519
520 }
521
522 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
523 {
524         off_t min,max,cur;
525         long offset=0,samples;
526         
527         samples = sample_offset * 2; /* SLINEAR is 16 bits mono, so sample_offset * 2 = bytes */
528         min = 44; /* wav header is 44 bytes */
529         cur = lseek(fs->fd, 0, SEEK_CUR);
530         max = lseek(fs->fd, 0, SEEK_END);
531         if (whence == SEEK_SET)
532                 offset = samples + min;
533         else if (whence == SEEK_CUR || whence == SEEK_FORCECUR)
534                 offset = samples + cur;
535         else if (whence == SEEK_END)
536                 offset = max - samples;
537         if (whence != SEEK_FORCECUR) {
538                 offset = (offset > max)?max:offset;
539         }
540         /* always protect the header space. */
541         offset = (offset < min)?min:offset;
542         return lseek(fs->fd,offset,SEEK_SET);
543 }
544
545 static int wav_trunc(struct ast_filestream *fs)
546 {
547         if(ftruncate(fs->fd, lseek(fs->fd,0,SEEK_CUR)))
548                 return -1;
549         return update_header(fs->fd);
550 }
551
552 static long wav_tell(struct ast_filestream *fs)
553 {
554         off_t offset;
555         offset = lseek(fs->fd, 0, SEEK_CUR);
556         /* subtract header size to get samples, then divide by 2 for 16 bit samples */
557         return (offset - 44)/2;
558 }
559
560 static char *wav_getcomment(struct ast_filestream *s)
561 {
562         return NULL;
563 }
564
565 int load_module()
566 {
567         return ast_format_register(name, exts, AST_FORMAT_SLINEAR,
568                                                                 wav_open,
569                                                                 wav_rewrite,
570                                                                 wav_write,
571                                                                 wav_seek,
572                                                                 wav_trunc,
573                                                                 wav_tell,
574                                                                 wav_read,
575                                                                 wav_close,
576                                                                 wav_getcomment);
577                                                                 
578                                                                 
579 }
580
581 int unload_module()
582 {
583         return ast_format_unregister(name);
584 }       
585
586 int usecount()
587 {
588         return glistcnt;
589 }
590
591 char *description()
592 {
593         return desc;
594 }
595
596
597 char *key()
598 {
599         return ASTERISK_GPL_KEY;
600 }