Stop playing wav at end of data segment
[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 #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 Jeffery 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_channel *owner;
45         struct ast_frame fr;                            /* Frame information */
46         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
47         char empty;                                                     /* Empty character */
48         short buf[160]; 
49         int foffset;
50         int lasttimeout;
51         int maxlen;
52         struct timeval last;
53         int adj;
54         struct ast_filestream *next;
55 };
56
57
58 static struct ast_filestream *glist = NULL;
59 static pthread_mutex_t wav_lock = AST_MUTEX_INITIALIZER;
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         /* Begin data chunk */
181         if (read(fd, &data, 4) != 4) {
182                 ast_log(LOG_WARNING, "Read failed (data)\n");
183                 return -1;
184         }
185         if (memcmp(&data, "data", 4)) {
186                 ast_log(LOG_WARNING, "Does not say data\n");
187                 return -1;
188         }
189         /* Data has the actual length of data in it */
190         if (read(fd, &data, 4) != 4) {
191                 ast_log(LOG_WARNING, "Read failed (data)\n");
192                 return -1;
193         }
194 #if 0
195         curpos = lseek(fd, 0, SEEK_CUR);
196         truelength = lseek(fd, 0, SEEK_END);
197         lseek(fd, curpos, SEEK_SET);
198         truelength -= curpos;
199 #endif  
200         return ltohl(data);
201 }
202
203 static int update_header(int fd)
204 {
205         off_t cur,end;
206         int datalen,filelen,bytes;
207         
208         
209         cur = lseek(fd, 0, SEEK_CUR);
210         end = lseek(fd, 0, SEEK_END);
211         /* data starts 44 bytes in */
212         bytes = end - 44;
213         datalen = htoll(bytes);
214         /* chunk size is bytes of data plus 36 bytes of header */
215         filelen = htoll(36 + bytes);
216         
217         if (cur < 0) {
218                 ast_log(LOG_WARNING, "Unable to find our position\n");
219                 return -1;
220         }
221         if (lseek(fd, 4, SEEK_SET) != 4) {
222                 ast_log(LOG_WARNING, "Unable to set our position\n");
223                 return -1;
224         }
225         if (write(fd, &filelen, 4) != 4) {
226                 ast_log(LOG_WARNING, "Unable to set write file size\n");
227                 return -1;
228         }
229         if (lseek(fd, 40, SEEK_SET) != 40) {
230                 ast_log(LOG_WARNING, "Unable to set our position\n");
231                 return -1;
232         }
233         if (write(fd, &datalen, 4) != 4) {
234                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
235                 return -1;
236         }
237         if (lseek(fd, cur, SEEK_SET) != cur) {
238                 ast_log(LOG_WARNING, "Unable to return to position\n");
239                 return -1;
240         }
241         return 0;
242 }
243
244 static int write_header(int fd)
245 {
246         unsigned int hz=htoll(8000);
247         unsigned int bhz = htoll(16000);
248         unsigned int hs = htoll(16);
249         unsigned short fmt = htols(1);
250         unsigned short chans = htols(1);
251         unsigned short bysam = htols(2);
252         unsigned short bisam = htols(16);
253         unsigned int size = htoll(0);
254         /* Write a wav header, ignoring sizes which will be filled in later */
255         lseek(fd,0,SEEK_SET);
256         if (write(fd, "RIFF", 4) != 4) {
257                 ast_log(LOG_WARNING, "Unable to write header\n");
258                 return -1;
259         }
260         if (write(fd, &size, 4) != 4) {
261                 ast_log(LOG_WARNING, "Unable to write header\n");
262                 return -1;
263         }
264         if (write(fd, "WAVEfmt ", 8) != 8) {
265                 ast_log(LOG_WARNING, "Unable to write header\n");
266                 return -1;
267         }
268         if (write(fd, &hs, 4) != 4) {
269                 ast_log(LOG_WARNING, "Unable to write header\n");
270                 return -1;
271         }
272         if (write(fd, &fmt, 2) != 2) {
273                 ast_log(LOG_WARNING, "Unable to write header\n");
274                 return -1;
275         }
276         if (write(fd, &chans, 2) != 2) {
277                 ast_log(LOG_WARNING, "Unable to write header\n");
278                 return -1;
279         }
280         if (write(fd, &hz, 4) != 4) {
281                 ast_log(LOG_WARNING, "Unable to write header\n");
282                 return -1;
283         }
284         if (write(fd, &bhz, 4) != 4) {
285                 ast_log(LOG_WARNING, "Unable to write header\n");
286                 return -1;
287         }
288         if (write(fd, &bysam, 2) != 2) {
289                 ast_log(LOG_WARNING, "Unable to write header\n");
290                 return -1;
291         }
292         if (write(fd, &bisam, 2) != 2) {
293                 ast_log(LOG_WARNING, "Unable to write header\n");
294                 return -1;
295         }
296         if (write(fd, "data", 4) != 4) {
297                 ast_log(LOG_WARNING, "Unable to write header\n");
298                 return -1;
299         }
300         if (write(fd, &size, 4) != 4) {
301                 ast_log(LOG_WARNING, "Unable to write header\n");
302                 return -1;
303         }
304         return 0;
305 }
306
307 static struct ast_filestream *wav_open(int fd)
308 {
309         /* We don't have any header to read or anything really, but
310            if we did, it would go here.  We also might want to check
311            and be sure it's a valid file.  */
312         struct ast_filestream *tmp;
313         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
314                 memset(tmp, 0, sizeof(struct ast_filestream));
315                 if ((tmp->maxlen = check_header(fd)) < 0) {
316                         free(tmp);
317                         return NULL;
318                 }
319                 if (ast_pthread_mutex_lock(&wav_lock)) {
320                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
321                         free(tmp);
322                         return NULL;
323                 }
324                 tmp->next = glist;
325                 glist = tmp;
326                 tmp->fd = fd;
327                 tmp->owner = NULL;
328                 tmp->needsgain = 1;
329                 tmp->fr.data = tmp->buf;
330                 tmp->fr.frametype = AST_FRAME_VOICE;
331                 tmp->fr.subclass = AST_FORMAT_SLINEAR;
332                 /* datalen will vary for each frame */
333                 tmp->fr.src = name;
334                 tmp->fr.mallocd = 0;
335                 tmp->lasttimeout = -1;
336                 tmp->bytes = 0;
337                 glistcnt++;
338                 ast_pthread_mutex_unlock(&wav_lock);
339                 ast_update_use_count();
340         }
341         return tmp;
342 }
343
344 static struct ast_filestream *wav_rewrite(int fd, char *comment)
345 {
346         /* We don't have any header to read or anything really, but
347            if we did, it would go here.  We also might want to check
348            and be sure it's a valid file.  */
349         struct ast_filestream *tmp;
350         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
351                 memset(tmp, 0, sizeof(struct ast_filestream));
352                 if (write_header(fd)) {
353                         free(tmp);
354                         return NULL;
355                 }
356                 if (ast_pthread_mutex_lock(&wav_lock)) {
357                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
358                         free(tmp);
359                         return NULL;
360                 }
361                 tmp->next = glist;
362                 glist = tmp;
363                 tmp->fd = fd;
364                 tmp->owner = NULL;
365                 tmp->lasttimeout = -1;
366                 glistcnt++;
367                 ast_pthread_mutex_unlock(&wav_lock);
368                 ast_update_use_count();
369         } else
370                 ast_log(LOG_WARNING, "Out of memory\n");
371         return tmp;
372 }
373
374 static struct ast_frame *wav_read(struct ast_filestream *s)
375 {
376         return NULL;
377 }
378
379 static void wav_close(struct ast_filestream *s)
380 {
381         struct ast_filestream *tmp, *tmpl = NULL;
382         char zero = 0;
383         if (ast_pthread_mutex_lock(&wav_lock)) {
384                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
385                 return;
386         }
387         tmp = glist;
388         while(tmp) {
389                 if (tmp == s) {
390                         if (tmpl)
391                                 tmpl->next = tmp->next;
392                         else
393                                 glist = tmp->next;
394                         break;
395                 }
396                 tmpl = tmp;
397                 tmp = tmp->next;
398         }
399         glistcnt--;
400         if (s->owner) {
401                 s->owner->stream = NULL;
402                 if (s->owner->streamid > -1)
403                         ast_sched_del(s->owner->sched, s->owner->streamid);
404                 s->owner->streamid = -1;
405         }
406         ast_pthread_mutex_unlock(&wav_lock);
407         ast_update_use_count();
408         if (!tmp) 
409                 ast_log(LOG_WARNING, "Freeing a filestream we don't seem to own\n");
410         /* Pad to even length */
411         if (s->bytes & 0x1)
412                 write(s->fd, &zero, 1);
413         close(s->fd);
414         free(s);
415         s = NULL;
416 #if 0
417         printf("bytes = %d\n", s->bytes);
418 #endif
419 }
420
421 static int ast_read_callback(void *data)
422 {
423         int retval = 0;
424         int res;
425         int delay;
426         int x;
427         struct ast_filestream *s = data;
428         short tmp[sizeof(s->buf) / 2];
429         int bytes = sizeof(tmp);
430         off_t here;
431         /* Send a frame from the file to the appropriate channel */
432         here = lseek(s->fd, 0, SEEK_CUR);
433         if ((s->maxlen - here) < bytes)
434                 bytes = s->maxlen - here;
435         if (bytes < 0)
436                 bytes = 0;
437 /*      ast_log(LOG_DEBUG, "here: %d, maxlen: %d, bytes: %d\n", here, s->maxlen, bytes); */
438         
439         if ( (res = read(s->fd, tmp, bytes)) <= 0 ) {
440                 if (res) {
441                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
442                 }
443                 s->owner->streamid = -1;
444                 return 0;
445         }
446
447 #if __BYTE_ORDER == __BIG_ENDIAN
448         for( x = 0; x < sizeof(tmp)/2; x++) tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
449 #endif
450
451         if (s->needsgain) {
452                 for (x=0;x<sizeof(tmp)/2;x++)
453                         if (tmp[x] & ((1 << GAIN) - 1)) {
454                                 /* If it has data down low, then it's not something we've artificially increased gain
455                                    on, so we don't need to gain adjust it */
456                                 s->needsgain = 0;
457                         }
458         }
459         if (s->needsgain) {
460                 for (x=0;x<sizeof(tmp)/2;x++) {
461                         s->buf[x] = tmp[x] >> GAIN;
462                 }
463         } else {
464                 memcpy(s->buf, tmp, sizeof(s->buf));
465         }
466                         
467         delay = res / 2;
468         s->fr.frametype = AST_FRAME_VOICE;
469         s->fr.subclass = AST_FORMAT_SLINEAR;
470         s->fr.offset = AST_FRIENDLY_OFFSET;
471         s->fr.datalen = res;
472         s->fr.data = s->buf;
473         s->fr.mallocd = 0;
474         s->fr.samples = delay;
475         delay /= 8;
476         /* Lastly, process the frame */ 
477         if (delay != s->lasttimeout) {
478                 s->owner->streamid = ast_sched_add(s->owner->sched, delay, ast_read_callback, s);
479                 s->lasttimeout = delay;
480         } else {
481                 retval = -1;
482         }
483         
484         
485         if (ast_write(s->owner, &s->fr)) {
486                 ast_log(LOG_WARNING, "Failed to write frame\n");
487                 s->owner->streamid = -1;
488                 return 0;
489         }
490         
491         return retval;
492 }
493
494 static int wav_apply(struct ast_channel *c, struct ast_filestream *s)
495 {
496         /* Select our owner for this stream, and get the ball rolling. */
497         s->owner = c;
498         return 0;
499 }
500
501 static int wav_play(struct ast_filestream *s)
502 {
503         ast_read_callback(s);
504         return 0;
505 }
506
507 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
508 {
509         int res = 0;
510         int x;
511         short tmp[8000], *tmpi;
512         float tmpf;
513         if (f->frametype != AST_FRAME_VOICE) {
514                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
515                 return -1;
516         }
517         if (f->subclass != AST_FORMAT_SLINEAR) {
518                 ast_log(LOG_WARNING, "Asked to write non-SLINEAR frame (%d)!\n", f->subclass);
519                 return -1;
520         }
521         if (f->datalen > sizeof(tmp)) {
522                 ast_log(LOG_WARNING, "Data length is too long\n");
523                 return -1;
524         }
525         if (!f->datalen)
526                 return -1;
527
528 #if 0
529         printf("Data Length: %d\n", f->datalen);
530 #endif  
531
532         if (fs->buf) {
533                 tmpi = f->data;
534                 /* Volume adjust here to accomodate */
535                 for (x=0;x<f->datalen/2;x++) {
536                         tmpf = ((float)tmpi[x]) * ((float)(1 << GAIN));
537                         if (tmpf > 32767.0)
538                                 tmpf = 32767.0;
539                         if (tmpf < -32768.0)
540                                 tmpf = -32768.0;
541                         tmp[x] = tmpf;
542                         tmp[x] &= ~((1 << GAIN) - 1);
543
544 #if __BYTE_ORDER == __BIG_ENDIAN
545                         tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
546 #endif
547
548                 }
549                 if ((write (fs->fd, tmp, f->datalen) != f->datalen) ) {
550                         ast_log(LOG_WARNING, "Bad write (%d): %s\n", res, strerror(errno));
551                         return -1;
552                 }
553         } else {
554                 ast_log(LOG_WARNING, "Cannot write data to file.\n");
555                 return -1;
556         }
557         
558         fs->bytes += f->datalen;
559         update_header(fs->fd);
560                 
561         return 0;
562
563 }
564
565 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
566 {
567         off_t min,max,cur;
568         long offset=0,samples;
569         
570         samples = sample_offset * 2; /* SLINEAR is 16 bits mono, so sample_offset * 2 = bytes */
571         min = 44; /* wav header is 44 bytes */
572         cur = lseek(fs->fd, 0, SEEK_CUR);
573         max = lseek(fs->fd, 0, SEEK_END);
574         if(whence == SEEK_SET)
575                 offset = samples + min;
576         if(whence == SEEK_CUR)
577                 offset = samples + cur;
578         if(whence == SEEK_END)
579                 offset = max - samples; 
580         offset = (offset > max)?max:offset;
581         offset = (offset < min)?min:offset;
582         return lseek(fs->fd,offset,SEEK_SET);
583 }
584
585 static int wav_trunc(struct ast_filestream *fs)
586 {
587         if(ftruncate(fs->fd, lseek(fs->fd,0,SEEK_CUR)))
588                 return -1;
589         return update_header(fs->fd);
590 }
591
592 static long wav_tell(struct ast_filestream *fs)
593 {
594         off_t offset;
595         offset = lseek(fs->fd, 0, SEEK_CUR);
596         /* subtract header size to get samples, then divide by 2 for 16 bit samples */
597         return (offset - 44)/2;
598 }
599
600 static char *wav_getcomment(struct ast_filestream *s)
601 {
602         return NULL;
603 }
604
605 int load_module()
606 {
607         return ast_format_register(name, exts, AST_FORMAT_SLINEAR,
608                                                                 wav_open,
609                                                                 wav_rewrite,
610                                                                 wav_apply,
611                                                                 wav_play,
612                                                                 wav_write,
613                                                                 wav_seek,
614                                                                 wav_trunc,
615                                                                 wav_tell,
616                                                                 wav_read,
617                                                                 wav_close,
618                                                                 wav_getcomment);
619                                                                 
620                                                                 
621 }
622
623 int unload_module()
624 {
625         struct ast_filestream *tmp, *tmpl;
626         if (ast_pthread_mutex_lock(&wav_lock)) {
627                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
628                 return -1;
629         }
630         tmp = glist;
631         while(tmp) {
632                 if (tmp->owner)
633                         ast_softhangup(tmp->owner, AST_SOFTHANGUP_APPUNLOAD);
634                 tmpl = tmp;
635                 tmp = tmp->next;
636                 free(tmpl);
637         }
638         ast_pthread_mutex_unlock(&wav_lock);
639         return ast_format_unregister(name);
640 }       
641
642 int usecount()
643 {
644         int res;
645         if (ast_pthread_mutex_lock(&wav_lock)) {
646                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
647                 return -1;
648         }
649         res = glistcnt;
650         ast_pthread_mutex_unlock(&wav_lock);
651         return res;
652 }
653
654 char *description()
655 {
656         return desc;
657 }
658
659
660 char *key()
661 {
662         return ASTERISK_GPL_KEY;
663 }