Version 0.1.12 from FTP
[asterisk/asterisk.git] / formats / format_vox.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Flat, binary, ADPCM vox file 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
30 #define BUF_SIZE 80             /* 160 samples */
31
32 struct ast_filestream {
33         void *reserved[AST_RESERVED_POINTERS];
34         /* Believe it or not, we must decode/recode to account for the
35            weird MS format */
36         /* This is what a filestream means to us */
37         int fd; /* Descriptor */
38         struct ast_channel *owner;
39         struct ast_frame fr;                            /* Frame information */
40         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
41         char empty;                                                     /* Empty character */
42         unsigned char buf[BUF_SIZE + 3];                                /* Output Buffer */
43         int lasttimeout;
44         struct timeval last;
45         int adj;
46         short signal;                                           /* Signal level (file side) */
47         short ssindex;                                          /* Signal ssindex (file side) */
48         struct ast_filestream *next;
49 };
50
51
52 static struct ast_filestream *glist = NULL;
53 static pthread_mutex_t vox_lock = AST_MUTEX_INITIALIZER;
54 static int glistcnt = 0;
55
56 static char *name = "vox";
57 static char *desc = "Dialogic VOX (ADPCM) File Format";
58 static char *exts = "vox";
59
60 /*
61  * Step size index shift table 
62  */
63
64 static short indsft[8] = { -1, -1, -1, -1, 2, 4, 6, 8 };
65
66 /*
67  * Step size table, where stpsz[i]=floor[16*(11/10)^i]
68  */
69
70 static short stpsz[49] = {
71   16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73,
72   80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279,
73   307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963,
74   1060, 1166, 1282, 1411, 1552
75 };
76
77 /* 
78  * Nibble to bit map
79  */
80
81 static short nbl2bit[16][4] = {
82   {1, 0, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 0, 1, 1},
83   {1, 1, 0, 0}, {1, 1, 0, 1}, {1, 1, 1, 0}, {1, 1, 1, 1},
84   {-1, 0, 0, 0}, {-1, 0, 0, 1}, {-1, 0, 1, 0}, {-1, 0, 1, 1},
85   {-1, 1, 0, 0}, {-1, 1, 0, 1}, {-1, 1, 1, 0}, {-1, 1, 1, 1}
86 };
87
88 /*
89  * Decode(encoded)
90  *  Decodes the encoded nibble from the adpcm file.
91  *
92  * Results:
93  *  Returns the encoded difference.
94  *
95  * Side effects:
96  *  Sets the index to the step size table for the next encode.
97  */
98
99 static inline short
100 decode (unsigned char encoded, short *ssindex)
101 {
102   short diff, step;
103   step = stpsz[*ssindex];
104   diff = nbl2bit[encoded][0] * (step * nbl2bit[encoded][1] +
105                                 (step >> 1) * nbl2bit[encoded][2] +
106                                 (step >> 2) * nbl2bit[encoded][3] +
107                                 (step >> 3));
108   *ssindex = *ssindex + indsft[(encoded & 7)];
109   if (*ssindex < 0)
110     *ssindex = 0;
111   else if (*ssindex > 48)
112     *ssindex = 48;
113   return (diff);
114 }
115
116 /*
117  * Adpcm
118  *  Takes a signed linear signal and encodes it as ADPCM
119  *  For more information see http://support.dialogic.com/appnotes/adpcm.pdf
120  *
121  * Results:
122  *  Foo.
123  *
124  * Side effects:
125  *  signal gets updated with each pass.
126  */
127
128 static inline unsigned char
129 adpcm (short csig, short *ssindex, short *signal)
130 {
131   short diff, step;
132   unsigned char encoded;
133   step = stpsz[*ssindex];
134   /* 
135    * Clip csig if too large or too small
136    */
137    
138   csig >>= 4;
139
140   diff = csig - *signal;
141   
142   if (diff < 0)
143     {
144       encoded = 8;
145       diff = -diff;
146     }
147   else
148     encoded = 0;
149   if (diff >= step)
150     {
151       encoded |= 4;
152       diff -= step;
153     }
154   step >>= 1;
155   if (diff >= step)
156     {
157       encoded |= 2;
158       diff -= step;
159     }
160   step >>= 1;
161   if (diff >= step)
162     encoded |= 1;
163     
164   *signal += decode (encoded, ssindex);
165   return (encoded);
166 }
167
168 static struct ast_filestream *vox_open(int fd)
169 {
170         /* We don't have any header to read or anything really, but
171            if we did, it would go here.  We also might want to check
172            and be sure it's a valid file.  */
173         struct ast_filestream *tmp;
174         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
175                 memset(tmp, 0, sizeof(struct ast_filestream));
176                 if (ast_pthread_mutex_lock(&vox_lock)) {
177                         ast_log(LOG_WARNING, "Unable to lock vox list\n");
178                         free(tmp);
179                         return NULL;
180                 }
181                 tmp->next = glist;
182                 glist = tmp;
183                 tmp->fd = fd;
184                 tmp->owner = NULL;
185                 tmp->fr.data = tmp->buf;
186                 tmp->fr.frametype = AST_FRAME_VOICE;
187                 tmp->fr.subclass = AST_FORMAT_ADPCM;
188                 /* datalen will vary for each frame */
189                 tmp->fr.src = name;
190                 tmp->fr.mallocd = 0;
191                 tmp->lasttimeout = -1;
192                 glistcnt++;
193                 ast_pthread_mutex_unlock(&vox_lock);
194                 ast_update_use_count();
195         }
196         return tmp;
197 }
198
199 static struct ast_filestream *vox_rewrite(int fd, char *comment)
200 {
201         /* We don't have any header to read or anything really, but
202            if we did, it would go here.  We also might want to check
203            and be sure it's a valid file.  */
204         struct ast_filestream *tmp;
205         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
206                 memset(tmp, 0, sizeof(struct ast_filestream));
207                 if (ast_pthread_mutex_lock(&vox_lock)) {
208                         ast_log(LOG_WARNING, "Unable to lock vox list\n");
209                         free(tmp);
210                         return NULL;
211                 }
212                 tmp->next = glist;
213                 glist = tmp;
214                 tmp->fd = fd;
215                 tmp->owner = NULL;
216                 tmp->lasttimeout = -1;
217                 glistcnt++;
218                 ast_pthread_mutex_unlock(&vox_lock);
219                 ast_update_use_count();
220         } else
221                 ast_log(LOG_WARNING, "Out of memory\n");
222         return tmp;
223 }
224
225 static struct ast_frame *vox_read(struct ast_filestream *s)
226 {
227         return NULL;
228 }
229
230 static void vox_close(struct ast_filestream *s)
231 {
232         struct ast_filestream *tmp, *tmpl = NULL;
233         if (ast_pthread_mutex_lock(&vox_lock)) {
234                 ast_log(LOG_WARNING, "Unable to lock vox list\n");
235                 return;
236         }
237         tmp = glist;
238         while(tmp) {
239                 if (tmp == s) {
240                         if (tmpl)
241                                 tmpl->next = tmp->next;
242                         else
243                                 glist = tmp->next;
244                         break;
245                 }
246                 tmpl = tmp;
247                 tmp = tmp->next;
248         }
249         glistcnt--;
250         if (s->owner) {
251                 s->owner->stream = NULL;
252                 if (s->owner->streamid > -1)
253                         ast_sched_del(s->owner->sched, s->owner->streamid);
254                 s->owner->streamid = -1;
255         }
256         ast_pthread_mutex_unlock(&vox_lock);
257         ast_update_use_count();
258         if (!tmp) 
259                 ast_log(LOG_WARNING, "Freeing a filestream we don't seem to own\n");
260         close(s->fd);
261         free(s);
262 }
263
264 static int ast_read_callback(void *data)
265 {
266         int retval = 0;
267         int res;
268         int delay;
269         struct ast_filestream *s = data;
270         struct timeval tv;
271         int x;
272         /* Send a frame from the file to the appropriate channel */
273
274         s->fr.frametype = AST_FRAME_VOICE;
275         s->fr.subclass = AST_FORMAT_ADPCM;
276         s->fr.offset = AST_FRIENDLY_OFFSET;
277         s->fr.mallocd = 0;
278         s->fr.data = s->buf;
279         if ((res = read(s->fd, s->buf + 3, BUF_SIZE)) < 1) {
280                 if (res)
281                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
282                 s->owner->streamid = -1;
283                 return 0;
284         }
285         /* Store index, then signal */
286         s->buf[0] = s->ssindex & 0xff;
287         s->buf[1] = (s->signal >> 8) & 0xff;
288         s->buf[2] = s->signal & 0xff;
289         /* Do the decoder to be sure we get the right stuff in the signal and index fields. */
290         for (x=3;x<res+3;x++) {
291                 s->signal += decode(s->buf[x] >> 4, &s->ssindex);
292                 s->signal += decode(s->buf[x] & 0xf, &s->ssindex);
293         }
294         s->fr.timelen = res / 4;
295         s->fr.datalen = res + 3;
296         delay = s->fr.timelen;
297         /* Lastly, process the frame */
298         if (ast_write(s->owner, &s->fr)) {
299                 ast_log(LOG_WARNING, "Failed to write frame\n");
300                 s->owner->streamid = -1;
301                 return 0;
302         }
303         if (s->last.tv_usec || s->last.tv_usec) {
304                 int ms;
305                 gettimeofday(&tv, NULL);
306                 ms = 1000 * (tv.tv_sec - s->last.tv_sec) + 
307                         (tv.tv_usec - s->last.tv_usec) / 1000;
308                 s->last.tv_sec = tv.tv_sec;
309                 s->last.tv_usec = tv.tv_usec;
310                 if ((ms - delay) * (ms - delay) > 4) {
311                         /* Compensate if we're more than 2 ms off */
312                         s->adj -= (ms - delay);
313                 }
314 #if 0
315                 fprintf(stdout, "Delay is %d, adjustment is %d, last was %d\n", delay, s->adj, ms);
316 #endif
317                 delay += s->adj;
318                 if (delay < 1)
319                         delay = 1;
320         } else
321                 gettimeofday(&s->last, NULL);
322         if (s->lasttimeout != delay) {
323                 /* We'll install the next timeout now. */
324                 s->owner->streamid = ast_sched_add(s->owner->sched,
325                                 delay, ast_read_callback, s); 
326                 s->lasttimeout = delay;
327         } else {
328                 /* Just come back again at the same time */
329                 retval = -1;
330         }
331         return retval;
332 }
333
334 static int vox_apply(struct ast_channel *c, struct ast_filestream *s)
335 {
336         /* Select our owner for this stream, and get the ball rolling. */
337         s->owner = c;
338         ast_read_callback(s);
339         return 0;
340 }
341
342 static int vox_write(struct ast_filestream *fs, struct ast_frame *f)
343 {
344         int res;
345         if (f->frametype != AST_FRAME_VOICE) {
346                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
347                 return -1;
348         }
349         if (f->subclass != AST_FORMAT_ADPCM) {
350                 ast_log(LOG_WARNING, "Asked to write non-ADPCM frame (%d)!\n", f->subclass);
351                 return -1;
352         }
353         if (f->datalen < 3) {
354                 ast_log(LOG_WARNING, "Invalid frame of data (< 3 bytes long) from %s\n", f->src);
355                 return -1;
356         }
357         if ((res = write(fs->fd, f->data + 3, f->datalen)) != f->datalen) {
358                         ast_log(LOG_WARNING, "Bad write (%d/%d): %s\n", res, f->datalen, strerror(errno));
359                         return -1;
360         }
361         return 0;
362 }
363
364 static char *vox_getcomment(struct ast_filestream *s)
365 {
366         return NULL;
367 }
368
369 int load_module()
370 {
371         return ast_format_register(name, exts, AST_FORMAT_ADPCM,
372                                                                 vox_open,
373                                                                 vox_rewrite,
374                                                                 vox_apply,
375                                                                 vox_write,
376                                                                 vox_read,
377                                                                 vox_close,
378                                                                 vox_getcomment);
379                                                                 
380                                                                 
381 }
382
383 int unload_module()
384 {
385         struct ast_filestream *tmp, *tmpl;
386         if (ast_pthread_mutex_lock(&vox_lock)) {
387                 ast_log(LOG_WARNING, "Unable to lock vox list\n");
388                 return -1;
389         }
390         tmp = glist;
391         while(tmp) {
392                 if (tmp->owner)
393                         ast_softhangup(tmp->owner);
394                 tmpl = tmp;
395                 tmp = tmp->next;
396                 free(tmpl);
397         }
398         ast_pthread_mutex_unlock(&vox_lock);
399         return ast_format_unregister(name);
400 }       
401
402 int usecount()
403 {
404         int res;
405         if (ast_pthread_mutex_lock(&vox_lock)) {
406                 ast_log(LOG_WARNING, "Unable to lock vox list\n");
407                 return -1;
408         }
409         res = glistcnt;
410         ast_pthread_mutex_unlock(&vox_lock);
411         return res;
412 }
413
414 char *description()
415 {
416         return desc;
417 }
418
419
420 char *key()
421 {
422         return ASTERISK_GPL_KEY;
423 }