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