Convert between MS and non-MS 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_channel *owner;
47         struct ast_frame fr;                            /* Frame information */
48         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
49         char empty;                                                     /* Empty character */
50         unsigned char gsm[66];                          /* Two Real GSM Frames */
51         int foffset;
52         int secondhalf;                                         /* Are we on the second half */
53         int lasttimeout;
54         struct timeval last;
55         int adj;
56         struct ast_filestream *next;
57 };
58
59
60 static struct ast_filestream *glist = NULL;
61 static pthread_mutex_t wav_lock = AST_MUTEX_INITIALIZER;
62 static int glistcnt = 0;
63
64 static char *name = "wav49";
65 static char *desc = "Microsoft WAV format (Proprietary GSM)";
66 static char *exts = "WAV";
67
68 #if __BYTE_ORDER == __LITTLE_ENDIAN
69 #define htoll(b) (b)
70 #define htols(b) (b)
71 #define ltohl(b) (b)
72 #define ltohs(b) (b)
73 #else
74 #if __BYTE_ORDER == __BIG_ENDIAN
75 #define htoll(b)  \
76           (((((b)      ) & 0xFF) << 24) | \
77                ((((b) >>  8) & 0xFF) << 16) | \
78                    ((((b) >> 16) & 0xFF) <<  8) | \
79                    ((((b) >> 24) & 0xFF)      ))
80 #define htols(b) \
81           (((((b)      ) & 0xFF) << 8) | \
82                    ((((b) >> 8) & 0xFF)      ))
83 #define ltohl(b) htoll(b)
84 #define ltohs(b) htols(b)
85 #else
86 #error "Endianess not defined"
87 #endif
88 #endif
89
90
91 static int check_header(int fd)
92 {
93         int type, size, formtype;
94         int fmt, hsize, fact;
95         short format, chans;
96         int freq;
97         int data;
98         if (read(fd, &type, 4) != 4) {
99                 ast_log(LOG_WARNING, "Read failed (type)\n");
100                 return -1;
101         }
102         if (read(fd, &size, 4) != 4) {
103                 ast_log(LOG_WARNING, "Read failed (size)\n");
104                 return -1;
105         }
106         size = ltohl(size);
107         if (read(fd, &formtype, 4) != 4) {
108                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
109                 return -1;
110         }
111         if (memcmp(&type, "RIFF", 4)) {
112                 ast_log(LOG_WARNING, "Does not begin with RIFF\n");
113                 return -1;
114         }
115         if (memcmp(&formtype, "WAVE", 4)) {
116                 ast_log(LOG_WARNING, "Does not contain WAVE\n");
117                 return -1;
118         }
119         if (read(fd, &fmt, 4) != 4) {
120                 ast_log(LOG_WARNING, "Read failed (fmt)\n");
121                 return -1;
122         }
123         if (memcmp(&fmt, "fmt ", 4)) {
124                 ast_log(LOG_WARNING, "Does not say fmt\n");
125                 return -1;
126         }
127         if (read(fd, &hsize, 4) != 4) {
128                 ast_log(LOG_WARNING, "Read failed (formtype)\n");
129                 return -1;
130         }
131         if (ltohl(hsize) != 20) {
132                 ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
133                 return -1;
134         }
135         if (read(fd, &format, 2) != 2) {
136                 ast_log(LOG_WARNING, "Read failed (format)\n");
137                 return -1;
138         }
139         if (ltohs(format) != 49) {
140                 ast_log(LOG_WARNING, "Not a GSM file %d\n", ltohs(format));
141                 return -1;
142         }
143         if (read(fd, &chans, 2) != 2) {
144                 ast_log(LOG_WARNING, "Read failed (format)\n");
145                 return -1;
146         }
147         if (ltohs(chans) != 1) {
148                 ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
149                 return -1;
150         }
151         if (read(fd, &freq, 4) != 4) {
152                 ast_log(LOG_WARNING, "Read failed (freq)\n");
153                 return -1;
154         }
155         if (ltohl(freq) != 8000) {
156                 ast_log(LOG_WARNING, "Unexpected freqency %d\n", ltohl(freq));
157                 return -1;
158         }
159         /* Ignore the byte frequency */
160         if (read(fd, &freq, 4) != 4) {
161                 ast_log(LOG_WARNING, "Read failed (X_1)\n");
162                 return -1;
163         }
164         /* Ignore the two weird fields */
165         if (read(fd, &freq, 4) != 4) {
166                 ast_log(LOG_WARNING, "Read failed (X_2/X_3)\n");
167                 return -1;
168         }
169         /* Ignore the byte frequency */
170         if (read(fd, &freq, 4) != 4) {
171                 ast_log(LOG_WARNING, "Read failed (Y_1)\n");
172                 return -1;
173         }
174         /* Check for the word fact */
175         if (read(fd, &fact, 4) != 4) {
176                 ast_log(LOG_WARNING, "Read failed (fact)\n");
177                 return -1;
178         }
179         if (memcmp(&fact, "fact", 4)) {
180                 ast_log(LOG_WARNING, "Does not say fact\n");
181                 return -1;
182         }
183         /* Ignore the "fact value" */
184         if (read(fd, &fact, 4) != 4) {
185                 ast_log(LOG_WARNING, "Read failed (fact header)\n");
186                 return -1;
187         }
188         if (read(fd, &fact, 4) != 4) {
189                 ast_log(LOG_WARNING, "Read failed (fact value)\n");
190                 return -1;
191         }
192         /* Check for the word data */
193         if (read(fd, &data, 4) != 4) {
194                 ast_log(LOG_WARNING, "Read failed (data)\n");
195                 return -1;
196         }
197         if (memcmp(&data, "data", 4)) {
198                 ast_log(LOG_WARNING, "Does not say data\n");
199                 return -1;
200         }
201         /* Ignore the data length */
202         if (read(fd, &data, 4) != 4) {
203                 ast_log(LOG_WARNING, "Read failed (data)\n");
204                 return -1;
205         }
206         return 0;
207 }
208
209 static int update_header(int fd)
210 {
211         off_t cur,end,bytes;
212         int datalen,filelen;
213         
214         cur = lseek(fd, 0, SEEK_CUR);
215         end = lseek(fd, 0, SEEK_END);
216         bytes = end - 52;
217         datalen = htoll(bytes);
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_pthread_mutex_lock(&wav_lock)) {
340                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
341                         free(tmp);
342                         return NULL;
343                 }
344                 tmp->next = glist;
345                 glist = tmp;
346                 tmp->fd = fd;
347                 tmp->owner = NULL;
348                 tmp->fr.data = tmp->gsm;
349                 tmp->fr.frametype = AST_FRAME_VOICE;
350                 tmp->fr.subclass = AST_FORMAT_GSM;
351                 /* datalen will vary for each frame */
352                 tmp->fr.src = name;
353                 tmp->fr.mallocd = 0;
354                 tmp->secondhalf = 0;
355                 tmp->lasttimeout = -1;
356                 glistcnt++;
357                 ast_pthread_mutex_unlock(&wav_lock);
358                 ast_update_use_count();
359         }
360         return tmp;
361 }
362
363 static struct ast_filestream *wav_rewrite(int fd, char *comment)
364 {
365         /* We don't have any header to read or anything really, but
366            if we did, it would go here.  We also might want to check
367            and be sure it's a valid file.  */
368         struct ast_filestream *tmp;
369         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
370                 memset(tmp, 0, sizeof(struct ast_filestream));
371                 if (write_header(fd)) {
372                         free(tmp);
373                         return NULL;
374                 }
375                 if (ast_pthread_mutex_lock(&wav_lock)) {
376                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
377                         free(tmp);
378                         return NULL;
379                 }
380                 tmp->next = glist;
381                 glist = tmp;
382                 tmp->fd = fd;
383                 tmp->owner = NULL;
384                 tmp->lasttimeout = -1;
385                 glistcnt++;
386                 ast_pthread_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 struct ast_frame *wav_read(struct ast_filestream *s)
394 {
395         return NULL;
396 }
397
398 static void wav_close(struct ast_filestream *s)
399 {
400         struct ast_filestream *tmp, *tmpl = NULL;
401         char zero = 0;
402         if (ast_pthread_mutex_lock(&wav_lock)) {
403                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
404                 return;
405         }
406         tmp = glist;
407         while(tmp) {
408                 if (tmp == s) {
409                         if (tmpl)
410                                 tmpl->next = tmp->next;
411                         else
412                                 glist = tmp->next;
413                         break;
414                 }
415                 tmpl = tmp;
416                 tmp = tmp->next;
417         }
418         glistcnt--;
419         if (s->owner) {
420                 s->owner->stream = NULL;
421                 if (s->owner->streamid > -1)
422                         ast_sched_del(s->owner->sched, s->owner->streamid);
423                 s->owner->streamid = -1;
424         }
425         ast_pthread_mutex_unlock(&wav_lock);
426         ast_update_use_count();
427         if (!tmp) 
428                 ast_log(LOG_WARNING, "Freeing a filestream we don't seem to own\n");
429         /* Pad to even length */
430         if (s->bytes & 0x1)
431                 write(s->fd, &zero, 1);
432         close(s->fd);
433         free(s);
434         s = NULL;
435 }
436
437 static int ast_read_callback(void *data)
438 {
439         int retval = 0;
440         int res;
441         int delay = 20;
442         struct ast_filestream *s = data;
443         char msdata[66];
444         struct timeval tv;
445         /* Send a frame from the file to the appropriate channel */
446
447         s->fr.frametype = AST_FRAME_VOICE;
448         s->fr.subclass = AST_FORMAT_GSM;
449         s->fr.offset = AST_FRIENDLY_OFFSET;
450         s->fr.samples = 160;
451         s->fr.datalen = 33;
452         s->fr.mallocd = 0;
453         if (s->secondhalf) {
454                 /* Just return a frame based on the second GSM frame */
455                 s->fr.data = s->gsm + 33;
456         } else {
457                 if ((res = read(s->fd, msdata, 65)) != 65) {
458                         if (res && (res != 1))
459                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
460                         s->owner->streamid = -1;
461                         return 0;
462                 }
463                 /* Convert from MS format to two real GSM frames */
464                 conv65(msdata, s->gsm);
465                 s->fr.data = s->gsm;
466         }
467         s->secondhalf = !s->secondhalf;
468         /* Lastly, process the frame */
469         if (ast_write(s->owner, &s->fr)) {
470                 ast_log(LOG_WARNING, "Failed to write frame\n");
471                 s->owner->streamid = -1;
472                 return 0;
473         }
474         if (s->last.tv_usec || s->last.tv_usec) {
475                 int ms;
476                 gettimeofday(&tv, NULL);
477                 ms = 1000 * (tv.tv_sec - s->last.tv_sec) + 
478                         (tv.tv_usec - s->last.tv_usec) / 1000;
479                 s->last.tv_sec = tv.tv_sec;
480                 s->last.tv_usec = tv.tv_usec;
481                 if ((ms - delay) * (ms - delay) > 4) {
482                         /* Compensate if we're more than 2 ms off */
483                         s->adj -= (ms - delay);
484                 }
485 #if 0
486                 fprintf(stdout, "Delay is %d, adjustment is %d, last was %d\n", delay, s->adj, ms);
487 #endif
488                 delay += s->adj;
489                 if (delay < 1)
490                         delay = 1;
491         } else
492                 gettimeofday(&s->last, NULL);
493         if (s->lasttimeout != delay) {
494                 /* We'll install the next timeout now. */
495                 s->owner->streamid = ast_sched_add(s->owner->sched,
496                                 delay, ast_read_callback, s); 
497                 s->lasttimeout = delay;
498         } else {
499                 /* Just come back again at the same time */
500                 retval = -1;
501         }
502         return retval;
503 }
504
505 static int wav_apply(struct ast_channel *c, struct ast_filestream *s)
506 {
507         /* Select our owner for this stream, and get the ball rolling. */
508         s->owner = c;
509         return 0;
510 }
511
512 static int wav_play(struct ast_filestream *s)
513 {
514         ast_read_callback(s);
515         return 0;
516 }
517
518 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
519 {
520         int res;
521         char msdata[66];
522         int len =0;
523         int alreadyms=0;
524         if (f->frametype != AST_FRAME_VOICE) {
525                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
526                 return -1;
527         }
528         if (f->subclass != AST_FORMAT_GSM) {
529                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
530                 return -1;
531         }
532         if (!(f->datalen % 65)) 
533                 alreadyms = 1;
534         while(len < f->datalen) {
535                 if (alreadyms) {
536                         fs->secondhalf = 0;
537                         if ((res = write(fs->fd, f->data + len, 65)) != 65) {
538                                 ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
539                                 return -1;
540                         }
541                         fs->bytes += 65;
542                         update_header(fs->fd);
543                         len += 65;
544                 } else {
545                         if (fs->secondhalf) {
546                                 memcpy(fs->gsm + 33, f->data + len, 33);
547                                 conv66(fs->gsm, msdata);
548                                 if ((res = write(fs->fd, msdata, 65)) != 65) {
549                                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
550                                         return -1;
551                                 }
552                                 fs->bytes += 65;
553                                 update_header(fs->fd);
554                         } else {
555                                 /* Copy the data and do nothing */
556                                 memcpy(fs->gsm, f->data + len, 33);
557                         }
558                         fs->secondhalf = !fs->secondhalf;
559                         len += 33;
560                 }
561         }
562         return 0;
563 }
564
565 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
566 {
567         off_t offset=0,distance,cur,min,max;
568         min = 52;
569         cur = lseek(fs->fd, 0, SEEK_CUR);
570         max = lseek(fs->fd, 0, SEEK_END);
571         /* I'm getting sloppy here, I'm only going to go to even splits of the 2
572          * frames, if you want tighter cuts use format_gsm, format_pcm, or format_wav */
573         distance = (sample_offset/320) * 65;
574         if(whence == SEEK_SET)
575                 offset = distance + min;
576         if(whence == SEEK_CUR)
577                 offset = distance + cur;
578         if(whence == SEEK_END)
579                 offset = max - distance;
580         offset = (offset < min)?min:offset;
581         offset = (offset > max)?max:offset;
582         fs->secondhalf = 0;
583         return lseek(fs->fd, offset, SEEK_SET);
584 }
585
586 static int wav_trunc(struct ast_filestream *fs)
587 {
588         if(ftruncate(fs->fd, lseek(fs->fd, 0, SEEK_CUR)))
589                 return -1;
590         return update_header(fs->fd);
591 }
592
593 static long wav_tell(struct ast_filestream *fs)
594 {
595         off_t offset;
596         offset = lseek(fs->fd, 0, SEEK_CUR);
597         /* since this will most likely be used later in play or record, lets stick
598          * to that level of resolution, just even frames boundaries */
599         return (offset - 52)/65/320;
600 }
601
602 static char *wav_getcomment(struct ast_filestream *s)
603 {
604         return NULL;
605 }
606
607 int load_module()
608 {
609         return ast_format_register(name, exts, AST_FORMAT_GSM,
610                                                                 wav_open,
611                                                                 wav_rewrite,
612                                                                 wav_apply,
613                                                                 wav_play,
614                                                                 wav_write,
615                                                                 wav_seek,
616                                                                 wav_trunc,
617                                                                 wav_tell,
618                                                                 wav_read,
619                                                                 wav_close,
620                                                                 wav_getcomment);
621                                                                 
622                                                                 
623 }
624
625 int unload_module()
626 {
627         struct ast_filestream *tmp, *tmpl;
628         if (ast_pthread_mutex_lock(&wav_lock)) {
629                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
630                 return -1;
631         }
632         tmp = glist;
633         while(tmp) {
634                 if (tmp->owner)
635                         ast_softhangup(tmp->owner, AST_SOFTHANGUP_APPUNLOAD);
636                 tmpl = tmp;
637                 tmp = tmp->next;
638                 free(tmpl);
639         }
640         ast_pthread_mutex_unlock(&wav_lock);
641         return ast_format_unregister(name);
642 }       
643
644 int usecount()
645 {
646         int res;
647         if (ast_pthread_mutex_lock(&wav_lock)) {
648                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
649                 return -1;
650         }
651         res = glistcnt;
652         ast_pthread_mutex_unlock(&wav_lock);
653         return res;
654 }
655
656 char *description()
657 {
658         return desc;
659 }
660
661
662 char *key()
663 {
664         return ASTERISK_GPL_KEY;
665 }