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