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