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