Fix size bug in wav49 format (bug #254) thanks rtucker!
[asterisk/asterisk.git] / formats / format_wav_gsm.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Save GSM 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 <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <stdlib.h>
23 #include <sys/time.h>
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <pthread.h>
29 #ifdef __linux__
30 #include <endian.h>
31 #else
32 #include <machine/endian.h>
33 #endif
34 #include "msgsm.h"
35
36 /* Some Ideas for this code came from makewave.c by Jeffery Chilton */
37
38 /* Portions of the conversion code are by guido@sienanet.it */
39
40 struct ast_filestream {
41         void *reserved[AST_RESERVED_POINTERS];
42         /* Believe it or not, we must decode/recode to account for the
43            weird MS format */
44         /* This is what a filestream means to us */
45         int fd; /* Descriptor */
46         int bytes;
47         struct ast_frame fr;                            /* Frame information */
48         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
49         char empty;                                                     /* Empty character */
50         unsigned char gsm[66];                          /* Two Real GSM Frames */
51         int foffset;
52         int secondhalf;                                         /* Are we on the second half */
53         struct timeval last;
54 };
55
56
57 static ast_mutex_t wav_lock = AST_MUTEX_INITIALIZER;
58 static int glistcnt = 0;
59
60 static char *name = "wav49";
61 static char *desc = "Microsoft WAV format (Proprietary GSM)";
62 static char *exts = "WAV";
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, fact;
91         short format, chans;
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) != 20) {
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) != 49) {
136                 ast_log(LOG_WARNING, "Not a GSM 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, &freq, 4) != 4) {
157                 ast_log(LOG_WARNING, "Read failed (X_1)\n");
158                 return -1;
159         }
160         /* Ignore the two weird fields */
161         if (read(fd, &freq, 4) != 4) {
162                 ast_log(LOG_WARNING, "Read failed (X_2/X_3)\n");
163                 return -1;
164         }
165         /* Ignore the byte frequency */
166         if (read(fd, &freq, 4) != 4) {
167                 ast_log(LOG_WARNING, "Read failed (Y_1)\n");
168                 return -1;
169         }
170         /* Check for the word fact */
171         if (read(fd, &fact, 4) != 4) {
172                 ast_log(LOG_WARNING, "Read failed (fact)\n");
173                 return -1;
174         }
175         if (memcmp(&fact, "fact", 4)) {
176                 ast_log(LOG_WARNING, "Does not say fact\n");
177                 return -1;
178         }
179         /* Ignore the "fact value" */
180         if (read(fd, &fact, 4) != 4) {
181                 ast_log(LOG_WARNING, "Read failed (fact header)\n");
182                 return -1;
183         }
184         if (read(fd, &fact, 4) != 4) {
185                 ast_log(LOG_WARNING, "Read failed (fact value)\n");
186                 return -1;
187         }
188         /* Check for the word data */
189         if (read(fd, &data, 4) != 4) {
190                 ast_log(LOG_WARNING, "Read failed (data)\n");
191                 return -1;
192         }
193         if (memcmp(&data, "data", 4)) {
194                 ast_log(LOG_WARNING, "Does not say data\n");
195                 return -1;
196         }
197         /* Ignore the data length */
198         if (read(fd, &data, 4) != 4) {
199                 ast_log(LOG_WARNING, "Read failed (data)\n");
200                 return -1;
201         }
202         return 0;
203 }
204
205 static int update_header(int fd)
206 {
207         off_t cur,end,bytes;
208         int datalen,filelen;
209         
210         cur = lseek(fd, 0, SEEK_CUR);
211         end = lseek(fd, 0, SEEK_END);
212         /* in a gsm WAV, data starts 60 bytes in */
213         bytes = end - 60;
214         datalen = htoll(bytes);
215         filelen = htoll(52 + ((bytes + 1) & ~0x1));
216         if (cur < 0) {
217                 ast_log(LOG_WARNING, "Unable to find our position\n");
218                 return -1;
219         }
220         if (lseek(fd, 4, SEEK_SET) != 4) {
221                 ast_log(LOG_WARNING, "Unable to set our position\n");
222                 return -1;
223         }
224         if (write(fd, &filelen, 4) != 4) {
225                 ast_log(LOG_WARNING, "Unable to set write file size\n");
226                 return -1;
227         }
228         if (lseek(fd, 56, SEEK_SET) != 56) {
229                 ast_log(LOG_WARNING, "Unable to set our position\n");
230                 return -1;
231         }
232         if (write(fd, &datalen, 4) != 4) {
233                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
234                 return -1;
235         }
236         if (lseek(fd, cur, SEEK_SET) != cur) {
237                 ast_log(LOG_WARNING, "Unable to return to position\n");
238                 return -1;
239         }
240         return 0;
241 }
242
243 static int write_header(int fd)
244 {
245         unsigned int hz=htoll(8000);
246         unsigned int bhz = htoll(1625);
247         unsigned int hs = htoll(20);
248         unsigned short fmt = htols(49);
249         unsigned short chans = htols(1);
250         unsigned int fhs = htoll(4);
251         unsigned int x_1 = htoll(65);
252         unsigned short x_2 = htols(2);
253         unsigned short x_3 = htols(320);
254         unsigned int y_1 = htoll(20160);
255         unsigned int size = htoll(0);
256         /* Write a GSM header, ignoring sizes which will be filled in later */
257         if (write(fd, "RIFF", 4) != 4) {
258                 ast_log(LOG_WARNING, "Unable to write header\n");
259                 return -1;
260         }
261         if (write(fd, &size, 4) != 4) {
262                 ast_log(LOG_WARNING, "Unable to write header\n");
263                 return -1;
264         }
265         if (write(fd, "WAVEfmt ", 8) != 8) {
266                 ast_log(LOG_WARNING, "Unable to write header\n");
267                 return -1;
268         }
269         if (write(fd, &hs, 4) != 4) {
270                 ast_log(LOG_WARNING, "Unable to write header\n");
271                 return -1;
272         }
273         if (write(fd, &fmt, 2) != 2) {
274                 ast_log(LOG_WARNING, "Unable to write header\n");
275                 return -1;
276         }
277         if (write(fd, &chans, 2) != 2) {
278                 ast_log(LOG_WARNING, "Unable to write header\n");
279                 return -1;
280         }
281         if (write(fd, &hz, 4) != 4) {
282                 ast_log(LOG_WARNING, "Unable to write header\n");
283                 return -1;
284         }
285         if (write(fd, &bhz, 4) != 4) {
286                 ast_log(LOG_WARNING, "Unable to write header\n");
287                 return -1;
288         }
289         if (write(fd, &x_1, 4) != 4) {
290                 ast_log(LOG_WARNING, "Unable to write header\n");
291                 return -1;
292         }
293         if (write(fd, &x_2, 2) != 2) {
294                 ast_log(LOG_WARNING, "Unable to write header\n");
295                 return -1;
296         }
297         if (write(fd, &x_3, 2) != 2) {
298                 ast_log(LOG_WARNING, "Unable to write header\n");
299                 return -1;
300         }
301         if (write(fd, "fact", 4) != 4) {
302                 ast_log(LOG_WARNING, "Unable to write header\n");
303                 return -1;
304         }
305         if (write(fd, &fhs, 4) != 4) {
306                 ast_log(LOG_WARNING, "Unable to write header\n");
307                 return -1;
308         }
309         if (write(fd, &y_1, 4) != 4) {
310                 ast_log(LOG_WARNING, "Unable to write header\n");
311                 return -1;
312         }
313         if (write(fd, "data", 4) != 4) {
314                 ast_log(LOG_WARNING, "Unable to write header\n");
315                 return -1;
316         }
317         if (write(fd, &size, 4) != 4) {
318                 ast_log(LOG_WARNING, "Unable to write header\n");
319                 return -1;
320         }
321         return 0;
322 }
323
324 static struct ast_filestream *wav_open(int fd)
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 (check_header(fd)) {
333                         free(tmp);
334                         return NULL;
335                 }
336                 if (ast_mutex_lock(&wav_lock)) {
337                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
338                         free(tmp);
339                         return NULL;
340                 }
341                 tmp->fd = fd;
342                 tmp->fr.data = tmp->gsm;
343                 tmp->fr.frametype = AST_FRAME_VOICE;
344                 tmp->fr.subclass = AST_FORMAT_GSM;
345                 /* datalen will vary for each frame */
346                 tmp->fr.src = name;
347                 tmp->fr.mallocd = 0;
348                 tmp->secondhalf = 0;
349                 glistcnt++;
350                 ast_mutex_unlock(&wav_lock);
351                 ast_update_use_count();
352         }
353         return tmp;
354 }
355
356 static struct ast_filestream *wav_rewrite(int fd, char *comment)
357 {
358         /* We don't have any header to read or anything really, but
359            if we did, it would go here.  We also might want to check
360            and be sure it's a valid file.  */
361         struct ast_filestream *tmp;
362         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
363                 memset(tmp, 0, sizeof(struct ast_filestream));
364                 if (write_header(fd)) {
365                         free(tmp);
366                         return NULL;
367                 }
368                 if (ast_mutex_lock(&wav_lock)) {
369                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
370                         free(tmp);
371                         return NULL;
372                 }
373                 tmp->fd = fd;
374                 glistcnt++;
375                 ast_mutex_unlock(&wav_lock);
376                 ast_update_use_count();
377         } else
378                 ast_log(LOG_WARNING, "Out of memory\n");
379         return tmp;
380 }
381
382 static void wav_close(struct ast_filestream *s)
383 {
384         char zero = 0;
385         ast_mutex_unlock(&wav_lock);
386         ast_update_use_count();
387         /* Pad to even length */
388         if (s->bytes & 0x1)
389                 write(s->fd, &zero, 1);
390         close(s->fd);
391         free(s);
392         s = NULL;
393 }
394
395 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
396 {
397         int res;
398         char msdata[66];
399         /* Send a frame from the file to the appropriate channel */
400
401         s->fr.frametype = AST_FRAME_VOICE;
402         s->fr.subclass = AST_FORMAT_GSM;
403         s->fr.offset = AST_FRIENDLY_OFFSET;
404         s->fr.samples = 160;
405         s->fr.datalen = 33;
406         s->fr.mallocd = 0;
407         if (s->secondhalf) {
408                 /* Just return a frame based on the second GSM frame */
409                 s->fr.data = s->gsm + 33;
410         } else {
411                 if ((res = read(s->fd, msdata, 65)) != 65) {
412                         if (res && (res != 1))
413                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
414                         return NULL;
415                 }
416                 /* Convert from MS format to two real GSM frames */
417                 conv65(msdata, s->gsm);
418                 s->fr.data = s->gsm;
419         }
420         s->secondhalf = !s->secondhalf;
421         *whennext = 160;
422         return &s->fr;
423 }
424
425 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
426 {
427         int res;
428         char msdata[66];
429         int len =0;
430         int alreadyms=0;
431         if (f->frametype != AST_FRAME_VOICE) {
432                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
433                 return -1;
434         }
435         if (f->subclass != AST_FORMAT_GSM) {
436                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
437                 return -1;
438         }
439         if (!(f->datalen % 65)) 
440                 alreadyms = 1;
441         while(len < f->datalen) {
442                 if (alreadyms) {
443                         fs->secondhalf = 0;
444                         if ((res = write(fs->fd, f->data + len, 65)) != 65) {
445                                 ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
446                                 return -1;
447                         }
448                         fs->bytes += 65;
449                         update_header(fs->fd);
450                         len += 65;
451                 } else {
452                         if (fs->secondhalf) {
453                                 memcpy(fs->gsm + 33, f->data + len, 33);
454                                 conv66(fs->gsm, msdata);
455                                 if ((res = write(fs->fd, msdata, 65)) != 65) {
456                                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
457                                         return -1;
458                                 }
459                                 fs->bytes += 65;
460                                 update_header(fs->fd);
461                         } else {
462                                 /* Copy the data and do nothing */
463                                 memcpy(fs->gsm, f->data + len, 33);
464                         }
465                         fs->secondhalf = !fs->secondhalf;
466                         len += 33;
467                 }
468         }
469         return 0;
470 }
471
472 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
473 {
474         off_t offset=0,distance,cur,min,max;
475         min = 52;
476         cur = lseek(fs->fd, 0, SEEK_CUR);
477         max = lseek(fs->fd, 0, SEEK_END);
478         /* I'm getting sloppy here, I'm only going to go to even splits of the 2
479          * frames, if you want tighter cuts use format_gsm, format_pcm, or format_wav */
480         distance = (sample_offset/320) * 65;
481         if(whence == SEEK_SET)
482                 offset = distance + min;
483         else if(whence == SEEK_CUR || whence == SEEK_FORCECUR)
484                 offset = distance + cur;
485         else if(whence == SEEK_END)
486                 offset = max - distance;
487         if (whence != SEEK_FORCECUR) {
488                 offset = (offset < min)?min:offset;
489                 offset = (offset > max)?max:offset;
490         }
491         fs->secondhalf = 0;
492         return lseek(fs->fd, offset, SEEK_SET);
493 }
494
495 static int wav_trunc(struct ast_filestream *fs)
496 {
497         if(ftruncate(fs->fd, lseek(fs->fd, 0, SEEK_CUR)))
498                 return -1;
499         return update_header(fs->fd);
500 }
501
502 static long wav_tell(struct ast_filestream *fs)
503 {
504         off_t offset;
505         offset = lseek(fs->fd, 0, SEEK_CUR);
506         /* since this will most likely be used later in play or record, lets stick
507          * to that level of resolution, just even frames boundaries */
508         return (offset - 52)/65/320;
509 }
510
511 static char *wav_getcomment(struct ast_filestream *s)
512 {
513         return NULL;
514 }
515
516 int load_module()
517 {
518         return ast_format_register(name, exts, AST_FORMAT_GSM,
519                                                                 wav_open,
520                                                                 wav_rewrite,
521                                                                 wav_write,
522                                                                 wav_seek,
523                                                                 wav_trunc,
524                                                                 wav_tell,
525                                                                 wav_read,
526                                                                 wav_close,
527                                                                 wav_getcomment);
528                                                                 
529                                                                 
530 }
531
532 int unload_module()
533 {
534         return ast_format_unregister(name);
535 }       
536
537 int usecount()
538 {
539         int res;
540         if (ast_mutex_lock(&wav_lock)) {
541                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
542                 return -1;
543         }
544         res = glistcnt;
545         ast_mutex_unlock(&wav_lock);
546         return res;
547 }
548
549 char *description()
550 {
551         return desc;
552 }
553
554
555 char *key()
556 {
557         return ASTERISK_GPL_KEY;
558 }