Improve disk writes for wav49 format
[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 /*! \file
20  *
21  * \brief Save GSM in the proprietary Microsoft format.
22  * 
23  * Microsoft WAV format (Proprietary GSM)
24  * \arg File name extension: WAV,wav49  (Upper case WAV, lower case is another format)
25  * This format can be played on Windows systems, used for
26  * e-mail attachments mainly.
27  * \ingroup formats
28  */
29
30 /*** MODULEINFO
31         <support_level>core</support_level>
32  ***/
33  
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/mod_format.h"
39 #include "asterisk/module.h"
40 #include "asterisk/endian.h"
41
42 #include "msgsm.h"
43
44 /* Some Ideas for this code came from makewave.c by Jeffrey Chilton */
45
46 /* Portions of the conversion code are by guido@sienanet.it */
47
48 #define GSM_FRAME_SIZE  33
49 #define MSGSM_FRAME_SIZE        65
50 #define MSGSM_DATA_OFFSET               60      /* offset of data bytes */
51 #define GSM_SAMPLES             160     /* samples in a GSM block */
52 #define MSGSM_SAMPLES           (2*GSM_SAMPLES) /* samples in an MSGSM block */
53
54 /* begin binary data: */
55 static char msgsm_silence[] = /* 65 */
56 {0x48,0x17,0xD6,0x84,0x02,0x80,0x24,0x49,0x92,0x24,0x89,0x02,0x80,0x24,0x49
57 ,0x92,0x24,0x89,0x02,0x80,0x24,0x49,0x92,0x24,0x89,0x02,0x80,0x24,0x49,0x92
58 ,0x24,0x09,0x82,0x74,0x61,0x4D,0x28,0x00,0x48,0x92,0x24,0x49,0x92,0x28,0x00
59 ,0x48,0x92,0x24,0x49,0x92,0x28,0x00,0x48,0x92,0x24,0x49,0x92,0x28,0x00,0x48
60 ,0x92,0x24,0x49,0x92,0x00};
61 /* end binary data. size = 65 bytes */
62
63 struct wavg_desc {
64         /* Believe it or not, we must decode/recode to account for the
65            weird MS format */
66         int secondhalf;                                         /* Are we on the second half */
67 };
68
69 #if __BYTE_ORDER == __LITTLE_ENDIAN
70 #define htoll(b) (b)
71 #define htols(b) (b)
72 #define ltohl(b) (b)
73 #define ltohs(b) (b)
74 #else
75 #if __BYTE_ORDER == __BIG_ENDIAN
76 #define htoll(b)  \
77           (((((b)      ) & 0xFF) << 24) | \
78                ((((b) >>  8) & 0xFF) << 16) | \
79                    ((((b) >> 16) & 0xFF) <<  8) | \
80                    ((((b) >> 24) & 0xFF)      ))
81 #define htols(b) \
82           (((((b)      ) & 0xFF) << 8) | \
83                    ((((b) >> 8) & 0xFF)      ))
84 #define ltohl(b) htoll(b)
85 #define ltohs(b) htols(b)
86 #else
87 #error "Endianess not defined"
88 #endif
89 #endif
90
91
92 static int check_header(FILE *f)
93 {
94         int type, size, formtype;
95         int fmt, hsize, fact;
96         short format, chans;
97         int freq;
98         int data;
99         if (fread(&type, 1, 4, f) != 4) {
100                 ast_log(LOG_WARNING, "Read failed (type)\n");
101                 return -1;
102         }
103         if (fread(&size, 1, 4, f) != 4) {
104                 ast_log(LOG_WARNING, "Read failed (size)\n");
105                 return -1;
106         }
107         size = ltohl(size);
108         if (fread(&formtype, 1, 4, f) != 4) {
109                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
110                 return -1;
111         }
112         if (memcmp(&type, "RIFF", 4)) {
113                 ast_log(LOG_WARNING, "Does not begin with RIFF\n");
114                 return -1;
115         }
116         if (memcmp(&formtype, "WAVE", 4)) {
117                 ast_log(LOG_WARNING, "Does not contain WAVE\n");
118                 return -1;
119         }
120         if (fread(&fmt, 1, 4, f) != 4) {
121                 ast_log(LOG_WARNING, "Read failed (fmt)\n");
122                 return -1;
123         }
124         if (memcmp(&fmt, "fmt ", 4)) {
125                 ast_log(LOG_WARNING, "Does not say fmt\n");
126                 return -1;
127         }
128         if (fread(&hsize, 1, 4, f) != 4) {
129                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
130                 return -1;
131         }
132         if (ltohl(hsize) != 20) {
133                 ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
134                 return -1;
135         }
136         if (fread(&format, 1, 2, f) != 2) {
137                 ast_log(LOG_WARNING, "Read failed (format)\n");
138                 return -1;
139         }
140         if (ltohs(format) != 49) {
141                 ast_log(LOG_WARNING, "Not a GSM file %d\n", ltohs(format));
142                 return -1;
143         }
144         if (fread(&chans, 1, 2, f) != 2) {
145                 ast_log(LOG_WARNING, "Read failed (format)\n");
146                 return -1;
147         }
148         if (ltohs(chans) != 1) {
149                 ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
150                 return -1;
151         }
152         if (fread(&freq, 1, 4, f) != 4) {
153                 ast_log(LOG_WARNING, "Read failed (freq)\n");
154                 return -1;
155         }
156         if (ltohl(freq) != DEFAULT_SAMPLE_RATE) {
157                 ast_log(LOG_WARNING, "Unexpected frequency %d\n", ltohl(freq));
158                 return -1;
159         }
160         /* Ignore the byte frequency */
161         if (fread(&freq, 1, 4, f) != 4) {
162                 ast_log(LOG_WARNING, "Read failed (X_1)\n");
163                 return -1;
164         }
165         /* Ignore the two weird fields */
166         if (fread(&freq, 1, 4, f) != 4) {
167                 ast_log(LOG_WARNING, "Read failed (X_2/X_3)\n");
168                 return -1;
169         }
170         /* Ignore the byte frequency */
171         if (fread(&freq, 1, 4, f) != 4) {
172                 ast_log(LOG_WARNING, "Read failed (Y_1)\n");
173                 return -1;
174         }
175         /* Check for the word fact */
176         if (fread(&fact, 1, 4, f) != 4) {
177                 ast_log(LOG_WARNING, "Read failed (fact)\n");
178                 return -1;
179         }
180         if (memcmp(&fact, "fact", 4)) {
181                 ast_log(LOG_WARNING, "Does not say fact\n");
182                 return -1;
183         }
184         /* Ignore the "fact value" */
185         if (fread(&fact, 1, 4, f) != 4) {
186                 ast_log(LOG_WARNING, "Read failed (fact header)\n");
187                 return -1;
188         }
189         if (fread(&fact, 1, 4, f) != 4) {
190                 ast_log(LOG_WARNING, "Read failed (fact value)\n");
191                 return -1;
192         }
193         /* Check for the word data */
194         if (fread(&data, 1, 4, f) != 4) {
195                 ast_log(LOG_WARNING, "Read failed (data)\n");
196                 return -1;
197         }
198         if (memcmp(&data, "data", 4)) {
199                 ast_log(LOG_WARNING, "Does not say data\n");
200                 return -1;
201         }
202         /* Ignore the data length */
203         if (fread(&data, 1, 4, f) != 4) {
204                 ast_log(LOG_WARNING, "Read failed (data)\n");
205                 return -1;
206         }
207         return 0;
208 }
209
210 static int update_header(FILE *f)
211 {
212         off_t cur,end,bytes;
213         int datalen, filelen, samples;
214
215         cur = ftello(f);
216         fseek(f, 0, SEEK_END);
217         end = ftello(f);
218         /* in a gsm WAV, data starts 60 bytes in */
219         bytes = end - MSGSM_DATA_OFFSET;
220         samples = htoll(bytes / MSGSM_FRAME_SIZE * MSGSM_SAMPLES);
221         datalen = htoll(bytes);
222         filelen = htoll(MSGSM_DATA_OFFSET - 8 + bytes);
223         if (cur < 0) {
224                 ast_log(LOG_WARNING, "Unable to find our position\n");
225                 return -1;
226         }
227         if (fseek(f, 4, SEEK_SET)) {
228                 ast_log(LOG_WARNING, "Unable to set our position\n");
229                 return -1;
230         }
231         if (fwrite(&filelen, 1, 4, f) != 4) {
232                 ast_log(LOG_WARNING, "Unable to write file size\n");
233                 return -1;
234         }
235         if (fseek(f, 48, SEEK_SET)) {
236                 ast_log(LOG_WARNING, "Unable to set our position\n");
237                 return -1;
238         }
239         if (fwrite(&samples, 1, 4, f) != 4) {
240                 ast_log(LOG_WARNING, "Unable to write samples\n");
241                 return -1;
242         }
243         if (fseek(f, 56, SEEK_SET)) {
244                 ast_log(LOG_WARNING, "Unable to set our position\n");
245                 return -1;
246         }
247         if (fwrite(&datalen, 1, 4, f) != 4) {
248                 ast_log(LOG_WARNING, "Unable to write datalen\n");
249                 return -1;
250         }
251         if (fseeko(f, cur, SEEK_SET)) {
252                 ast_log(LOG_WARNING, "Unable to return to position\n");
253                 return -1;
254         }
255         return 0;
256 }
257
258 static int write_header(FILE *f)
259 {
260         /* Samples per second (always 8000 for this format). */
261         unsigned int sample_rate = htoll(8000);
262         /* Bytes per second (always 1625 for this format). */
263         unsigned int byte_sample_rate = htoll(1625);
264         /* This is the size of the "fmt " subchunk */
265         unsigned int fmtsize = htoll(20);
266         /* WAV #49 */
267         unsigned short fmt = htols(49);
268         /* Mono = 1 channel */
269         unsigned short chans = htols(1);
270         /* Each block of data is exactly 65 bytes in size. */
271         unsigned int block_align = htoll(MSGSM_FRAME_SIZE);
272         /* Not actually 2, but rounded up to the nearest bit */
273         unsigned short bits_per_sample = htols(2);
274         /* Needed for compressed formats */
275         unsigned short extra_format = htols(MSGSM_SAMPLES);
276         /* This is the size of the "fact" subchunk */
277         unsigned int factsize = htoll(4);
278         /* Number of samples in the data chunk */
279         unsigned int num_samples = htoll(0);
280         /* Number of bytes in the data chunk */
281         unsigned int size = htoll(0);
282         /* Write a GSM header, ignoring sizes which will be filled in later */
283
284         /*  0: Chunk ID */
285         if (fwrite("RIFF", 1, 4, f) != 4) {
286                 ast_log(LOG_WARNING, "Unable to write header\n");
287                 return -1;
288         }
289         /*  4: Chunk Size */
290         if (fwrite(&size, 1, 4, f) != 4) {
291                 ast_log(LOG_WARNING, "Unable to write header\n");
292                 return -1;
293         }
294         /*  8: Chunk Format */
295         if (fwrite("WAVE", 1, 4, f) != 4) {
296                 ast_log(LOG_WARNING, "Unable to write header\n");
297                 return -1;
298         }
299         /* 12: Subchunk 1: ID */
300         if (fwrite("fmt ", 1, 4, f) != 4) {
301                 ast_log(LOG_WARNING, "Unable to write header\n");
302                 return -1;
303         }
304         /* 16: Subchunk 1: Size (minus 8) */
305         if (fwrite(&fmtsize, 1, 4, f) != 4) {
306                 ast_log(LOG_WARNING, "Unable to write header\n");
307                 return -1;
308         }
309         /* 20: Subchunk 1: Audio format (49) */
310         if (fwrite(&fmt, 1, 2, f) != 2) {
311                 ast_log(LOG_WARNING, "Unable to write header\n");
312                 return -1;
313         }
314         /* 22: Subchunk 1: Number of channels */
315         if (fwrite(&chans, 1, 2, f) != 2) {
316                 ast_log(LOG_WARNING, "Unable to write header\n");
317                 return -1;
318         }
319         /* 24: Subchunk 1: Sample rate */
320         if (fwrite(&sample_rate, 1, 4, f) != 4) {
321                 ast_log(LOG_WARNING, "Unable to write header\n");
322                 return -1;
323         }
324         /* 28: Subchunk 1: Byte rate */
325         if (fwrite(&byte_sample_rate, 1, 4, f) != 4) {
326                 ast_log(LOG_WARNING, "Unable to write header\n");
327                 return -1;
328         }
329         /* 32: Subchunk 1: Block align */
330         if (fwrite(&block_align, 1, 4, f) != 4) {
331                 ast_log(LOG_WARNING, "Unable to write header\n");
332                 return -1;
333         }
334         /* 36: Subchunk 1: Bits per sample */
335         if (fwrite(&bits_per_sample, 1, 2, f) != 2) {
336                 ast_log(LOG_WARNING, "Unable to write header\n");
337                 return -1;
338         }
339         /* 38: Subchunk 1: Extra format bytes */
340         if (fwrite(&extra_format, 1, 2, f) != 2) {
341                 ast_log(LOG_WARNING, "Unable to write header\n");
342                 return -1;
343         }
344         /* 40: Subchunk 2: ID */
345         if (fwrite("fact", 1, 4, f) != 4) {
346                 ast_log(LOG_WARNING, "Unable to write header\n");
347                 return -1;
348         }
349         /* 44: Subchunk 2: Size (minus 8) */
350         if (fwrite(&factsize, 1, 4, f) != 4) {
351                 ast_log(LOG_WARNING, "Unable to write header\n");
352                 return -1;
353         }
354         /* 48: Subchunk 2: Number of samples */
355         if (fwrite(&num_samples, 1, 4, f) != 4) {
356                 ast_log(LOG_WARNING, "Unable to write header\n");
357                 return -1;
358         }
359         /* 52: Subchunk 3: ID */
360         if (fwrite("data", 1, 4, f) != 4) {
361                 ast_log(LOG_WARNING, "Unable to write header\n");
362                 return -1;
363         }
364         /* 56: Subchunk 3: Size */
365         if (fwrite(&size, 1, 4, f) != 4) {
366                 ast_log(LOG_WARNING, "Unable to write header\n");
367                 return -1;
368         }
369         return 0;
370 }
371
372 static int wav_open(struct ast_filestream *s)
373 {
374         /* We don't have any header to read or anything really, but
375            if we did, it would go here.  We also might want to check
376            and be sure it's a valid file.  */
377         struct wavg_desc *fs = (struct wavg_desc *)s->_private;
378
379         if (check_header(s->f))
380                 return -1;
381         fs->secondhalf = 0;     /* not strictly necessary */
382         return 0;
383 }
384
385 static int wav_rewrite(struct ast_filestream *s, const char *comment)
386 {
387         /* We don't have any header to read or anything really, but
388            if we did, it would go here.  We also might want to check
389            and be sure it's a valid file.  */
390
391         if (write_header(s->f))
392                 return -1;
393         return 0;
394 }
395
396 static void wav_close(struct ast_filestream *s)
397 {
398         if (s->mode == O_RDONLY) {
399                 return;
400         }
401
402         if (s->filename) {
403                 update_header(s->f);
404         }
405 }
406
407 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
408 {
409         /* Send a frame from the file to the appropriate channel */
410         struct wavg_desc *fs = (struct wavg_desc *)s->_private;
411
412         s->fr.frametype = AST_FRAME_VOICE;
413         ast_format_set(&s->fr.subclass.format, AST_FORMAT_GSM, 0);
414         s->fr.offset = AST_FRIENDLY_OFFSET;
415         s->fr.samples = GSM_SAMPLES;
416         s->fr.mallocd = 0;
417         AST_FRAME_SET_BUFFER(&s->fr, s->buf, AST_FRIENDLY_OFFSET, GSM_FRAME_SIZE);
418         if (fs->secondhalf) {
419                 /* Just return a frame based on the second GSM frame */
420                 s->fr.data.ptr = (char *)s->fr.data.ptr + GSM_FRAME_SIZE;
421                 s->fr.offset += GSM_FRAME_SIZE;
422         } else {
423                 /* read and convert */
424                 unsigned char msdata[MSGSM_FRAME_SIZE];
425                 int res;
426                 
427                 if ((res = fread(msdata, 1, MSGSM_FRAME_SIZE, s->f)) != MSGSM_FRAME_SIZE) {
428                         if (res && (res != 1))
429                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
430                         return NULL;
431                 }
432                 /* Convert from MS format to two real GSM frames */
433                 conv65(msdata, s->fr.data.ptr);
434         }
435         fs->secondhalf = !fs->secondhalf;
436         *whennext = GSM_SAMPLES;
437         return &s->fr;
438 }
439
440 static int wav_write(struct ast_filestream *s, struct ast_frame *f)
441 {
442         int len;
443         int size;
444         struct wavg_desc *fs = (struct wavg_desc *)s->_private;
445
446         if (f->frametype != AST_FRAME_VOICE) {
447                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
448                 return -1;
449         }
450         if (f->subclass.format.id != AST_FORMAT_GSM) {
451                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%s)!\n", ast_getformatname(&f->subclass.format));
452                 return -1;
453         }
454         /* XXX this might fail... if the input is a multiple of MSGSM_FRAME_SIZE
455          * we assume it is already in the correct format.
456          */
457         if (!(f->datalen % MSGSM_FRAME_SIZE)) {
458                 size = MSGSM_FRAME_SIZE;
459                 fs->secondhalf = 0;
460         } else {
461                 size = GSM_FRAME_SIZE;
462         }
463         for (len = 0; len < f->datalen ; len += size) {
464                 int res;
465                 unsigned char *src, msdata[MSGSM_FRAME_SIZE];
466                 if (fs->secondhalf) {   /* second half of raw gsm to be converted */
467                         memcpy(s->buf + GSM_FRAME_SIZE, f->data.ptr + len, GSM_FRAME_SIZE);
468                         conv66((unsigned char *) s->buf, msdata);
469                         src = msdata;
470                         fs->secondhalf = 0;
471                 } else if (size == GSM_FRAME_SIZE) {    /* first half of raw gsm */
472                         memcpy(s->buf, f->data.ptr + len, GSM_FRAME_SIZE);
473                         src = NULL;     /* nothing to write */
474                         fs->secondhalf = 1;
475                 } else {        /* raw msgsm data */
476                         src = f->data.ptr + len;
477                 }
478                 if (src && (res = fwrite(src, 1, MSGSM_FRAME_SIZE, s->f)) != MSGSM_FRAME_SIZE) {
479                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
480                         return -1;
481                 }
482         }
483         return 0;
484 }
485
486 static int wav_seek(struct ast_filestream *fs, off_t sample_offset, int whence)
487 {
488         off_t offset = 0, min = MSGSM_DATA_OFFSET, distance, max, cur;
489         struct wavg_desc *s = (struct wavg_desc *)fs->_private;
490
491         if ((cur = ftello(fs->f)) < 0) {
492                 ast_log(AST_LOG_WARNING, "Unable to determine current position in WAV filestream %p: %s\n", fs, strerror(errno));
493                 return -1;
494         }
495
496         if (fseeko(fs->f, 0, SEEK_END) < 0) {
497                 ast_log(AST_LOG_WARNING, "Unable to seek to end of WAV filestream %p: %s\n", fs, strerror(errno));
498                 return -1;
499         }
500
501         /* XXX ideally, should round correctly */
502         if ((max = ftello(fs->f)) < 0) {
503                 ast_log(AST_LOG_WARNING, "Unable to determine max position in WAV filestream %p: %s\n", fs, strerror(errno));
504                 return -1;
505         }
506
507         /* Compute the distance in bytes, rounded to the block size */
508         distance = (sample_offset/MSGSM_SAMPLES) * MSGSM_FRAME_SIZE;
509         if (whence == SEEK_SET)
510                 offset = distance + min;
511         else if (whence == SEEK_CUR || whence == SEEK_FORCECUR)
512                 offset = distance + cur;
513         else if (whence == SEEK_END)
514                 offset = max - distance;
515         /* always protect against seeking past end of header */
516         if (offset < min)
517                 offset = min;
518         if (whence != SEEK_FORCECUR) {
519                 if (offset > max)
520                         offset = max;
521         } else if (offset > max) {
522                 int i;
523                 fseek(fs->f, 0, SEEK_END);
524                 for (i=0; i< (offset - max) / MSGSM_FRAME_SIZE; i++) {
525                         if (!fwrite(msgsm_silence, 1, MSGSM_FRAME_SIZE, fs->f)) {
526                                 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
527                         }
528                 }
529         }
530         s->secondhalf = 0;
531         return fseeko(fs->f, offset, SEEK_SET);
532 }
533
534 static int wav_trunc(struct ast_filestream *fs)
535 {
536         int fd;
537         off_t cur;
538
539         if ((fd = fileno(fs->f)) < 0) {
540                 ast_log(AST_LOG_WARNING, "Unable to determine file descriptor for WAV filestream %p: %s\n", fs, strerror(errno));
541                 return -1;
542         }
543         if ((cur = ftello(fs->f)) < 0) {
544                 ast_log(AST_LOG_WARNING, "Unable to determine current position in WAV filestream %p: %s\n", fs, strerror(errno));
545                 return -1;
546         }
547         /* Truncate file to current length */
548         if (ftruncate(fd, cur)) {
549                 return -1;
550         }
551         return update_header(fs->f);
552 }
553
554 static off_t wav_tell(struct ast_filestream *fs)
555 {
556         off_t offset;
557         offset = ftello(fs->f);
558         /* since this will most likely be used later in play or record, lets stick
559          * to that level of resolution, just even frames boundaries */
560         return (offset - MSGSM_DATA_OFFSET)/MSGSM_FRAME_SIZE*MSGSM_SAMPLES;
561 }
562
563 static struct ast_format_def wav49_f = {
564         .name = "wav49",
565         .exts = "WAV|wav49",
566         .open = wav_open,
567         .rewrite = wav_rewrite,
568         .write = wav_write,
569         .seek = wav_seek,
570         .trunc = wav_trunc,
571         .tell = wav_tell,
572         .read = wav_read,
573         .close = wav_close,
574         .buf_size = 2*GSM_FRAME_SIZE + AST_FRIENDLY_OFFSET,
575         .desc_size = sizeof(struct wavg_desc),
576 };
577
578 static int load_module(void)
579 {
580         ast_format_set(&wav49_f.format, AST_FORMAT_GSM, 0);
581         if (ast_format_def_register(&wav49_f))
582                 return AST_MODULE_LOAD_FAILURE;
583         return AST_MODULE_LOAD_SUCCESS;
584 }
585
586 static int unload_module(void)
587 {
588         return ast_format_def_unregister(wav49_f.name);
589 }
590
591 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Microsoft WAV format (Proprietary GSM)",
592         .load = load_module,
593         .unload = unload_module,
594         .load_pri = AST_MODPRI_APP_DEPEND
595 );