Version 0.1.9 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/channel.h>
15 #include <asterisk/file.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/sched.h>
18 #include <asterisk/module.h>
19 #include <arpa/inet.h>
20 #include <stdlib.h>
21 #include <sys/time.h>
22 #include <stdio.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <pthread.h>
27 #include <endian.h>
28 #include "msgsm.h"
29
30 /* Some Ideas for this code came from makewave.c by Jeffery Chilton */
31
32 /* Portions of the conversion code are by guido@sienanet.it */
33
34 struct ast_filestream {
35         void *reserved[AST_RESERVED_POINTERS];
36         /* Believe it or not, we must decode/recode to account for the
37            weird MS format */
38         /* This is what a filestream means to us */
39         int fd; /* Descriptor */
40         int bytes;
41         struct ast_channel *owner;
42         struct ast_frame fr;                            /* Frame information */
43         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
44         char empty;                                                     /* Empty character */
45         unsigned char gsm[66];                          /* Two Real GSM Frames */
46         int foffset;
47         int secondhalf;                                         /* Are we on the second half */
48         int lasttimeout;
49         struct timeval last;
50         int adj;
51         struct ast_filestream *next;
52 };
53
54
55 static struct ast_filestream *glist = NULL;
56 static pthread_mutex_t wav_lock = PTHREAD_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, int bytes)
205 {
206         int cur;
207         int datalen = htoll(bytes);
208         int filelen = htoll(52 + ((bytes + 1) & ~0x1));
209         cur = lseek(fd, 0, SEEK_CUR);
210         if (cur < 0) {
211                 ast_log(LOG_WARNING, "Unable to find our position\n");
212                 return -1;
213         }
214         if (lseek(fd, 4, SEEK_SET) != 4) {
215                 ast_log(LOG_WARNING, "Unable to set our position\n");
216                 return -1;
217         }
218         if (write(fd, &filelen, 4) != 4) {
219                 ast_log(LOG_WARNING, "Unable to set write file size\n");
220                 return -1;
221         }
222         if (lseek(fd, 56, SEEK_SET) != 56) {
223                 ast_log(LOG_WARNING, "Unable to set our position\n");
224                 return -1;
225         }
226         if (write(fd, &datalen, 4) != 4) {
227                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
228                 return -1;
229         }
230         if (lseek(fd, cur, SEEK_SET) != cur) {
231                 ast_log(LOG_WARNING, "Unable to return to position\n");
232                 return -1;
233         }
234         return 0;
235 }
236
237 static int write_header(int fd)
238 {
239         unsigned int hz=htoll(8000);
240         unsigned int bhz = htoll(1625);
241         unsigned int hs = htoll(20);
242         unsigned short fmt = htols(49);
243         unsigned short chans = htols(1);
244         unsigned int fhs = htoll(4);
245         unsigned int x_1 = htoll(65);
246         unsigned short x_2 = htols(2);
247         unsigned short x_3 = htols(320);
248         unsigned int y_1 = htoll(20160);
249         unsigned int size = htoll(0);
250         /* Write a GSM header, ignoring sizes which will be filled in later */
251         if (write(fd, "RIFF", 4) != 4) {
252                 ast_log(LOG_WARNING, "Unable to write header\n");
253                 return -1;
254         }
255         if (write(fd, &size, 4) != 4) {
256                 ast_log(LOG_WARNING, "Unable to write header\n");
257                 return -1;
258         }
259         if (write(fd, "WAVEfmt ", 8) != 8) {
260                 ast_log(LOG_WARNING, "Unable to write header\n");
261                 return -1;
262         }
263         if (write(fd, &hs, 4) != 4) {
264                 ast_log(LOG_WARNING, "Unable to write header\n");
265                 return -1;
266         }
267         if (write(fd, &fmt, 2) != 2) {
268                 ast_log(LOG_WARNING, "Unable to write header\n");
269                 return -1;
270         }
271         if (write(fd, &chans, 2) != 2) {
272                 ast_log(LOG_WARNING, "Unable to write header\n");
273                 return -1;
274         }
275         if (write(fd, &hz, 4) != 4) {
276                 ast_log(LOG_WARNING, "Unable to write header\n");
277                 return -1;
278         }
279         if (write(fd, &bhz, 4) != 4) {
280                 ast_log(LOG_WARNING, "Unable to write header\n");
281                 return -1;
282         }
283         if (write(fd, &x_1, 4) != 4) {
284                 ast_log(LOG_WARNING, "Unable to write header\n");
285                 return -1;
286         }
287         if (write(fd, &x_2, 2) != 2) {
288                 ast_log(LOG_WARNING, "Unable to write header\n");
289                 return -1;
290         }
291         if (write(fd, &x_3, 2) != 2) {
292                 ast_log(LOG_WARNING, "Unable to write header\n");
293                 return -1;
294         }
295         if (write(fd, "fact", 4) != 4) {
296                 ast_log(LOG_WARNING, "Unable to write header\n");
297                 return -1;
298         }
299         if (write(fd, &fhs, 4) != 4) {
300                 ast_log(LOG_WARNING, "Unable to write header\n");
301                 return -1;
302         }
303         if (write(fd, &y_1, 4) != 4) {
304                 ast_log(LOG_WARNING, "Unable to write header\n");
305                 return -1;
306         }
307         if (write(fd, "data", 4) != 4) {
308                 ast_log(LOG_WARNING, "Unable to write header\n");
309                 return -1;
310         }
311         if (write(fd, &size, 4) != 4) {
312                 ast_log(LOG_WARNING, "Unable to write header\n");
313                 return -1;
314         }
315         return 0;
316 }
317
318 static struct ast_filestream *wav_open(int fd)
319 {
320         /* We don't have any header to read or anything really, but
321            if we did, it would go here.  We also might want to check
322            and be sure it's a valid file.  */
323         struct ast_filestream *tmp;
324         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
325                 memset(tmp, 0, sizeof(struct ast_filestream));
326                 if (check_header(fd)) {
327                         free(tmp);
328                         return NULL;
329                 }
330                 if (ast_pthread_mutex_lock(&wav_lock)) {
331                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
332                         free(tmp);
333                         return NULL;
334                 }
335                 tmp->next = glist;
336                 glist = tmp;
337                 tmp->fd = fd;
338                 tmp->owner = NULL;
339                 tmp->fr.data = tmp->gsm;
340                 tmp->fr.frametype = AST_FRAME_VOICE;
341                 tmp->fr.subclass = AST_FORMAT_GSM;
342                 /* datalen will vary for each frame */
343                 tmp->fr.src = name;
344                 tmp->fr.mallocd = 0;
345                 tmp->secondhalf = 0;
346                 tmp->lasttimeout = -1;
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->next = glist;
372                 glist = tmp;
373                 tmp->fd = fd;
374                 tmp->owner = NULL;
375                 tmp->lasttimeout = -1;
376                 glistcnt++;
377                 ast_pthread_mutex_unlock(&wav_lock);
378                 ast_update_use_count();
379         } else
380                 ast_log(LOG_WARNING, "Out of memory\n");
381         return tmp;
382 }
383
384 static struct ast_frame *wav_read(struct ast_filestream *s)
385 {
386         return NULL;
387 }
388
389 static void wav_close(struct ast_filestream *s)
390 {
391         struct ast_filestream *tmp, *tmpl = NULL;
392         char zero = 0;
393         if (ast_pthread_mutex_lock(&wav_lock)) {
394                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
395                 return;
396         }
397         tmp = glist;
398         while(tmp) {
399                 if (tmp == s) {
400                         if (tmpl)
401                                 tmpl->next = tmp->next;
402                         else
403                                 glist = tmp->next;
404                         break;
405                 }
406                 tmpl = tmp;
407                 tmp = tmp->next;
408         }
409         glistcnt--;
410         if (s->owner) {
411                 s->owner->stream = NULL;
412                 if (s->owner->streamid > -1)
413                         ast_sched_del(s->owner->sched, s->owner->streamid);
414                 s->owner->streamid = -1;
415         }
416         ast_pthread_mutex_unlock(&wav_lock);
417         ast_update_use_count();
418         if (!tmp) 
419                 ast_log(LOG_WARNING, "Freeing a filestream we don't seem to own\n");
420         /* Pad to even length */
421         if (s->bytes & 0x1)
422                 write(s->fd, &zero, 1);
423         close(s->fd);
424         free(s);
425 }
426
427 static int ast_read_callback(void *data)
428 {
429         int retval = 0;
430         int res;
431         int delay = 20;
432         struct ast_filestream *s = data;
433         char msdata[66];
434         struct timeval tv;
435         /* Send a frame from the file to the appropriate channel */
436
437         s->fr.frametype = AST_FRAME_VOICE;
438         s->fr.subclass = AST_FORMAT_GSM;
439         s->fr.offset = AST_FRIENDLY_OFFSET;
440         s->fr.timelen = 20;
441         s->fr.datalen = 33;
442         s->fr.mallocd = 0;
443         if (s->secondhalf) {
444                 /* Just return a frame based on the second GSM frame */
445                 s->fr.data = s->gsm + 33;
446         } else {
447                 if ((res = read(s->fd, msdata, 65)) != 65) {
448                         if (res && (res != 1))
449                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
450                         s->owner->streamid = -1;
451                         return 0;
452                 }
453                 /* Convert from MS format to two real GSM frames */
454                 conv65(msdata, s->gsm);
455                 s->fr.data = s->gsm;
456         }
457         s->secondhalf = !s->secondhalf;
458         /* Lastly, process the frame */
459         if (ast_write(s->owner, &s->fr)) {
460                 ast_log(LOG_WARNING, "Failed to write frame\n");
461                 s->owner->streamid = -1;
462                 return 0;
463         }
464         if (s->last.tv_usec || s->last.tv_usec) {
465                 int ms;
466                 gettimeofday(&tv, NULL);
467                 ms = 1000 * (tv.tv_sec - s->last.tv_sec) + 
468                         (tv.tv_usec - s->last.tv_usec) / 1000;
469                 s->last.tv_sec = tv.tv_sec;
470                 s->last.tv_usec = tv.tv_usec;
471                 if ((ms - delay) * (ms - delay) > 4) {
472                         /* Compensate if we're more than 2 ms off */
473                         s->adj -= (ms - delay);
474                 }
475 #if 0
476                 fprintf(stdout, "Delay is %d, adjustment is %d, last was %d\n", delay, s->adj, ms);
477 #endif
478                 delay += s->adj;
479                 if (delay < 1)
480                         delay = 1;
481         } else
482                 gettimeofday(&s->last, NULL);
483         if (s->lasttimeout != delay) {
484                 /* We'll install the next timeout now. */
485                 s->owner->streamid = ast_sched_add(s->owner->sched,
486                                 delay, ast_read_callback, s); 
487                 s->lasttimeout = delay;
488         } else {
489                 /* Just come back again at the same time */
490                 retval = -1;
491         }
492         return retval;
493 }
494
495 static int wav_apply(struct ast_channel *c, struct ast_filestream *s)
496 {
497         /* Select our owner for this stream, and get the ball rolling. */
498         s->owner = c;
499         ast_read_callback(s);
500         return 0;
501 }
502
503 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
504 {
505         int res;
506         char msdata[66];
507         int len =0;
508         if (f->frametype != AST_FRAME_VOICE) {
509                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
510                 return -1;
511         }
512         if (f->subclass != AST_FORMAT_GSM) {
513                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
514                 return -1;
515         }
516         while(len < f->datalen) {
517                 if (fs->secondhalf) {
518                         memcpy(fs->gsm + 33, f->data + len, 33);
519                         conv66(fs->gsm, msdata);
520                         if ((res = write(fs->fd, msdata, 65)) != 65) {
521                                 ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
522                                 return -1;
523                         }
524                         fs->bytes += 65;
525                         update_header(fs->fd, fs->bytes);
526                 } else {
527                         /* Copy the data and do nothing */
528                         memcpy(fs->gsm, f->data + len, 33);
529                 }
530                 fs->secondhalf = !fs->secondhalf;
531                 len += 33;
532         }
533         return 0;
534 }
535
536 static char *wav_getcomment(struct ast_filestream *s)
537 {
538         return NULL;
539 }
540
541 int load_module()
542 {
543         return ast_format_register(name, exts, AST_FORMAT_GSM,
544                                                                 wav_open,
545                                                                 wav_rewrite,
546                                                                 wav_apply,
547                                                                 wav_write,
548                                                                 wav_read,
549                                                                 wav_close,
550                                                                 wav_getcomment);
551                                                                 
552                                                                 
553 }
554
555 int unload_module()
556 {
557         struct ast_filestream *tmp, *tmpl;
558         if (ast_pthread_mutex_lock(&wav_lock)) {
559                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
560                 return -1;
561         }
562         tmp = glist;
563         while(tmp) {
564                 if (tmp->owner)
565                         ast_softhangup(tmp->owner);
566                 tmpl = tmp;
567                 tmp = tmp->next;
568                 free(tmpl);
569         }
570         ast_pthread_mutex_unlock(&wav_lock);
571         return ast_format_unregister(name);
572 }       
573
574 int usecount()
575 {
576         int res;
577         if (ast_pthread_mutex_lock(&wav_lock)) {
578                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
579                 return -1;
580         }
581         res = glistcnt;
582         ast_pthread_mutex_unlock(&wav_lock);
583         return res;
584 }
585
586 char *description()
587 {
588         return desc;
589 }
590
591
592 char *key()
593 {
594         return ASTERISK_GPL_KEY;
595 }