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