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