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