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