Add Mahmut's Alaw patch
[asterisk/asterisk.git] / formats / format_pcm_alaw.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Flat, binary, alaw PCM 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 <sys/times.h>
24 #include <sys/types.h>
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <pthread.h>
30 #include <endian.h>
31
32 #define BUF_SIZE 160            /* 160 samples */
33
34 // #define REALTIME_WRITE
35
36 struct ast_filestream {
37         void *reserved[AST_RESERVED_POINTERS];
38         /* Believe it or not, we must decode/recode to account for the
39            weird MS format */
40         /* This is what a filestream means to us */
41         int fd; /* Descriptor */
42         struct ast_channel *owner;
43         struct ast_frame fr;                            /* Frame information */
44         char waste[AST_FRIENDLY_OFFSET];        /* Buffer for sending frames, etc */
45         char empty;                                                     /* Empty character */
46         unsigned char buf[BUF_SIZE];                            /* Output Buffer */
47         int lasttimeout;
48         struct timeval last;
49 #ifdef REALTIME_WRITE
50         unsigned long start_time;
51 #endif
52         int adj;
53         struct ast_filestream *next;
54 };
55
56
57 static struct ast_filestream *glist = NULL;
58 static pthread_mutex_t pcm_lock = AST_MUTEX_INITIALIZER;
59 static int glistcnt = 0;
60
61 static char *name = "alaw";
62 static char *desc = "Raw aLaw 8khz PCM Audio support";
63 static char *exts = "alaw|al";
64
65
66 /* Returns time in msec since system boot. */
67 static unsigned long get_time()
68 {
69         struct tms buf;
70         clock_t cur;
71
72         cur = times( &buf );
73         if( cur < 0 )
74         {
75                 ast_log( LOG_WARNING, "Cannot get current time\n" );
76                 return 0;
77         }
78         return cur * 1000 / sysconf( _SC_CLK_TCK );
79 }
80
81 static struct ast_filestream *pcm_open(int fd)
82 {
83         /* We don't have any header to read or anything really, but
84            if we did, it would go here.  We also might want to check
85            and be sure it's a valid file.  */
86         struct ast_filestream *tmp;
87         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
88                 memset(tmp, 0, sizeof(struct ast_filestream));
89                 if (pthread_mutex_lock(&pcm_lock)) {
90                         ast_log(LOG_WARNING, "Unable to lock pcm list\n");
91                         free(tmp);
92                         return NULL;
93                 }
94                 tmp->next = glist;
95                 glist = tmp;
96                 tmp->fd = fd;
97                 tmp->owner = NULL;
98                 tmp->fr.data = tmp->buf;
99                 tmp->fr.frametype = AST_FRAME_VOICE;
100                 tmp->fr.subclass = AST_FORMAT_ALAW;
101                 /* datalen will vary for each frame */
102                 tmp->fr.src = name;
103                 tmp->fr.mallocd = 0;
104                 tmp->lasttimeout = -1;
105 #ifdef REALTIME_WRITE
106                 tmp->start_time = get_time();
107 #endif
108                 glistcnt++;
109                 pthread_mutex_unlock(&pcm_lock);
110                 ast_update_use_count();
111         }
112         return tmp;
113 }
114
115 static struct ast_filestream *pcm_rewrite(int fd, char *comment)
116 {
117         /* We don't have any header to read or anything really, but
118            if we did, it would go here.  We also might want to check
119            and be sure it's a valid file.  */
120         struct ast_filestream *tmp;
121         if ((tmp = malloc(sizeof(struct ast_filestream)))) {
122                 memset(tmp, 0, sizeof(struct ast_filestream));
123                 if (pthread_mutex_lock(&pcm_lock)) {
124                         ast_log(LOG_WARNING, "Unable to lock pcm list\n");
125                         free(tmp);
126                         return NULL;
127                 }
128                 tmp->next = glist;
129                 glist = tmp;
130                 tmp->fd = fd;
131                 tmp->owner = NULL;
132                 tmp->lasttimeout = -1;
133 #ifdef REALTIME_WRITE
134                 tmp->start_time = get_time();
135 #endif
136                 glistcnt++;
137                 pthread_mutex_unlock(&pcm_lock);
138                 ast_update_use_count();
139         } else
140                 ast_log(LOG_WARNING, "Out of memory\n");
141         return tmp;
142 }
143
144 static struct ast_frame *pcm_read(struct ast_filestream *s)
145 {
146         return NULL;
147 }
148
149 static void pcm_close(struct ast_filestream *s)
150 {
151         struct ast_filestream *tmp, *tmpl = NULL;
152         if (pthread_mutex_lock(&pcm_lock)) {
153                 ast_log(LOG_WARNING, "Unable to lock pcm list\n");
154                 return;
155         }
156         tmp = glist;
157         while(tmp) {
158                 if (tmp == s) {
159                         if (tmpl)
160                                 tmpl->next = tmp->next;
161                         else
162                                 glist = tmp->next;
163                         break;
164                 }
165                 tmpl = tmp;
166                 tmp = tmp->next;
167         }
168         glistcnt--;
169         if (s->owner) {
170                 s->owner->stream = NULL;
171                 if (s->owner->streamid > -1)
172                         ast_sched_del(s->owner->sched, s->owner->streamid);
173                 s->owner->streamid = -1;
174         }
175         pthread_mutex_unlock(&pcm_lock);
176         ast_update_use_count();
177         if (!tmp) 
178                 ast_log(LOG_WARNING, "Freeing a filestream we don't seem to own\n");
179         close(s->fd);
180         free(s);
181         s = NULL;
182 }
183
184 static int ast_read_callback(void *data)
185 {
186         int retval = 0;
187         int res;
188         int delay;
189         struct ast_filestream *s = data;
190         struct timeval tv;
191         /* Send a frame from the file to the appropriate channel */
192
193         s->fr.frametype = AST_FRAME_VOICE;
194         s->fr.subclass = AST_FORMAT_ALAW;
195         s->fr.offset = AST_FRIENDLY_OFFSET;
196         s->fr.mallocd = 0;
197         s->fr.data = s->buf;
198         if ((res = read(s->fd, s->buf, BUF_SIZE)) < 1) {
199                 if (res)
200                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
201                 s->owner->streamid = -1;
202                 return 0;
203         }
204         s->fr.samples = res;
205         s->fr.datalen = res;
206         delay = s->fr.samples/8;
207         /* Lastly, process the frame */
208         if (ast_write(s->owner, &s->fr)) {
209                 ast_log(LOG_WARNING, "Failed to write frame\n");
210                 s->owner->streamid = -1;
211                 return 0;
212         }
213         if (s->last.tv_usec || s->last.tv_usec) {
214                 int ms;
215                 gettimeofday(&tv, NULL);
216                 ms = 1000 * (tv.tv_sec - s->last.tv_sec) + 
217                         (tv.tv_usec - s->last.tv_usec) / 1000;
218                 s->last.tv_sec = tv.tv_sec;
219                 s->last.tv_usec = tv.tv_usec;
220                 if ((ms - delay) * (ms - delay) > 4) {
221                         /* Compensate if we're more than 2 ms off */
222                         s->adj -= (ms - delay);
223                 }
224 #if 0
225                 fprintf(stdout, "Delay is %d, adjustment is %d, last was %d\n", delay, s->adj, ms);
226 #endif
227                 delay += s->adj;
228                 if (delay < 1)
229                         delay = 1;
230         } else
231                 gettimeofday(&s->last, NULL);
232         if (s->lasttimeout != delay) {
233                 /* We'll install the next timeout now. */
234                 s->owner->streamid = ast_sched_add(s->owner->sched,
235                                 delay, ast_read_callback, s); 
236                 s->lasttimeout = delay;
237         } else {
238                 /* Just come back again at the same time */
239                 retval = -1;
240         }
241         return retval;
242 }
243
244 static int pcm_apply(struct ast_channel *c, struct ast_filestream *s)
245 {
246         /* Select our owner for this stream, and get the ball rolling. */
247         s->owner = c;
248         return 0;
249 }
250
251 static int pcm_play(struct ast_filestream *s)
252 {
253         ast_read_callback(s);
254         return 0;
255 }
256
257 static int pcm_write(struct ast_filestream *fs, struct ast_frame *f)
258 {
259         int res;
260 #ifdef REALTIME_WRITE
261         unsigned long cur_time;
262         unsigned long fpos;
263         struct stat stat_buf;
264 #endif
265
266         if (f->frametype != AST_FRAME_VOICE) {
267                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
268                 return -1;
269         }
270         if (f->subclass != AST_FORMAT_ALAW) {
271                 ast_log(LOG_WARNING, "Asked to write non-alaw frame (%d)!\n", f->subclass);
272                 return -1;
273         }
274
275 #ifdef REALTIME_WRITE
276         cur_time = get_time();
277         fpos = ( cur_time - fs->start_time ) * 8;       // 8 bytes per msec
278         // Check if we have written to this position yet. If we have, then increment pos by one frame
279         // for some degree of protection against receiving packets in the same clock tick.
280         fstat( fs->fd, &stat_buf );
281         if( stat_buf.st_size > fpos )
282         {
283                 fpos += f->datalen;     // Incrementing with the size of this current frame
284         }
285
286         if( stat_buf.st_size < fpos )
287         {
288                 // fill the gap with 0x55 rather than 0.
289                 char buf[ 512 ];
290                 unsigned long cur, to_write;
291
292                 cur = stat_buf.st_size;
293                 if( lseek( fs->fd, cur, SEEK_SET ) < 0 )
294                 {
295                         ast_log( LOG_WARNING, "Cannot seek in file: %s\n", strerror(errno) );
296                         return -1;
297                 }
298                 memset( buf, 0x55, 512 );
299                 while( cur < fpos )
300                 {
301                         to_write = fpos - cur;
302                         if( to_write > 512 )
303                         {
304                                 to_write = 512;
305                         }
306                         write( fs->fd, buf, to_write );
307                         cur += to_write;
308                 }
309         }
310
311
312         if( lseek( fs->fd, fpos, SEEK_SET ) < 0 )
313         {
314                 ast_log( LOG_WARNING, "Cannot seek in file: %s\n", strerror(errno) );
315                 return -1;
316         }
317 #endif  // REALTIME_WRITE
318         
319         if ((res = write(fs->fd, f->data, f->datalen)) != f->datalen) {
320                         ast_log(LOG_WARNING, "Bad write (%d/%d): %s\n", res, f->datalen, strerror(errno));
321                         return -1;
322         }
323         return 0;
324 }
325
326 static int pcm_seek(struct ast_filestream *fs, long sample_offset, int whence)
327 {
328         off_t offset,min,cur,max;
329
330         min = 0;
331         cur = lseek(fs->fd, 0, SEEK_CUR);
332         max = lseek(fs->fd, 0, SEEK_END);
333         if(whence == SEEK_SET)
334                 offset = sample_offset;
335         if(whence == SEEK_CUR)
336                 offset = sample_offset + cur;
337         if(whence == SEEK_END)
338                 offset = max - sample_offset;
339         offset = (offset > max)?max:offset;
340         offset = (offset < min)?min:offset;
341         return lseek(fs->fd, offset, SEEK_SET);
342 }
343
344 static int pcm_trunc(struct ast_filestream *fs)
345 {
346         return ftruncate(fs->fd, lseek(fs->fd,0,SEEK_CUR));
347 }
348
349 static long pcm_tell(struct ast_filestream *fs)
350 {
351         off_t offset;
352         offset = lseek(fs->fd, 0, SEEK_CUR);
353         return offset;
354 }
355
356
357 static char *pcm_getcomment(struct ast_filestream *s)
358 {
359         return NULL;
360 }
361
362 int load_module()
363 {
364         return ast_format_register(name, exts, AST_FORMAT_ALAW,
365                                                                 pcm_open,
366                                                                 pcm_rewrite,
367                                                                 pcm_apply,
368                                                                 pcm_play,
369                                                                 pcm_write,
370                                                                 pcm_seek,
371                                                                 pcm_trunc,
372                                                                 pcm_tell,
373                                                                 pcm_read,
374                                                                 pcm_close,
375                                                                 pcm_getcomment);
376 }
377
378 int unload_module()
379 {
380         struct ast_filestream *tmp, *tmpl;
381         if (pthread_mutex_lock(&pcm_lock)) {
382                 ast_log(LOG_WARNING, "Unable to lock pcm list\n");
383                 return -1;
384         }
385         tmp = glist;
386         while(tmp) {
387                 if (tmp->owner)
388                         ast_softhangup(tmp->owner, AST_SOFTHANGUP_APPUNLOAD);
389                 tmpl = tmp;
390                 tmp = tmp->next;
391                 free(tmpl);
392         }
393         pthread_mutex_unlock(&pcm_lock);
394         return ast_format_unregister(name);
395 }       
396
397 int usecount()
398 {
399         int res;
400         if (pthread_mutex_lock(&pcm_lock)) {
401                 ast_log(LOG_WARNING, "Unable to lock pcm list\n");
402                 return -1;
403         }
404         res = glistcnt;
405         pthread_mutex_unlock(&pcm_lock);
406         return res;
407 }
408
409 char *description()
410 {
411         return desc;
412 }
413
414
415 char *key()
416 {
417         return ASTERISK_GPL_KEY;
418 }