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