b1a0c1c1e684da211758c011b5ad02c5f2c859b7
[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 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
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 #ifdef __linux__
29 #include <endian.h>
30 #else
31 #ifdef SOLARIS
32 #include "solaris-compat/compat.h"
33 #else
34 #include <machine/endian.h>
35 #endif
36 #endif
37 #include "msgsm.h"
38
39 /* Some Ideas for this code came from makewave.c by Jeffrey Chilton */
40
41 /* Portions of the conversion code are by guido@sienanet.it */
42
43 /* begin binary data: */
44 char msgsm_silence[] = /* 65 */
45 {0x48,0x17,0xD6,0x84,0x02,0x80,0x24,0x49,0x92,0x24,0x89,0x02,0x80,0x24,0x49
46 ,0x92,0x24,0x89,0x02,0x80,0x24,0x49,0x92,0x24,0x89,0x02,0x80,0x24,0x49,0x92
47 ,0x24,0x09,0x82,0x74,0x61,0x4D,0x28,0x00,0x48,0x92,0x24,0x49,0x92,0x28,0x00
48 ,0x48,0x92,0x24,0x49,0x92,0x28,0x00,0x48,0x92,0x24,0x49,0x92,0x28,0x00,0x48
49 ,0x92,0x24,0x49,0x92,0x00};
50 /* end binary data. size = 65 bytes */
51
52 struct ast_filestream {
53         void *reserved[AST_RESERVED_POINTERS];
54         /* Believe it or not, we must decode/recode to account for the
55            weird MS format */
56         /* This is what a filestream means to us */
57         int fd; /* Descriptor */
58         struct ast_frame fr;                            /* Frame information */
59         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
60         char empty;                                                     /* Empty character */
61         unsigned char gsm[66];                          /* Two Real GSM Frames */
62         int foffset;
63         int secondhalf;                                         /* Are we on the second half */
64         struct timeval last;
65 };
66
67
68 AST_MUTEX_DEFINE_STATIC(wav_lock);
69 static int glistcnt = 0;
70
71 static char *name = "wav49";
72 static char *desc = "Microsoft WAV format (Proprietary GSM)";
73 static char *exts = "WAV|wav49";
74
75 #if __BYTE_ORDER == __LITTLE_ENDIAN
76 #define htoll(b) (b)
77 #define htols(b) (b)
78 #define ltohl(b) (b)
79 #define ltohs(b) (b)
80 #else
81 #if __BYTE_ORDER == __BIG_ENDIAN
82 #define htoll(b)  \
83           (((((b)      ) & 0xFF) << 24) | \
84                ((((b) >>  8) & 0xFF) << 16) | \
85                    ((((b) >> 16) & 0xFF) <<  8) | \
86                    ((((b) >> 24) & 0xFF)      ))
87 #define htols(b) \
88           (((((b)      ) & 0xFF) << 8) | \
89                    ((((b) >> 8) & 0xFF)      ))
90 #define ltohl(b) htoll(b)
91 #define ltohs(b) htols(b)
92 #else
93 #error "Endianess not defined"
94 #endif
95 #endif
96
97
98 static int check_header(int fd)
99 {
100         int type, size, formtype;
101         int fmt, hsize, fact;
102         short format, chans;
103         int freq;
104         int data;
105         if (read(fd, &type, 4) != 4) {
106                 ast_log(LOG_WARNING, "Read failed (type)\n");
107                 return -1;
108         }
109         if (read(fd, &size, 4) != 4) {
110                 ast_log(LOG_WARNING, "Read failed (size)\n");
111                 return -1;
112         }
113         size = ltohl(size);
114         if (read(fd, &formtype, 4) != 4) {
115                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
116                 return -1;
117         }
118         if (memcmp(&type, "RIFF", 4)) {
119                 ast_log(LOG_WARNING, "Does not begin with RIFF\n");
120                 return -1;
121         }
122         if (memcmp(&formtype, "WAVE", 4)) {
123                 ast_log(LOG_WARNING, "Does not contain WAVE\n");
124                 return -1;
125         }
126         if (read(fd, &fmt, 4) != 4) {
127                 ast_log(LOG_WARNING, "Read failed (fmt)\n");
128                 return -1;
129         }
130         if (memcmp(&fmt, "fmt ", 4)) {
131                 ast_log(LOG_WARNING, "Does not say fmt\n");
132                 return -1;
133         }
134         if (read(fd, &hsize, 4) != 4) {
135                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
136                 return -1;
137         }
138         if (ltohl(hsize) != 20) {
139                 ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
140                 return -1;
141         }
142         if (read(fd, &format, 2) != 2) {
143                 ast_log(LOG_WARNING, "Read failed (format)\n");
144                 return -1;
145         }
146         if (ltohs(format) != 49) {
147                 ast_log(LOG_WARNING, "Not a GSM file %d\n", ltohs(format));
148                 return -1;
149         }
150         if (read(fd, &chans, 2) != 2) {
151                 ast_log(LOG_WARNING, "Read failed (format)\n");
152                 return -1;
153         }
154         if (ltohs(chans) != 1) {
155                 ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
156                 return -1;
157         }
158         if (read(fd, &freq, 4) != 4) {
159                 ast_log(LOG_WARNING, "Read failed (freq)\n");
160                 return -1;
161         }
162         if (ltohl(freq) != 8000) {
163                 ast_log(LOG_WARNING, "Unexpected freqency %d\n", ltohl(freq));
164                 return -1;
165         }
166         /* Ignore the byte frequency */
167         if (read(fd, &freq, 4) != 4) {
168                 ast_log(LOG_WARNING, "Read failed (X_1)\n");
169                 return -1;
170         }
171         /* Ignore the two weird fields */
172         if (read(fd, &freq, 4) != 4) {
173                 ast_log(LOG_WARNING, "Read failed (X_2/X_3)\n");
174                 return -1;
175         }
176         /* Ignore the byte frequency */
177         if (read(fd, &freq, 4) != 4) {
178                 ast_log(LOG_WARNING, "Read failed (Y_1)\n");
179                 return -1;
180         }
181         /* Check for the word fact */
182         if (read(fd, &fact, 4) != 4) {
183                 ast_log(LOG_WARNING, "Read failed (fact)\n");
184                 return -1;
185         }
186         if (memcmp(&fact, "fact", 4)) {
187                 ast_log(LOG_WARNING, "Does not say fact\n");
188                 return -1;
189         }
190         /* Ignore the "fact value" */
191         if (read(fd, &fact, 4) != 4) {
192                 ast_log(LOG_WARNING, "Read failed (fact header)\n");
193                 return -1;
194         }
195         if (read(fd, &fact, 4) != 4) {
196                 ast_log(LOG_WARNING, "Read failed (fact value)\n");
197                 return -1;
198         }
199         /* Check for the word data */
200         if (read(fd, &data, 4) != 4) {
201                 ast_log(LOG_WARNING, "Read failed (data)\n");
202                 return -1;
203         }
204         if (memcmp(&data, "data", 4)) {
205                 ast_log(LOG_WARNING, "Does not say data\n");
206                 return -1;
207         }
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 + 1) & ~0x1);
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, const 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         if (ast_mutex_lock(&wav_lock)) {
397                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
398                 return;
399         }
400         glistcnt--;
401         ast_mutex_unlock(&wav_lock);
402         ast_update_use_count();
403         /* Pad to even length */
404         if (lseek(s->fd, 0, SEEK_END) & 0x1)
405                 write(s->fd, &zero, 1);
406         close(s->fd);
407         free(s);
408         s = NULL;
409 }
410
411 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
412 {
413         int res;
414         char msdata[66];
415         /* Send a frame from the file to the appropriate channel */
416
417         s->fr.frametype = AST_FRAME_VOICE;
418         s->fr.subclass = AST_FORMAT_GSM;
419         s->fr.offset = AST_FRIENDLY_OFFSET;
420         s->fr.samples = 160;
421         s->fr.datalen = 33;
422         s->fr.mallocd = 0;
423         if (s->secondhalf) {
424                 /* Just return a frame based on the second GSM frame */
425                 s->fr.data = s->gsm + 33;
426         } else {
427                 if ((res = read(s->fd, msdata, 65)) != 65) {
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->gsm);
434                 s->fr.data = s->gsm;
435         }
436         s->secondhalf = !s->secondhalf;
437         *whennext = 160;
438         return &s->fr;
439 }
440
441 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
442 {
443         int res;
444         char msdata[66];
445         int len =0;
446         int alreadyms=0;
447         if (f->frametype != AST_FRAME_VOICE) {
448                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
449                 return -1;
450         }
451         if (f->subclass != AST_FORMAT_GSM) {
452                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
453                 return -1;
454         }
455         if (!(f->datalen % 65)) 
456                 alreadyms = 1;
457         while(len < f->datalen) {
458                 if (alreadyms) {
459                         fs->secondhalf = 0;
460                         if ((res = write(fs->fd, f->data + len, 65)) != 65) {
461                                 ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
462                                 return -1;
463                         }
464                         update_header(fs->fd);
465                         len += 65;
466                 } else {
467                         if (fs->secondhalf) {
468                                 memcpy(fs->gsm + 33, f->data + len, 33);
469                                 conv66(fs->gsm, msdata);
470                                 if ((res = write(fs->fd, msdata, 65)) != 65) {
471                                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
472                                         return -1;
473                                 }
474                                 update_header(fs->fd);
475                         } else {
476                                 /* Copy the data and do nothing */
477                                 memcpy(fs->gsm, f->data + len, 33);
478                         }
479                         fs->secondhalf = !fs->secondhalf;
480                         len += 33;
481                 }
482         }
483         return 0;
484 }
485
486 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
487 {
488         off_t offset=0,distance,cur,min,max;
489         min = 60;
490         cur = lseek(fs->fd, 0, SEEK_CUR);
491         max = lseek(fs->fd, 0, SEEK_END);
492         /* I'm getting sloppy here, I'm only going to go to even splits of the 2
493          * frames, if you want tighter cuts use format_gsm, format_pcm, or format_wav */
494         distance = (sample_offset/320) * 65;
495         if(whence == SEEK_SET)
496                 offset = distance + min;
497         else if(whence == SEEK_CUR || whence == SEEK_FORCECUR)
498                 offset = distance + cur;
499         else if(whence == SEEK_END)
500                 offset = max - distance;
501         /* always protect against seeking past end of header */
502         offset = (offset < min)?min:offset;
503         if (whence != SEEK_FORCECUR) {
504                 offset = (offset > max)?max:offset;
505         } else if (offset > max) {
506                 int i;
507                 lseek(fs->fd, 0, SEEK_END);
508                 for (i=0; i< (offset - max) / 65; i++) {
509                         write(fs->fd, msgsm_silence, 65);
510                 }
511         }
512         fs->secondhalf = 0;
513         return lseek(fs->fd, offset, SEEK_SET);
514 }
515
516 static int wav_trunc(struct ast_filestream *fs)
517 {
518         if(ftruncate(fs->fd, lseek(fs->fd, 0, SEEK_CUR)))
519                 return -1;
520         return update_header(fs->fd);
521 }
522
523 static long wav_tell(struct ast_filestream *fs)
524 {
525         off_t offset;
526         offset = lseek(fs->fd, 0, SEEK_CUR);
527         /* since this will most likely be used later in play or record, lets stick
528          * to that level of resolution, just even frames boundaries */
529         return (offset - 52)/65*320;
530 }
531
532 static char *wav_getcomment(struct ast_filestream *s)
533 {
534         return NULL;
535 }
536
537 int load_module()
538 {
539         return ast_format_register(name, exts, AST_FORMAT_GSM,
540                                                                 wav_open,
541                                                                 wav_rewrite,
542                                                                 wav_write,
543                                                                 wav_seek,
544                                                                 wav_trunc,
545                                                                 wav_tell,
546                                                                 wav_read,
547                                                                 wav_close,
548                                                                 wav_getcomment);
549                                                                 
550                                                                 
551 }
552
553 int unload_module()
554 {
555         return ast_format_unregister(name);
556 }       
557
558 int usecount()
559 {
560         int res;
561         if (ast_mutex_lock(&wav_lock)) {
562                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
563                 return -1;
564         }
565         res = glistcnt;
566         ast_mutex_unlock(&wav_lock);
567         return res;
568 }
569
570 char *description()
571 {
572         return desc;
573 }
574
575
576 char *key()
577 {
578         return ASTERISK_GPL_KEY;
579 }