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