BSD portability enhancements (bug #234)
[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 <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <stdlib.h>
23 #include <sys/time.h>
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <pthread.h>
29 #ifdef __linux__
30 #include <endian.h>
31 #else
32 #include <machine/endian.h>
33 #endif
34 #include "msgsm.h"
35
36 /* Some Ideas for this code came from makewave.c by Jeffery Chilton */
37
38 /* Portions of the conversion code are by guido@sienanet.it */
39
40 struct ast_filestream {
41         void *reserved[AST_RESERVED_POINTERS];
42         /* Believe it or not, we must decode/recode to account for the
43            weird MS format */
44         /* This is what a filestream means to us */
45         int fd; /* Descriptor */
46         int bytes;
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         struct timeval last;
54 };
55
56
57 static ast_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)
206 {
207         off_t cur,end,bytes;
208         int datalen,filelen;
209         
210         cur = lseek(fd, 0, SEEK_CUR);
211         end = lseek(fd, 0, SEEK_END);
212         bytes = end - 52;
213         datalen = htoll(bytes);
214         filelen = htoll(52 + ((bytes + 1) & ~0x1));
215         if (cur < 0) {
216                 ast_log(LOG_WARNING, "Unable to find our position\n");
217                 return -1;
218         }
219         if (lseek(fd, 4, SEEK_SET) != 4) {
220                 ast_log(LOG_WARNING, "Unable to set our position\n");
221                 return -1;
222         }
223         if (write(fd, &filelen, 4) != 4) {
224                 ast_log(LOG_WARNING, "Unable to set write file size\n");
225                 return -1;
226         }
227         if (lseek(fd, 56, SEEK_SET) != 56) {
228                 ast_log(LOG_WARNING, "Unable to set our position\n");
229                 return -1;
230         }
231         if (write(fd, &datalen, 4) != 4) {
232                 ast_log(LOG_WARNING, "Unable to set write datalen\n");
233                 return -1;
234         }
235         if (lseek(fd, cur, SEEK_SET) != cur) {
236                 ast_log(LOG_WARNING, "Unable to return to position\n");
237                 return -1;
238         }
239         return 0;
240 }
241
242 static int write_header(int fd)
243 {
244         unsigned int hz=htoll(8000);
245         unsigned int bhz = htoll(1625);
246         unsigned int hs = htoll(20);
247         unsigned short fmt = htols(49);
248         unsigned short chans = htols(1);
249         unsigned int fhs = htoll(4);
250         unsigned int x_1 = htoll(65);
251         unsigned short x_2 = htols(2);
252         unsigned short x_3 = htols(320);
253         unsigned int y_1 = htoll(20160);
254         unsigned int size = htoll(0);
255         /* Write a GSM header, ignoring sizes which will be filled in later */
256         if (write(fd, "RIFF", 4) != 4) {
257                 ast_log(LOG_WARNING, "Unable to write header\n");
258                 return -1;
259         }
260         if (write(fd, &size, 4) != 4) {
261                 ast_log(LOG_WARNING, "Unable to write header\n");
262                 return -1;
263         }
264         if (write(fd, "WAVEfmt ", 8) != 8) {
265                 ast_log(LOG_WARNING, "Unable to write header\n");
266                 return -1;
267         }
268         if (write(fd, &hs, 4) != 4) {
269                 ast_log(LOG_WARNING, "Unable to write header\n");
270                 return -1;
271         }
272         if (write(fd, &fmt, 2) != 2) {
273                 ast_log(LOG_WARNING, "Unable to write header\n");
274                 return -1;
275         }
276         if (write(fd, &chans, 2) != 2) {
277                 ast_log(LOG_WARNING, "Unable to write header\n");
278                 return -1;
279         }
280         if (write(fd, &hz, 4) != 4) {
281                 ast_log(LOG_WARNING, "Unable to write header\n");
282                 return -1;
283         }
284         if (write(fd, &bhz, 4) != 4) {
285                 ast_log(LOG_WARNING, "Unable to write header\n");
286                 return -1;
287         }
288         if (write(fd, &x_1, 4) != 4) {
289                 ast_log(LOG_WARNING, "Unable to write header\n");
290                 return -1;
291         }
292         if (write(fd, &x_2, 2) != 2) {
293                 ast_log(LOG_WARNING, "Unable to write header\n");
294                 return -1;
295         }
296         if (write(fd, &x_3, 2) != 2) {
297                 ast_log(LOG_WARNING, "Unable to write header\n");
298                 return -1;
299         }
300         if (write(fd, "fact", 4) != 4) {
301                 ast_log(LOG_WARNING, "Unable to write header\n");
302                 return -1;
303         }
304         if (write(fd, &fhs, 4) != 4) {
305                 ast_log(LOG_WARNING, "Unable to write header\n");
306                 return -1;
307         }
308         if (write(fd, &y_1, 4) != 4) {
309                 ast_log(LOG_WARNING, "Unable to write header\n");
310                 return -1;
311         }
312         if (write(fd, "data", 4) != 4) {
313                 ast_log(LOG_WARNING, "Unable to write header\n");
314                 return -1;
315         }
316         if (write(fd, &size, 4) != 4) {
317                 ast_log(LOG_WARNING, "Unable to write header\n");
318                 return -1;
319         }
320         return 0;
321 }
322
323 static struct ast_filestream *wav_open(int fd)
324 {
325         /* We don't have any header to read or anything really, but
326            if we did, it would go here.  We also might want to check
327            and be sure it's a valid file.  */
328         struct ast_filestream *tmp;
329         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
330                 memset(tmp, 0, sizeof(struct ast_filestream));
331                 if (check_header(fd)) {
332                         free(tmp);
333                         return NULL;
334                 }
335                 if (ast_mutex_lock(&wav_lock)) {
336                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
337                         free(tmp);
338                         return NULL;
339                 }
340                 tmp->fd = fd;
341                 tmp->fr.data = tmp->gsm;
342                 tmp->fr.frametype = AST_FRAME_VOICE;
343                 tmp->fr.subclass = AST_FORMAT_GSM;
344                 /* datalen will vary for each frame */
345                 tmp->fr.src = name;
346                 tmp->fr.mallocd = 0;
347                 tmp->secondhalf = 0;
348                 glistcnt++;
349                 ast_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_mutex_lock(&wav_lock)) {
368                         ast_log(LOG_WARNING, "Unable to lock wav list\n");
369                         free(tmp);
370                         return NULL;
371                 }
372                 tmp->fd = fd;
373                 glistcnt++;
374                 ast_mutex_unlock(&wav_lock);
375                 ast_update_use_count();
376         } else
377                 ast_log(LOG_WARNING, "Out of memory\n");
378         return tmp;
379 }
380
381 static void wav_close(struct ast_filestream *s)
382 {
383         char zero = 0;
384         ast_mutex_unlock(&wav_lock);
385         ast_update_use_count();
386         /* Pad to even length */
387         if (s->bytes & 0x1)
388                 write(s->fd, &zero, 1);
389         close(s->fd);
390         free(s);
391         s = NULL;
392 }
393
394 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
395 {
396         int res;
397         char msdata[66];
398         /* Send a frame from the file to the appropriate channel */
399
400         s->fr.frametype = AST_FRAME_VOICE;
401         s->fr.subclass = AST_FORMAT_GSM;
402         s->fr.offset = AST_FRIENDLY_OFFSET;
403         s->fr.samples = 160;
404         s->fr.datalen = 33;
405         s->fr.mallocd = 0;
406         if (s->secondhalf) {
407                 /* Just return a frame based on the second GSM frame */
408                 s->fr.data = s->gsm + 33;
409         } else {
410                 if ((res = read(s->fd, msdata, 65)) != 65) {
411                         if (res && (res != 1))
412                                 ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
413                         return NULL;
414                 }
415                 /* Convert from MS format to two real GSM frames */
416                 conv65(msdata, s->gsm);
417                 s->fr.data = s->gsm;
418         }
419         s->secondhalf = !s->secondhalf;
420         *whennext = 160;
421         return &s->fr;
422 }
423
424 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
425 {
426         int res;
427         char msdata[66];
428         int len =0;
429         int alreadyms=0;
430         if (f->frametype != AST_FRAME_VOICE) {
431                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
432                 return -1;
433         }
434         if (f->subclass != AST_FORMAT_GSM) {
435                 ast_log(LOG_WARNING, "Asked to write non-GSM frame (%d)!\n", f->subclass);
436                 return -1;
437         }
438         if (!(f->datalen % 65)) 
439                 alreadyms = 1;
440         while(len < f->datalen) {
441                 if (alreadyms) {
442                         fs->secondhalf = 0;
443                         if ((res = write(fs->fd, f->data + len, 65)) != 65) {
444                                 ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
445                                 return -1;
446                         }
447                         fs->bytes += 65;
448                         update_header(fs->fd);
449                         len += 65;
450                 } else {
451                         if (fs->secondhalf) {
452                                 memcpy(fs->gsm + 33, f->data + len, 33);
453                                 conv66(fs->gsm, msdata);
454                                 if ((res = write(fs->fd, msdata, 65)) != 65) {
455                                         ast_log(LOG_WARNING, "Bad write (%d/65): %s\n", res, strerror(errno));
456                                         return -1;
457                                 }
458                                 fs->bytes += 65;
459                                 update_header(fs->fd);
460                         } else {
461                                 /* Copy the data and do nothing */
462                                 memcpy(fs->gsm, f->data + len, 33);
463                         }
464                         fs->secondhalf = !fs->secondhalf;
465                         len += 33;
466                 }
467         }
468         return 0;
469 }
470
471 static int wav_seek(struct ast_filestream *fs, long sample_offset, int whence)
472 {
473         off_t offset=0,distance,cur,min,max;
474         min = 52;
475         cur = lseek(fs->fd, 0, SEEK_CUR);
476         max = lseek(fs->fd, 0, SEEK_END);
477         /* I'm getting sloppy here, I'm only going to go to even splits of the 2
478          * frames, if you want tighter cuts use format_gsm, format_pcm, or format_wav */
479         distance = (sample_offset/320) * 65;
480         if(whence == SEEK_SET)
481                 offset = distance + min;
482         else if(whence == SEEK_CUR || whence == SEEK_FORCECUR)
483                 offset = distance + cur;
484         else if(whence == SEEK_END)
485                 offset = max - distance;
486         if (whence != SEEK_FORCECUR) {
487                 offset = (offset < min)?min:offset;
488                 offset = (offset > max)?max:offset;
489         }
490         fs->secondhalf = 0;
491         return lseek(fs->fd, offset, SEEK_SET);
492 }
493
494 static int wav_trunc(struct ast_filestream *fs)
495 {
496         if(ftruncate(fs->fd, lseek(fs->fd, 0, SEEK_CUR)))
497                 return -1;
498         return update_header(fs->fd);
499 }
500
501 static long wav_tell(struct ast_filestream *fs)
502 {
503         off_t offset;
504         offset = lseek(fs->fd, 0, SEEK_CUR);
505         /* since this will most likely be used later in play or record, lets stick
506          * to that level of resolution, just even frames boundaries */
507         return (offset - 52)/65/320;
508 }
509
510 static char *wav_getcomment(struct ast_filestream *s)
511 {
512         return NULL;
513 }
514
515 int load_module()
516 {
517         return ast_format_register(name, exts, AST_FORMAT_GSM,
518                                                                 wav_open,
519                                                                 wav_rewrite,
520                                                                 wav_write,
521                                                                 wav_seek,
522                                                                 wav_trunc,
523                                                                 wav_tell,
524                                                                 wav_read,
525                                                                 wav_close,
526                                                                 wav_getcomment);
527                                                                 
528                                                                 
529 }
530
531 int unload_module()
532 {
533         return ast_format_unregister(name);
534 }       
535
536 int usecount()
537 {
538         int res;
539         if (ast_mutex_lock(&wav_lock)) {
540                 ast_log(LOG_WARNING, "Unable to lock wav list\n");
541                 return -1;
542         }
543         res = glistcnt;
544         ast_mutex_unlock(&wav_lock);
545         return res;
546 }
547
548 char *description()
549 {
550         return desc;
551 }
552
553
554 char *key()
555 {
556         return ASTERISK_GPL_KEY;
557 }