update MANY more files with proper copyright/license info (thanks Ian!)
[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         int fd; /* 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(int fd)
108 {
109         int type, size, formtype;
110         int fmt, hsize, fact;
111         short format, chans;
112         int freq;
113         int data;
114         if (read(fd, &type, 4) != 4) {
115                 ast_log(LOG_WARNING, "Read failed (type)\n");
116                 return -1;
117         }
118         if (read(fd, &size, 4) != 4) {
119                 ast_log(LOG_WARNING, "Read failed (size)\n");
120                 return -1;
121         }
122         size = ltohl(size);
123         if (read(fd, &formtype, 4) != 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 (read(fd, &fmt, 4) != 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 (read(fd, &hsize, 4) != 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 (read(fd, &format, 2) != 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 (read(fd, &chans, 2) != 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 (read(fd, &freq, 4) != 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 (read(fd, &freq, 4) != 4) {
177                 ast_log(LOG_WARNING, "Read failed (X_1)\n");
178                 return -1;
179         }
180         /* Ignore the two weird fields */
181         if (read(fd, &freq, 4) != 4) {
182                 ast_log(LOG_WARNING, "Read failed (X_2/X_3)\n");
183                 return -1;
184         }
185         /* Ignore the byte frequency */
186         if (read(fd, &freq, 4) != 4) {
187                 ast_log(LOG_WARNING, "Read failed (Y_1)\n");
188                 return -1;
189         }
190         /* Check for the word fact */
191         if (read(fd, &fact, 4) != 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 (read(fd, &fact, 4) != 4) {
201                 ast_log(LOG_WARNING, "Read failed (fact header)\n");
202                 return -1;
203         }
204         if (read(fd, &fact, 4) != 4) {
205                 ast_log(LOG_WARNING, "Read failed (fact value)\n");
206                 return -1;
207         }
208         /* Check for the word data */
209         if (read(fd, &data, 4) != 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 (read(fd, &data, 4) != 4) {
219                 ast_log(LOG_WARNING, "Read failed (data)\n");
220                 return -1;
221         }
222         return 0;
223 }
224
225 static int update_header(int fd)
226 {
227         off_t cur,end,bytes;
228         int datalen,filelen;
229         
230         cur = lseek(fd, 0, SEEK_CUR);
231         end = lseek(fd, 0, SEEK_END);
232         /* in a gsm WAV, data starts 60 bytes in */
233         bytes = end - 60;
234         datalen = htoll((bytes + 1) & ~0x1);
235         filelen = htoll(52 + ((bytes + 1) & ~0x1));
236         if (cur < 0) {
237                 ast_log(LOG_WARNING, "Unable to find our position\n");
238                 return -1;
239         }
240         if (lseek(fd, 4, SEEK_SET) != 4) {
241                 ast_log(LOG_WARNING, "Unable to set our position\n");
242                 return -1;
243         }
244         if (write(fd, &filelen, 4) != 4) {
245                 ast_log(LOG_WARNING, "Unable to set write file size\n");
246                 return -1;
247         }
248         if (lseek(fd, 56, SEEK_SET) != 56) {
249                 ast_log(LOG_WARNING, "Unable to set our position\n");
250                 return -1;
251         }
252         if (write(fd, &datalen, 4) != 4) {
253                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
254                 return -1;
255         }
256         if (lseek(fd, cur, SEEK_SET) != cur) {
257                 ast_log(LOG_WARNING, "Unable to return to position\n");
258                 return -1;
259         }
260         return 0;
261 }
262
263 static int write_header(int fd)
264 {
265         unsigned int hz=htoll(8000);
266         unsigned int bhz = htoll(1625);
267         unsigned int hs = htoll(20);
268         unsigned short fmt = htols(49);
269         unsigned short chans = htols(1);
270         unsigned int fhs = htoll(4);
271         unsigned int x_1 = htoll(65);
272         unsigned short x_2 = htols(2);
273         unsigned short x_3 = htols(320);
274         unsigned int y_1 = htoll(20160);
275         unsigned int size = htoll(0);
276         /* Write a GSM header, ignoring sizes which will be filled in later */
277         if (write(fd, "RIFF", 4) != 4) {
278                 ast_log(LOG_WARNING, "Unable to write header\n");
279                 return -1;
280         }
281         if (write(fd, &size, 4) != 4) {
282                 ast_log(LOG_WARNING, "Unable to write header\n");
283                 return -1;
284         }
285         if (write(fd, "WAVEfmt ", 8) != 8) {
286                 ast_log(LOG_WARNING, "Unable to write header\n");
287                 return -1;
288         }
289         if (write(fd, &hs, 4) != 4) {
290                 ast_log(LOG_WARNING, "Unable to write header\n");
291                 return -1;
292         }
293         if (write(fd, &fmt, 2) != 2) {
294                 ast_log(LOG_WARNING, "Unable to write header\n");
295                 return -1;
296         }
297         if (write(fd, &chans, 2) != 2) {
298                 ast_log(LOG_WARNING, "Unable to write header\n");
299                 return -1;
300         }
301         if (write(fd, &hz, 4) != 4) {
302                 ast_log(LOG_WARNING, "Unable to write header\n");
303                 return -1;
304         }
305         if (write(fd, &bhz, 4) != 4) {
306                 ast_log(LOG_WARNING, "Unable to write header\n");
307                 return -1;
308         }
309         if (write(fd, &x_1, 4) != 4) {
310                 ast_log(LOG_WARNING, "Unable to write header\n");
311                 return -1;
312         }
313         if (write(fd, &x_2, 2) != 2) {
314                 ast_log(LOG_WARNING, "Unable to write header\n");
315                 return -1;
316         }
317         if (write(fd, &x_3, 2) != 2) {
318                 ast_log(LOG_WARNING, "Unable to write header\n");
319                 return -1;
320         }
321         if (write(fd, "fact", 4) != 4) {
322                 ast_log(LOG_WARNING, "Unable to write header\n");
323                 return -1;
324         }
325         if (write(fd, &fhs, 4) != 4) {
326                 ast_log(LOG_WARNING, "Unable to write header\n");
327                 return -1;
328         }
329         if (write(fd, &y_1, 4) != 4) {
330                 ast_log(LOG_WARNING, "Unable to write header\n");
331                 return -1;
332         }
333         if (write(fd, "data", 4) != 4) {
334                 ast_log(LOG_WARNING, "Unable to write header\n");
335                 return -1;
336         }
337         if (write(fd, &size, 4) != 4) {
338                 ast_log(LOG_WARNING, "Unable to write header\n");
339                 return -1;
340         }
341         return 0;
342 }
343
344 static struct ast_filestream *wav_open(int fd)
345 {
346         /* We don't have any header to read or anything really, but
347            if we did, it would go here.  We also might want to check
348            and be sure it's a valid file.  */
349         struct ast_filestream *tmp;
350         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
351                 memset(tmp, 0, sizeof(struct ast_filestream));
352                 if (check_header(fd)) {
353                         free(tmp);
354                         return NULL;
355                 }
356                 if (ast_mutex_lock(&wav_lock)) {
357                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
358                         free(tmp);
359                         return NULL;
360                 }
361                 tmp->fd = fd;
362                 tmp->fr.data = tmp->gsm;
363                 tmp->fr.frametype = AST_FRAME_VOICE;
364                 tmp->fr.subclass = AST_FORMAT_GSM;
365                 /* datalen will vary for each frame */
366                 tmp->fr.src = name;
367                 tmp->fr.mallocd = 0;
368                 tmp->secondhalf = 0;
369                 glistcnt++;
370                 ast_mutex_unlock(&wav_lock);
371                 ast_update_use_count();
372         }
373         return tmp;
374 }
375
376 static struct ast_filestream *wav_rewrite(int fd, const char *comment)
377 {
378         /* We don't have any header to read or anything really, but
379            if we did, it would go here.  We also might want to check
380            and be sure it's a valid file.  */
381         struct ast_filestream *tmp;
382         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
383                 memset(tmp, 0, sizeof(struct ast_filestream));
384                 if (write_header(fd)) {
385                         free(tmp);
386                         return NULL;
387                 }
388                 if (ast_mutex_lock(&wav_lock)) {
389                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
390                         free(tmp);
391                         return NULL;
392                 }
393                 tmp->fd = fd;
394                 glistcnt++;
395                 ast_mutex_unlock(&wav_lock);
396                 ast_update_use_count();
397         } else
398                 ast_log(LOG_WARNING, "Out of memory\n");
399         return tmp;
400 }
401
402 static void wav_close(struct ast_filestream *s)
403 {
404         char zero = 0;
405         if (ast_mutex_lock(&wav_lock)) {
406                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
407                 return;
408         }
409         glistcnt--;
410         ast_mutex_unlock(&wav_lock);
411         ast_update_use_count();
412         /* Pad to even length */
413         if (lseek(s->fd, 0, SEEK_END) & 0x1)
414                 write(s->fd, &zero, 1);
415         close(s->fd);
416         free(s);
417         s = NULL;
418 }
419
420 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
421 {
422         int res;
423         char msdata[66];
424         /* Send a frame from the file to the appropriate channel */
425
426         s->fr.frametype = AST_FRAME_VOICE;
427         s->fr.subclass = AST_FORMAT_GSM;
428         s->fr.offset = AST_FRIENDLY_OFFSET;
429         s->fr.samples = 160;
430         s->fr.datalen = 33;
431         s->fr.mallocd = 0;
432         if (s->secondhalf) {
433                 /* Just return a frame based on the second GSM frame */
434                 s->fr.data = s->gsm + 33;
435         } else {
436                 if ((res = read(s->fd, msdata, 65)) != 65) {
437                         if (res && (res != 1))
438                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
439                         return NULL;
440                 }
441                 /* Convert from MS format to two real GSM frames */
442                 conv65(msdata, s->gsm);
443                 s->fr.data = s->gsm;
444         }
445         s->secondhalf = !s->secondhalf;
446         *whennext = 160;
447         return &s->fr;
448 }
449
450 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
451 {
452         int res;
453         char msdata[66];
454         int len =0;
455         int alreadyms=0;
456         if (f->frametype != AST_FRAME_VOICE) {
457                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
458                 return -1;
459         }
460         if (f->subclass != AST_FORMAT_GSM) {
461                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
462                 return -1;
463         }
464         if (!(f->datalen % 65)) 
465                 alreadyms = 1;
466         while(len < f->datalen) {
467                 if (alreadyms) {
468                         fs->secondhalf = 0;
469                         if ((res = write(fs->fd, f->data + len, 65)) != 65) {
470                                 ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
471                                 return -1;
472                         }
473                         update_header(fs->fd);
474                         len += 65;
475                 } else {
476                         if (fs->secondhalf) {
477                                 memcpy(fs->gsm + 33, f->data + len, 33);
478                                 conv66(fs->gsm, msdata);
479                                 if ((res = write(fs->fd, msdata, 65)) != 65) {
480                                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
481                                         return -1;
482                                 }
483                                 update_header(fs->fd);
484                         } else {
485                                 /* Copy the data and do nothing */
486                                 memcpy(fs->gsm, f->data + len, 33);
487                         }
488                         fs->secondhalf = !fs->secondhalf;
489                         len += 33;
490                 }
491         }
492         return 0;
493 }
494
495 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
496 {
497         off_t offset=0,distance,cur,min,max;
498         min = 60;
499         cur = lseek(fs->fd, 0, SEEK_CUR);
500         max = lseek(fs->fd, 0, SEEK_END);
501         /* I'm getting sloppy here, I'm only going to go to even splits of the 2
502          * frames, if you want tighter cuts use format_gsm, format_pcm, or format_wav */
503         distance = (sample_offset/320) * 65;
504         if(whence == SEEK_SET)
505                 offset = distance + min;
506         else if(whence == SEEK_CUR || whence == SEEK_FORCECUR)
507                 offset = distance + cur;
508         else if(whence == SEEK_END)
509                 offset = max - distance;
510         /* always protect against seeking past end of header */
511         offset = (offset < min)?min:offset;
512         if (whence != SEEK_FORCECUR) {
513                 offset = (offset > max)?max:offset;
514         } else if (offset > max) {
515                 int i;
516                 lseek(fs->fd, 0, SEEK_END);
517                 for (i=0; i< (offset - max) / 65; i++) {
518                         write(fs->fd, msgsm_silence, 65);
519                 }
520         }
521         fs->secondhalf = 0;
522         return lseek(fs->fd, offset, SEEK_SET);
523 }
524
525 static int wav_trunc(struct ast_filestream *fs)
526 {
527         if(ftruncate(fs->fd, lseek(fs->fd, 0, SEEK_CUR)))
528                 return -1;
529         return update_header(fs->fd);
530 }
531
532 static long wav_tell(struct ast_filestream *fs)
533 {
534         off_t offset;
535         offset = lseek(fs->fd, 0, SEEK_CUR);
536         /* since this will most likely be used later in play or record, lets stick
537          * to that level of resolution, just even frames boundaries */
538         return (offset - 52)/65*320;
539 }
540
541 static char *wav_getcomment(struct ast_filestream *s)
542 {
543         return NULL;
544 }
545
546 int load_module()
547 {
548         return ast_format_register(name, exts, AST_FORMAT_GSM,
549                                                                 wav_open,
550                                                                 wav_rewrite,
551                                                                 wav_write,
552                                                                 wav_seek,
553                                                                 wav_trunc,
554                                                                 wav_tell,
555                                                                 wav_read,
556                                                                 wav_close,
557                                                                 wav_getcomment);
558                                                                 
559                                                                 
560 }
561
562 int unload_module()
563 {
564         return ast_format_unregister(name);
565 }       
566
567 int usecount()
568 {
569         return glistcnt;
570 }
571
572 char *description()
573 {
574         return desc;
575 }
576
577
578 char *key()
579 {
580         return ASTERISK_GPL_KEY;
581 }