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