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