Fix synchronization of recorded files when using Monitor application
[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_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 static ast_mutex_t wav_lock = AST_MUTEX_INITIALIZER;
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         /* Begin data chunk */
177         if (read(fd, &data, 4) != 4) {
178                 ast_log(LOG_WARNING, "Read failed (data)\n");
179                 return -1;
180         }
181         if (memcmp(&data, "data", 4)) {
182                 ast_log(LOG_WARNING, "Does not say data\n");
183                 return -1;
184         }
185         /* Data has the actual length of data in it */
186         if (read(fd, &data, 4) != 4) {
187                 ast_log(LOG_WARNING, "Read failed (data)\n");
188                 return -1;
189         }
190 #if 0
191         curpos = lseek(fd, 0, SEEK_CUR);
192         truelength = lseek(fd, 0, SEEK_END);
193         lseek(fd, curpos, SEEK_SET);
194         truelength -= curpos;
195 #endif  
196         return ltohl(data);
197 }
198
199 static int update_header(int fd)
200 {
201         off_t cur,end;
202         int datalen,filelen,bytes;
203         
204         
205         cur = lseek(fd, 0, SEEK_CUR);
206         end = lseek(fd, 0, SEEK_END);
207         /* data starts 44 bytes in */
208         bytes = end - 44;
209         datalen = htoll(bytes);
210         /* chunk size is bytes of data plus 36 bytes of header */
211         filelen = htoll(36 + bytes);
212         
213         if (cur < 0) {
214                 ast_log(LOG_WARNING, "Unable to find our position\n");
215                 return -1;
216         }
217         if (lseek(fd, 4, SEEK_SET) != 4) {
218                 ast_log(LOG_WARNING, "Unable to set our position\n");
219                 return -1;
220         }
221         if (write(fd, &filelen, 4) != 4) {
222                 ast_log(LOG_WARNING, "Unable to set write file size\n");
223                 return -1;
224         }
225         if (lseek(fd, 40, SEEK_SET) != 40) {
226                 ast_log(LOG_WARNING, "Unable to set our position\n");
227                 return -1;
228         }
229         if (write(fd, &datalen, 4) != 4) {
230                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
231                 return -1;
232         }
233         if (lseek(fd, cur, SEEK_SET) != cur) {
234                 ast_log(LOG_WARNING, "Unable to return to position\n");
235                 return -1;
236         }
237         return 0;
238 }
239
240 static int write_header(int fd)
241 {
242         unsigned int hz=htoll(8000);
243         unsigned int bhz = htoll(16000);
244         unsigned int hs = htoll(16);
245         unsigned short fmt = htols(1);
246         unsigned short chans = htols(1);
247         unsigned short bysam = htols(2);
248         unsigned short bisam = htols(16);
249         unsigned int size = htoll(0);
250         /* Write a wav header, ignoring sizes which will be filled in later */
251         lseek(fd,0,SEEK_SET);
252         if (write(fd, "RIFF", 4) != 4) {
253                 ast_log(LOG_WARNING, "Unable to write header\n");
254                 return -1;
255         }
256         if (write(fd, &size, 4) != 4) {
257                 ast_log(LOG_WARNING, "Unable to write header\n");
258                 return -1;
259         }
260         if (write(fd, "WAVEfmt ", 8) != 8) {
261                 ast_log(LOG_WARNING, "Unable to write header\n");
262                 return -1;
263         }
264         if (write(fd, &hs, 4) != 4) {
265                 ast_log(LOG_WARNING, "Unable to write header\n");
266                 return -1;
267         }
268         if (write(fd, &fmt, 2) != 2) {
269                 ast_log(LOG_WARNING, "Unable to write header\n");
270                 return -1;
271         }
272         if (write(fd, &chans, 2) != 2) {
273                 ast_log(LOG_WARNING, "Unable to write header\n");
274                 return -1;
275         }
276         if (write(fd, &hz, 4) != 4) {
277                 ast_log(LOG_WARNING, "Unable to write header\n");
278                 return -1;
279         }
280         if (write(fd, &bhz, 4) != 4) {
281                 ast_log(LOG_WARNING, "Unable to write header\n");
282                 return -1;
283         }
284         if (write(fd, &bysam, 2) != 2) {
285                 ast_log(LOG_WARNING, "Unable to write header\n");
286                 return -1;
287         }
288         if (write(fd, &bisam, 2) != 2) {
289                 ast_log(LOG_WARNING, "Unable to write header\n");
290                 return -1;
291         }
292         if (write(fd, "data", 4) != 4) {
293                 ast_log(LOG_WARNING, "Unable to write header\n");
294                 return -1;
295         }
296         if (write(fd, &size, 4) != 4) {
297                 ast_log(LOG_WARNING, "Unable to write header\n");
298                 return -1;
299         }
300         return 0;
301 }
302
303 static struct ast_filestream *wav_open(int fd)
304 {
305         /* We don't have any header to read or anything really, but
306            if we did, it would go here.  We also might want to check
307            and be sure it's a valid file.  */
308         struct ast_filestream *tmp;
309         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
310                 memset(tmp, 0, sizeof(struct ast_filestream));
311                 if ((tmp->maxlen = check_header(fd)) < 0) {
312                         free(tmp);
313                         return NULL;
314                 }
315                 if (ast_mutex_lock(&wav_lock)) {
316                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
317                         free(tmp);
318                         return NULL;
319                 }
320                 tmp->fd = fd;
321                 tmp->needsgain = 1;
322                 tmp->fr.data = tmp->buf;
323                 tmp->fr.frametype = AST_FRAME_VOICE;
324                 tmp->fr.subclass = AST_FORMAT_SLINEAR;
325                 /* datalen will vary for each frame */
326                 tmp->fr.src = name;
327                 tmp->fr.mallocd = 0;
328                 tmp->bytes = 0;
329                 glistcnt++;
330                 ast_mutex_unlock(&wav_lock);
331                 ast_update_use_count();
332         }
333         return tmp;
334 }
335
336 static struct ast_filestream *wav_rewrite(int fd, char *comment)
337 {
338         /* We don't have any header to read or anything really, but
339            if we did, it would go here.  We also might want to check
340            and be sure it's a valid file.  */
341         struct ast_filestream *tmp;
342         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
343                 memset(tmp, 0, sizeof(struct ast_filestream));
344                 if (write_header(fd)) {
345                         free(tmp);
346                         return NULL;
347                 }
348                 if (ast_mutex_lock(&wav_lock)) {
349                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
350                         free(tmp);
351                         return NULL;
352                 }
353                 tmp->fd = fd;
354                 glistcnt++;
355                 ast_mutex_unlock(&wav_lock);
356                 ast_update_use_count();
357         } else
358                 ast_log(LOG_WARNING, "Out of memory\n");
359         return tmp;
360 }
361
362 static void wav_close(struct ast_filestream *s)
363 {
364         char zero = 0;
365         if (ast_mutex_lock(&wav_lock)) {
366                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
367                 return;
368         }
369         glistcnt--;
370         ast_mutex_unlock(&wav_lock);
371         ast_update_use_count();
372         /* Pad to even length */
373         if (s->bytes & 0x1)
374                 write(s->fd, &zero, 1);
375         close(s->fd);
376         free(s);
377         s = NULL;
378 }
379
380 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
381 {
382         int res;
383         int delay;
384         int x;
385         short tmp[sizeof(s->buf) / 2];
386         int bytes = sizeof(tmp);
387         off_t here;
388         /* Send a frame from the file to the appropriate channel */
389         here = lseek(s->fd, 0, SEEK_CUR);
390         if ((s->maxlen - here) < bytes)
391                 bytes = s->maxlen - here;
392         if (bytes < 0)
393                 bytes = 0;
394 /*      ast_log(LOG_DEBUG, "here: %d, maxlen: %d, bytes: %d\n", here, s->maxlen, bytes); */
395         
396         if ( (res = read(s->fd, tmp, bytes)) <= 0 ) {
397                 if (res) {
398                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
399                 }
400                 return NULL;
401         }
402
403 #if __BYTE_ORDER == __BIG_ENDIAN
404         for( x = 0; x < sizeof(tmp)/2; x++) tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
405 #endif
406
407         if (s->needsgain) {
408                 for (x=0;x<sizeof(tmp)/2;x++)
409                         if (tmp[x] & ((1 << GAIN) - 1)) {
410                                 /* If it has data down low, then it's not something we've artificially increased gain
411                                    on, so we don't need to gain adjust it */
412                                 s->needsgain = 0;
413                         }
414         }
415         if (s->needsgain) {
416                 for (x=0;x<sizeof(tmp)/2;x++) {
417                         s->buf[x] = tmp[x] >> GAIN;
418                 }
419         } else {
420                 memcpy(s->buf, tmp, sizeof(s->buf));
421         }
422                         
423         delay = res / 2;
424         s->fr.frametype = AST_FRAME_VOICE;
425         s->fr.subclass = AST_FORMAT_SLINEAR;
426         s->fr.offset = AST_FRIENDLY_OFFSET;
427         s->fr.datalen = res;
428         s->fr.data = s->buf;
429         s->fr.mallocd = 0;
430         s->fr.samples = delay;
431         *whennext = delay;
432         return &s->fr;
433 }
434
435 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
436 {
437         int res = 0;
438         int x;
439         short tmp[8000], *tmpi;
440         float tmpf;
441         if (f->frametype != AST_FRAME_VOICE) {
442                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
443                 return -1;
444         }
445         if (f->subclass != AST_FORMAT_SLINEAR) {
446                 ast_log(LOG_WARNING, "Asked to write non-SLINEAR frame (%d)!\n", f->subclass);
447                 return -1;
448         }
449         if (f->datalen > sizeof(tmp)) {
450                 ast_log(LOG_WARNING, "Data length is too long\n");
451                 return -1;
452         }
453         if (!f->datalen)
454                 return -1;
455
456 #if 0
457         printf("Data Length: %d\n", f->datalen);
458 #endif  
459
460         if (fs->buf) {
461                 tmpi = f->data;
462                 /* Volume adjust here to accomodate */
463                 for (x=0;x<f->datalen/2;x++) {
464                         tmpf = ((float)tmpi[x]) * ((float)(1 << GAIN));
465                         if (tmpf > 32767.0)
466                                 tmpf = 32767.0;
467                         if (tmpf < -32768.0)
468                                 tmpf = -32768.0;
469                         tmp[x] = tmpf;
470                         tmp[x] &= ~((1 << GAIN) - 1);
471
472 #if __BYTE_ORDER == __BIG_ENDIAN
473                         tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
474 #endif
475
476                 }
477                 if ((write (fs->fd, tmp, f->datalen) != f->datalen) ) {
478                         ast_log(LOG_WARNING, "Bad write (%d): %s\n", res, strerror(errno));
479                         return -1;
480                 }
481         } else {
482                 ast_log(LOG_WARNING, "Cannot write data to file.\n");
483                 return -1;
484         }
485         
486         fs->bytes += f->datalen;
487         update_header(fs->fd);
488                 
489         return 0;
490
491 }
492
493 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
494 {
495         off_t min,max,cur;
496         long offset=0,samples;
497         
498         samples = sample_offset * 2; /* SLINEAR is 16 bits mono, so sample_offset * 2 = bytes */
499         min = 44; /* wav header is 44 bytes */
500         cur = lseek(fs->fd, 0, SEEK_CUR);
501         max = lseek(fs->fd, 0, SEEK_END);
502         if (whence == SEEK_SET)
503                 offset = samples + min;
504         else if (whence == SEEK_CUR || whence == SEEK_FORCECUR)
505                 offset = samples + cur;
506         else if (whence == SEEK_END)
507                 offset = max - samples;
508         if (whence != SEEK_FORCECUR) {
509                 offset = (offset > max)?max:offset;
510                 offset = (offset < min)?min:offset;
511         }
512         return lseek(fs->fd,offset,SEEK_SET);
513 }
514
515 static int wav_trunc(struct ast_filestream *fs)
516 {
517         if(ftruncate(fs->fd, lseek(fs->fd,0,SEEK_CUR)))
518                 return -1;
519         return update_header(fs->fd);
520 }
521
522 static long wav_tell(struct ast_filestream *fs)
523 {
524         off_t offset;
525         offset = lseek(fs->fd, 0, SEEK_CUR);
526         /* subtract header size to get samples, then divide by 2 for 16 bit samples */
527         return (offset - 44)/2;
528 }
529
530 static char *wav_getcomment(struct ast_filestream *s)
531 {
532         return NULL;
533 }
534
535 int load_module()
536 {
537         return ast_format_register(name, exts, AST_FORMAT_SLINEAR,
538                                                                 wav_open,
539                                                                 wav_rewrite,
540                                                                 wav_write,
541                                                                 wav_seek,
542                                                                 wav_trunc,
543                                                                 wav_tell,
544                                                                 wav_read,
545                                                                 wav_close,
546                                                                 wav_getcomment);
547                                                                 
548                                                                 
549 }
550
551 int unload_module()
552 {
553         return ast_format_unregister(name);
554 }       
555
556 int usecount()
557 {
558         int res;
559         if (ast_mutex_lock(&wav_lock)) {
560                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
561                 return -1;
562         }
563         res = glistcnt;
564         ast_mutex_unlock(&wav_lock);
565         return res;
566 }
567
568 char *description()
569 {
570         return desc;
571 }
572
573
574 char *key()
575 {
576         return ASTERISK_GPL_KEY;
577 }