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