Bug #1087. Fix wav49 format so it can be played. Make file functions
[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 Jeffrey Chilton */
37
38 /* Portions of the conversion code are by guido@sienanet.it */
39
40 /* begin binary data: */
41 char msgsm_silence[] = /* 65 */
42 {0x48,0x17,0xD6,0x84,0x02,0x80,0x24,0x49,0x92,0x24,0x89,0x02,0x80,0x24,0x49
43 ,0x92,0x24,0x89,0x02,0x80,0x24,0x49,0x92,0x24,0x89,0x02,0x80,0x24,0x49,0x92
44 ,0x24,0x09,0x82,0x74,0x61,0x4D,0x28,0x00,0x48,0x92,0x24,0x49,0x92,0x28,0x00
45 ,0x48,0x92,0x24,0x49,0x92,0x28,0x00,0x48,0x92,0x24,0x49,0x92,0x28,0x00,0x48
46 ,0x92,0x24,0x49,0x92,0x00};
47 /* end binary data. size = 65 bytes */
48
49 struct ast_filestream {
50         void *reserved[AST_RESERVED_POINTERS];
51         /* Believe it or not, we must decode/recode to account for the
52            weird MS format */
53         /* This is what a filestream means to us */
54         int fd; /* Descriptor */
55         int bytes;
56         struct ast_frame fr;                            /* Frame information */
57         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
58         char empty;                                                     /* Empty character */
59         unsigned char gsm[66];                          /* Two Real GSM Frames */
60         int foffset;
61         int secondhalf;                                         /* Are we on the second half */
62         struct timeval last;
63 };
64
65
66 static ast_mutex_t wav_lock = AST_MUTEX_INITIALIZER;
67 static int glistcnt = 0;
68
69 static char *name = "wav49";
70 static char *desc = "Microsoft WAV format (Proprietary GSM)";
71 static char *exts = "WAV|wav49";
72
73 #if __BYTE_ORDER == __LITTLE_ENDIAN
74 #define htoll(b) (b)
75 #define htols(b) (b)
76 #define ltohl(b) (b)
77 #define ltohs(b) (b)
78 #else
79 #if __BYTE_ORDER == __BIG_ENDIAN
80 #define htoll(b)  \
81           (((((b)      ) & 0xFF) << 24) | \
82                ((((b) >>  8) & 0xFF) << 16) | \
83                    ((((b) >> 16) & 0xFF) <<  8) | \
84                    ((((b) >> 24) & 0xFF)      ))
85 #define htols(b) \
86           (((((b)      ) & 0xFF) << 8) | \
87                    ((((b) >> 8) & 0xFF)      ))
88 #define ltohl(b) htoll(b)
89 #define ltohs(b) htols(b)
90 #else
91 #error "Endianess not defined"
92 #endif
93 #endif
94
95
96 static int check_header(int fd)
97 {
98         int type, size, formtype;
99         int fmt, hsize, fact;
100         short format, chans;
101         int freq;
102         int data;
103         if (read(fd, &type, 4) != 4) {
104                 ast_log(LOG_WARNING, "Read failed (type)\n");
105                 return -1;
106         }
107         if (read(fd, &size, 4) != 4) {
108                 ast_log(LOG_WARNING, "Read failed (size)\n");
109                 return -1;
110         }
111         size = ltohl(size);
112         if (read(fd, &formtype, 4) != 4) {
113                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
114                 return -1;
115         }
116         if (memcmp(&type, "RIFF", 4)) {
117                 ast_log(LOG_WARNING, "Does not begin with RIFF\n");
118                 return -1;
119         }
120         if (memcmp(&formtype, "WAVE", 4)) {
121                 ast_log(LOG_WARNING, "Does not contain WAVE\n");
122                 return -1;
123         }
124         if (read(fd, &fmt, 4) != 4) {
125                 ast_log(LOG_WARNING, "Read failed (fmt)\n");
126                 return -1;
127         }
128         if (memcmp(&fmt, "fmt ", 4)) {
129                 ast_log(LOG_WARNING, "Does not say fmt\n");
130                 return -1;
131         }
132         if (read(fd, &hsize, 4) != 4) {
133                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
134                 return -1;
135         }
136         if (ltohl(hsize) != 20) {
137                 ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
138                 return -1;
139         }
140         if (read(fd, &format, 2) != 2) {
141                 ast_log(LOG_WARNING, "Read failed (format)\n");
142                 return -1;
143         }
144         if (ltohs(format) != 49) {
145                 ast_log(LOG_WARNING, "Not a GSM file %d\n", ltohs(format));
146                 return -1;
147         }
148         if (read(fd, &chans, 2) != 2) {
149                 ast_log(LOG_WARNING, "Read failed (format)\n");
150                 return -1;
151         }
152         if (ltohs(chans) != 1) {
153                 ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
154                 return -1;
155         }
156         if (read(fd, &freq, 4) != 4) {
157                 ast_log(LOG_WARNING, "Read failed (freq)\n");
158                 return -1;
159         }
160         if (ltohl(freq) != 8000) {
161                 ast_log(LOG_WARNING, "Unexpected freqency %d\n", ltohl(freq));
162                 return -1;
163         }
164         /* Ignore the byte frequency */
165         if (read(fd, &freq, 4) != 4) {
166                 ast_log(LOG_WARNING, "Read failed (X_1)\n");
167                 return -1;
168         }
169         /* Ignore the two weird fields */
170         if (read(fd, &freq, 4) != 4) {
171                 ast_log(LOG_WARNING, "Read failed (X_2/X_3)\n");
172                 return -1;
173         }
174         /* Ignore the byte frequency */
175         if (read(fd, &freq, 4) != 4) {
176                 ast_log(LOG_WARNING, "Read failed (Y_1)\n");
177                 return -1;
178         }
179         /* Check for the word fact */
180         if (read(fd, &fact, 4) != 4) {
181                 ast_log(LOG_WARNING, "Read failed (fact)\n");
182                 return -1;
183         }
184         if (memcmp(&fact, "fact", 4)) {
185                 ast_log(LOG_WARNING, "Does not say fact\n");
186                 return -1;
187         }
188         /* Ignore the "fact value" */
189         if (read(fd, &fact, 4) != 4) {
190                 ast_log(LOG_WARNING, "Read failed (fact header)\n");
191                 return -1;
192         }
193         if (read(fd, &fact, 4) != 4) {
194                 ast_log(LOG_WARNING, "Read failed (fact value)\n");
195                 return -1;
196         }
197         /* Check for the word data */
198         if (read(fd, &data, 4) != 4) {
199                 ast_log(LOG_WARNING, "Read failed (data)\n");
200                 return -1;
201         }
202 #if 0  /* Does this header actually exist?  It doesn't appear to in the files that are created with ast_writefile using this format */
203         if (memcmp(&data, "data", 4)) {
204                 ast_log(LOG_WARNING, "Does not say data\n");
205                 return -1;
206         }
207 #endif
208         /* Ignore the data length */
209         if (read(fd, &data, 4) != 4) {
210                 ast_log(LOG_WARNING, "Read failed (data)\n");
211                 return -1;
212         }
213         return 0;
214 }
215
216 static int update_header(int fd)
217 {
218         off_t cur,end,bytes;
219         int datalen,filelen;
220         
221         cur = lseek(fd, 0, SEEK_CUR);
222         end = lseek(fd, 0, SEEK_END);
223         /* in a gsm WAV, data starts 60 bytes in */
224         bytes = end - 60;
225         datalen = htoll(bytes);
226         filelen = htoll(52 + ((bytes + 1) & ~0x1));
227         if (cur < 0) {
228                 ast_log(LOG_WARNING, "Unable to find our position\n");
229                 return -1;
230         }
231         if (lseek(fd, 4, SEEK_SET) != 4) {
232                 ast_log(LOG_WARNING, "Unable to set our position\n");
233                 return -1;
234         }
235         if (write(fd, &filelen, 4) != 4) {
236                 ast_log(LOG_WARNING, "Unable to set write file size\n");
237                 return -1;
238         }
239         if (lseek(fd, 56, SEEK_SET) != 56) {
240                 ast_log(LOG_WARNING, "Unable to set our position\n");
241                 return -1;
242         }
243         if (write(fd, &datalen, 4) != 4) {
244                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
245                 return -1;
246         }
247         if (lseek(fd, cur, SEEK_SET) != cur) {
248                 ast_log(LOG_WARNING, "Unable to return to position\n");
249                 return -1;
250         }
251         return 0;
252 }
253
254 static int write_header(int fd)
255 {
256         unsigned int hz=htoll(8000);
257         unsigned int bhz = htoll(1625);
258         unsigned int hs = htoll(20);
259         unsigned short fmt = htols(49);
260         unsigned short chans = htols(1);
261         unsigned int fhs = htoll(4);
262         unsigned int x_1 = htoll(65);
263         unsigned short x_2 = htols(2);
264         unsigned short x_3 = htols(320);
265         unsigned int y_1 = htoll(20160);
266         unsigned int size = htoll(0);
267         /* Write a GSM header, ignoring sizes which will be filled in later */
268         if (write(fd, "RIFF", 4) != 4) {
269                 ast_log(LOG_WARNING, "Unable to write header\n");
270                 return -1;
271         }
272         if (write(fd, &size, 4) != 4) {
273                 ast_log(LOG_WARNING, "Unable to write header\n");
274                 return -1;
275         }
276         if (write(fd, "WAVEfmt ", 8) != 8) {
277                 ast_log(LOG_WARNING, "Unable to write header\n");
278                 return -1;
279         }
280         if (write(fd, &hs, 4) != 4) {
281                 ast_log(LOG_WARNING, "Unable to write header\n");
282                 return -1;
283         }
284         if (write(fd, &fmt, 2) != 2) {
285                 ast_log(LOG_WARNING, "Unable to write header\n");
286                 return -1;
287         }
288         if (write(fd, &chans, 2) != 2) {
289                 ast_log(LOG_WARNING, "Unable to write header\n");
290                 return -1;
291         }
292         if (write(fd, &hz, 4) != 4) {
293                 ast_log(LOG_WARNING, "Unable to write header\n");
294                 return -1;
295         }
296         if (write(fd, &bhz, 4) != 4) {
297                 ast_log(LOG_WARNING, "Unable to write header\n");
298                 return -1;
299         }
300         if (write(fd, &x_1, 4) != 4) {
301                 ast_log(LOG_WARNING, "Unable to write header\n");
302                 return -1;
303         }
304         if (write(fd, &x_2, 2) != 2) {
305                 ast_log(LOG_WARNING, "Unable to write header\n");
306                 return -1;
307         }
308         if (write(fd, &x_3, 2) != 2) {
309                 ast_log(LOG_WARNING, "Unable to write header\n");
310                 return -1;
311         }
312         if (write(fd, "fact", 4) != 4) {
313                 ast_log(LOG_WARNING, "Unable to write header\n");
314                 return -1;
315         }
316         if (write(fd, &fhs, 4) != 4) {
317                 ast_log(LOG_WARNING, "Unable to write header\n");
318                 return -1;
319         }
320         if (write(fd, &y_1, 4) != 4) {
321                 ast_log(LOG_WARNING, "Unable to write header\n");
322                 return -1;
323         }
324         if (write(fd, "data", 4) != 4) {
325                 ast_log(LOG_WARNING, "Unable to write header\n");
326                 return -1;
327         }
328         if (write(fd, &size, 4) != 4) {
329                 ast_log(LOG_WARNING, "Unable to write header\n");
330                 return -1;
331         }
332         return 0;
333 }
334
335 static struct ast_filestream *wav_open(int fd)
336 {
337         /* We don't have any header to read or anything really, but
338            if we did, it would go here.  We also might want to check
339            and be sure it's a valid file.  */
340         struct ast_filestream *tmp;
341         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
342                 memset(tmp, 0, sizeof(struct ast_filestream));
343                 if (check_header(fd)) {
344                         free(tmp);
345                         return NULL;
346                 }
347                 if (ast_mutex_lock(&wav_lock)) {
348                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
349                         free(tmp);
350                         return NULL;
351                 }
352                 tmp->fd = fd;
353                 tmp->fr.data = tmp->gsm;
354                 tmp->fr.frametype = AST_FRAME_VOICE;
355                 tmp->fr.subclass = AST_FORMAT_GSM;
356                 /* datalen will vary for each frame */
357                 tmp->fr.src = name;
358                 tmp->fr.mallocd = 0;
359                 tmp->secondhalf = 0;
360                 glistcnt++;
361                 ast_mutex_unlock(&wav_lock);
362                 ast_update_use_count();
363         }
364         return tmp;
365 }
366
367 static struct ast_filestream *wav_rewrite(int fd, char *comment)
368 {
369         /* We don't have any header to read or anything really, but
370            if we did, it would go here.  We also might want to check
371            and be sure it's a valid file.  */
372         struct ast_filestream *tmp;
373         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
374                 memset(tmp, 0, sizeof(struct ast_filestream));
375                 if (write_header(fd)) {
376                         free(tmp);
377                         return NULL;
378                 }
379                 if (ast_mutex_lock(&wav_lock)) {
380                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
381                         free(tmp);
382                         return NULL;
383                 }
384                 tmp->fd = fd;
385                 glistcnt++;
386                 ast_mutex_unlock(&wav_lock);
387                 ast_update_use_count();
388         } else
389                 ast_log(LOG_WARNING, "Out of memory\n");
390         return tmp;
391 }
392
393 static void wav_close(struct ast_filestream *s)
394 {
395         char zero = 0;
396         ast_mutex_unlock(&wav_lock);
397         ast_update_use_count();
398         /* Pad to even length */
399         if (s->bytes & 0x1)
400                 write(s->fd, &zero, 1);
401         close(s->fd);
402         free(s);
403         s = NULL;
404 }
405
406 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
407 {
408         int res;
409         char msdata[66];
410         /* Send a frame from the file to the appropriate channel */
411
412         s->fr.frametype = AST_FRAME_VOICE;
413         s->fr.subclass = AST_FORMAT_GSM;
414         s->fr.offset = AST_FRIENDLY_OFFSET;
415         s->fr.samples = 160;
416         s->fr.datalen = 33;
417         s->fr.mallocd = 0;
418         if (s->secondhalf) {
419                 /* Just return a frame based on the second GSM frame */
420                 s->fr.data = s->gsm + 33;
421         } else {
422                 if ((res = read(s->fd, msdata, 65)) != 65) {
423                         if (res && (res != 1))
424                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
425                         return NULL;
426                 }
427                 /* Convert from MS format to two real GSM frames */
428                 conv65(msdata, s->gsm);
429                 s->fr.data = s->gsm;
430         }
431         s->secondhalf = !s->secondhalf;
432         *whennext = 160;
433         return &s->fr;
434 }
435
436 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
437 {
438         int res;
439         char msdata[66];
440         int len =0;
441         int alreadyms=0;
442         if (f->frametype != AST_FRAME_VOICE) {
443                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
444                 return -1;
445         }
446         if (f->subclass != AST_FORMAT_GSM) {
447                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
448                 return -1;
449         }
450         if (!(f->datalen % 65)) 
451                 alreadyms = 1;
452         while(len < f->datalen) {
453                 if (alreadyms) {
454                         fs->secondhalf = 0;
455                         if ((res = write(fs->fd, f->data + len, 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                         len += 65;
462                 } else {
463                         if (fs->secondhalf) {
464                                 memcpy(fs->gsm + 33, f->data + len, 33);
465                                 conv66(fs->gsm, msdata);
466                                 if ((res = write(fs->fd, msdata, 65)) != 65) {
467                                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
468                                         return -1;
469                                 }
470                                 fs->bytes += 65;
471                                 update_header(fs->fd);
472                         } else {
473                                 /* Copy the data and do nothing */
474                                 memcpy(fs->gsm, f->data + len, 33);
475                         }
476                         fs->secondhalf = !fs->secondhalf;
477                         len += 33;
478                 }
479         }
480         return 0;
481 }
482
483 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
484 {
485         off_t offset=0,distance,cur,min,max;
486         min = 52;
487         cur = lseek(fs->fd, 0, SEEK_CUR);
488         max = lseek(fs->fd, 0, SEEK_END);
489         /* I'm getting sloppy here, I'm only going to go to even splits of the 2
490          * frames, if you want tighter cuts use format_gsm, format_pcm, or format_wav */
491         distance = (sample_offset/320) * 65;
492         if(whence == SEEK_SET)
493                 offset = distance + min;
494         else if(whence == SEEK_CUR || whence == SEEK_FORCECUR)
495                 offset = distance + cur;
496         else if(whence == SEEK_END)
497                 offset = max - distance;
498         if (whence != SEEK_FORCECUR) {
499                 offset = (offset < min)?min:offset;
500                 offset = (offset > max)?max:offset;
501         } else if (offset > max) {
502                 int i;
503                 lseek(fs->fd, 0, SEEK_END);
504                 for (i=0; i< (offset - max) / 65; i++) {
505                         write(fs->fd, msgsm_silence, 65);
506                 }
507         }
508         fs->secondhalf = 0;
509         return lseek(fs->fd, offset, SEEK_SET);
510 }
511
512 static int wav_trunc(struct ast_filestream *fs)
513 {
514         if(ftruncate(fs->fd, lseek(fs->fd, 0, SEEK_CUR)))
515                 return -1;
516         return update_header(fs->fd);
517 }
518
519 static long wav_tell(struct ast_filestream *fs)
520 {
521         off_t offset;
522         offset = lseek(fs->fd, 0, SEEK_CUR);
523         /* since this will most likely be used later in play or record, lets stick
524          * to that level of resolution, just even frames boundaries */
525         return (offset - 52)/65/320;
526 }
527
528 static char *wav_getcomment(struct ast_filestream *s)
529 {
530         return NULL;
531 }
532
533 int load_module()
534 {
535         return ast_format_register(name, exts, AST_FORMAT_GSM,
536                                                                 wav_open,
537                                                                 wav_rewrite,
538                                                                 wav_write,
539                                                                 wav_seek,
540                                                                 wav_trunc,
541                                                                 wav_tell,
542                                                                 wav_read,
543                                                                 wav_close,
544                                                                 wav_getcomment);
545                                                                 
546                                                                 
547 }
548
549 int unload_module()
550 {
551         return ast_format_unregister(name);
552 }       
553
554 int usecount()
555 {
556         int res;
557         if (ast_mutex_lock(&wav_lock)) {
558                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
559                 return -1;
560         }
561         res = glistcnt;
562         ast_mutex_unlock(&wav_lock);
563         return res;
564 }
565
566 char *description()
567 {
568         return desc;
569 }
570
571
572 char *key()
573 {
574         return ASTERISK_GPL_KEY;
575 }