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