c514b586301b3646f657f8206ee90c1544042c52
[asterisk/asterisk.git] / formats / format_pcm.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Flat, binary, ulaw PCM file format.
22  * \arg File name extension: pcm, ulaw, ul, mu
23  * 
24  * \ingroup formats
25  */
26  
27 #include "asterisk.h"
28
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30
31 #include "asterisk/mod_format.h"
32 #include "asterisk/module.h"
33 #include "asterisk/endian.h"
34 #include "asterisk/ulaw.h"
35 #include "asterisk/alaw.h"
36
37 #define BUF_SIZE 160            /* 160 bytes, and same number of samples */
38
39 static char ulaw_silence[BUF_SIZE];
40 static char alaw_silence[BUF_SIZE];
41
42 /* #define REALTIME_WRITE */    /* XXX does it work at all ? */
43
44 #ifdef REALTIME_WRITE
45 struct pcm_desc {
46         unsigned long start_time;
47 };
48
49 /* Returns time in msec since system boot. */
50 static unsigned long get_time(void)
51 {
52         struct tms buf;
53         clock_t cur;
54
55         cur = times( &buf );
56         if( cur < 0 ) {
57                 ast_log( LOG_WARNING, "Cannot get current time\n" );
58                 return 0;
59         }
60         return cur * 1000 / sysconf( _SC_CLK_TCK );
61 }
62
63 static int pcma_open(struct ast_filestream *s)
64 {
65         if (s->fmt->format == AST_FORMAT_ALAW)
66                 pd->starttime = get_time();
67         return 0;
68 }
69
70 static int pcma_rewrite(struct ast_filestream *s, const char *comment)
71 {
72         return pcma_open(s);
73 }
74 #endif
75
76 static struct ast_frame *pcm_read(struct ast_filestream *s, int *whennext)
77 {
78         int res;
79         
80         /* Send a frame from the file to the appropriate channel */
81
82         s->fr.frametype = AST_FRAME_VOICE;
83         s->fr.subclass = s->fmt->format;
84         s->fr.mallocd = 0;
85         AST_FRAME_SET_BUFFER(&s->fr, s->buf, AST_FRIENDLY_OFFSET, BUF_SIZE);
86         if ((res = fread(s->fr.data, 1, s->fr.datalen, s->f)) < 1) {
87                 if (res)
88                         ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
89                 return NULL;
90         }
91         s->fr.datalen = res;
92         *whennext = s->fr.samples = res;
93         return &s->fr;
94 }
95
96 static int pcm_seek(struct ast_filestream *fs, off_t sample_offset, int whence)
97 {
98         off_t cur, max, offset = 0;
99         int ret = -1;   /* assume error */
100
101         cur = ftello(fs->f);
102         fseeko(fs->f, 0, SEEK_END);
103         max = ftello(fs->f);
104
105         switch (whence) {
106         case SEEK_SET:
107                 offset = sample_offset;
108                 break;
109         case SEEK_END:
110                 offset = max - sample_offset;
111                 break;
112         case SEEK_CUR:
113         case SEEK_FORCECUR:
114                 offset = cur + sample_offset;
115                 break;
116         default:
117                 ast_log(LOG_WARNING, "invalid whence %d, assuming SEEK_SET\n", whence);
118                 offset = sample_offset;
119         }
120         if (offset < 0) {
121                 ast_log(LOG_WARNING, "negative offset %ld, resetting to 0\n", (long) offset);
122                 offset = 0;
123         }
124         if (whence == SEEK_FORCECUR && offset > max) { /* extend the file */
125                 size_t left = offset - max;
126                 const char *src = (fs->fmt->format == AST_FORMAT_ALAW) ? alaw_silence : ulaw_silence;
127
128                 while (left) {
129                         size_t written = fwrite(src, 1, (left > BUF_SIZE) ? BUF_SIZE : left, fs->f);
130                         if (written == -1)
131                                 break;  /* error */
132                         left -= written;
133                 }
134                 ret = 0; /* successful */
135         } else {
136                 if (offset > max) {
137                         ast_log(LOG_WARNING, "offset too large %ld, truncating to %ld\n", (long) offset, (long) max);
138                         offset = max;
139                 }
140                 ret = fseeko(fs->f, offset, SEEK_SET);
141         }
142         return ret;
143 }
144
145 static int pcm_trunc(struct ast_filestream *fs)
146 {
147         return ftruncate(fileno(fs->f), ftello(fs->f));
148 }
149
150 static off_t pcm_tell(struct ast_filestream *fs)
151 {
152         return ftello(fs->f);
153 }
154
155 static int pcm_write(struct ast_filestream *fs, struct ast_frame *f)
156 {
157         int res;
158
159         if (f->frametype != AST_FRAME_VOICE) {
160                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
161                 return -1;
162         }
163         if (f->subclass != fs->fmt->format) {
164                 ast_log(LOG_WARNING, "Asked to write incompatible format frame (%d)!\n", f->subclass);
165                 return -1;
166         }
167
168 #ifdef REALTIME_WRITE
169         if (s->fmt->format == AST_FORMAT_ALAW) {
170                 struct pcm_desc *pd = (struct pcm_desc *)fs->_private;
171                 struct stat stat_buf;
172                 unsigned long cur_time = get_time();
173                 unsigned long fpos = ( cur_time - pd->start_time ) * 8; /* 8 bytes per msec */
174                 /* Check if we have written to this position yet. If we have, then increment pos by one frame
175                 *  for some degree of protection against receiving packets in the same clock tick.
176                 */
177                 
178                 fstat(fileno(fs->f), &stat_buf );
179                 if (stat_buf.st_size > fpos )
180                         fpos += f->datalen;     /* Incrementing with the size of this current frame */
181
182                 if (stat_buf.st_size < fpos) {
183                         /* fill the gap with 0x55 rather than 0. */
184                         char buf[1024];
185                         unsigned long cur, to_write;
186
187                         cur = stat_buf.st_size;
188                         if (fseek(fs->f, cur, SEEK_SET) < 0) {
189                                 ast_log( LOG_WARNING, "Cannot seek in file: %s\n", strerror(errno) );
190                                 return -1;
191                         }
192                         memset(buf, 0x55, 512);
193                         while (cur < fpos) {
194                                 to_write = fpos - cur;
195                                 if (to_write > sizeof(buf))
196                                         to_write = sizeof(buf);
197                                 fwrite(buf, 1, to_write, fs->f);
198                                 cur += to_write;
199                         }
200                 }
201
202                 if (fseek(s->f, fpos, SEEK_SET) < 0) {
203                         ast_log( LOG_WARNING, "Cannot seek in file: %s\n", strerror(errno) );
204                         return -1;
205                 }
206         }
207 #endif  /* REALTIME_WRITE */
208         
209         if ((res = fwrite(f->data, 1, f->datalen, fs->f)) != f->datalen) {
210                 ast_log(LOG_WARNING, "Bad write (%d/%d): %s\n", res, f->datalen, strerror(errno));
211                 return -1;
212         }
213         return 0;
214 }
215
216 /* SUN .au support routines */
217
218 #define AU_HEADER_SIZE          24
219 #define AU_HEADER(var)          uint32_t var[6]
220
221 #define AU_HDR_MAGIC_OFF        0
222 #define AU_HDR_HDR_SIZE_OFF     1
223 #define AU_HDR_DATA_SIZE_OFF    2
224 #define AU_HDR_ENCODING_OFF     3
225 #define AU_HDR_SAMPLE_RATE_OFF  4
226 #define AU_HDR_CHANNELS_OFF     5
227
228 #define AU_ENC_8BIT_ULAW        1
229
230 #define AU_MAGIC 0x2e736e64
231 #if __BYTE_ORDER == __BIG_ENDIAN
232 #define htoll(b) (b)
233 #define htols(b) (b)
234 #define ltohl(b) (b)
235 #define ltohs(b) (b)
236 #else
237 #if __BYTE_ORDER == __LITTLE_ENDIAN
238 #define htoll(b)  \
239           (((((b)      ) & 0xFF) << 24) | \
240                ((((b) >>  8) & 0xFF) << 16) | \
241                    ((((b) >> 16) & 0xFF) <<  8) | \
242                    ((((b) >> 24) & 0xFF)      ))
243 #define htols(b) \
244           (((((b)      ) & 0xFF) << 8) | \
245                    ((((b) >> 8) & 0xFF)      ))
246 #define ltohl(b) htoll(b)
247 #define ltohs(b) htols(b)
248 #else
249 #error "Endianess not defined"
250 #endif
251 #endif
252
253 static int check_header(FILE *f)
254 {
255         AU_HEADER(header);
256         uint32_t magic;
257         uint32_t hdr_size;
258         uint32_t data_size;
259         uint32_t encoding;
260         uint32_t sample_rate;
261         uint32_t channels;
262
263         if (fread(header, 1, AU_HEADER_SIZE, f) != AU_HEADER_SIZE) {
264                 ast_log(LOG_WARNING, "Read failed (header)\n");
265                 return -1;
266         }
267         magic = ltohl(header[AU_HDR_MAGIC_OFF]);
268         if (magic != (uint32_t) AU_MAGIC) {
269                 ast_log(LOG_WARNING, "Bad magic: 0x%x\n", magic);
270         }
271 /*      hdr_size = ltohl(header[AU_HDR_HDR_SIZE_OFF]);
272         if (hdr_size < AU_HEADER_SIZE)*/
273         hdr_size = AU_HEADER_SIZE;
274 /*      data_size = ltohl(header[AU_HDR_DATA_SIZE_OFF]); */
275         encoding = ltohl(header[AU_HDR_ENCODING_OFF]);
276         if (encoding != AU_ENC_8BIT_ULAW) {
277                 ast_log(LOG_WARNING, "Unexpected format: %d. Only 8bit ULAW allowed (%d)\n", encoding, AU_ENC_8BIT_ULAW);
278                 return -1;
279         }
280         sample_rate = ltohl(header[AU_HDR_SAMPLE_RATE_OFF]);
281         if (sample_rate != DEFAULT_SAMPLE_RATE) {
282                 ast_log(LOG_WARNING, "Sample rate can only be 8000 not %d\n", sample_rate);
283                 return -1;
284         }
285         channels = ltohl(header[AU_HDR_CHANNELS_OFF]);
286         if (channels != 1) {
287                 ast_log(LOG_WARNING, "Not in mono: channels=%d\n", channels);
288                 return -1;
289         }
290         /* Skip to data */
291         fseek(f, 0, SEEK_END);
292         data_size = ftell(f) - hdr_size;
293         if (fseek(f, hdr_size, SEEK_SET) == -1 ) {
294                 ast_log(LOG_WARNING, "Failed to skip to data: %d\n", hdr_size);
295                 return -1;
296         }
297         return data_size;
298 }
299
300 static int update_header(FILE *f)
301 {
302         off_t cur, end;
303         uint32_t datalen;
304         int bytes;
305
306         cur = ftell(f);
307         fseek(f, 0, SEEK_END);
308         end = ftell(f);
309         /* data starts 24 bytes in */
310         bytes = end - AU_HEADER_SIZE;
311         datalen = htoll(bytes);
312
313         if (cur < 0) {
314                 ast_log(LOG_WARNING, "Unable to find our position\n");
315                 return -1;
316         }
317         if (fseek(f, AU_HDR_DATA_SIZE_OFF * sizeof(uint32_t), SEEK_SET)) {
318                 ast_log(LOG_WARNING, "Unable to set our position\n");
319                 return -1;
320         }
321         if (fwrite(&datalen, 1, sizeof(datalen), f) != sizeof(datalen)) {
322                 ast_log(LOG_WARNING, "Unable to set write file size\n");
323                 return -1;
324         }
325         if (fseek(f, cur, SEEK_SET)) {
326                 ast_log(LOG_WARNING, "Unable to return to position\n");
327                 return -1;
328         }
329         return 0;
330 }
331
332 static int write_header(FILE *f)
333 {
334         AU_HEADER(header);
335
336         header[AU_HDR_MAGIC_OFF] = htoll((uint32_t) AU_MAGIC);
337         header[AU_HDR_HDR_SIZE_OFF] = htoll(AU_HEADER_SIZE);
338         header[AU_HDR_DATA_SIZE_OFF] = 0;
339         header[AU_HDR_ENCODING_OFF] = htoll(AU_ENC_8BIT_ULAW);
340         header[AU_HDR_SAMPLE_RATE_OFF] = htoll(DEFAULT_SAMPLE_RATE);
341         header[AU_HDR_CHANNELS_OFF] = htoll(1);
342
343         /* Write an au header, ignoring sizes which will be filled in later */
344         fseek(f, 0, SEEK_SET);
345         if (fwrite(header, 1, AU_HEADER_SIZE, f) != AU_HEADER_SIZE) {
346                 ast_log(LOG_WARNING, "Unable to write header\n");
347                 return -1;
348         }
349         return 0;
350 }
351
352 static int au_open(struct ast_filestream *s)
353 {
354         if (check_header(s->f) < 0)
355                 return -1;
356         return 0;
357 }
358
359 static int au_rewrite(struct ast_filestream *s, const char *comment)
360 {
361         if (write_header(s->f))
362                 return -1;
363         return 0;
364 }
365
366 /* XXX check this, probably incorrect */
367 static int au_seek(struct ast_filestream *fs, off_t sample_offset, int whence)
368 {
369         off_t min, max, cur;
370         long offset = 0, samples;
371         
372         samples = sample_offset;
373         min = AU_HEADER_SIZE;
374         cur = ftello(fs->f);
375         fseek(fs->f, 0, SEEK_END);
376         max = ftello(fs->f);
377         if (whence == SEEK_SET)
378                 offset = samples + min;
379         else if (whence == SEEK_CUR || whence == SEEK_FORCECUR)
380                 offset = samples + cur;
381         else if (whence == SEEK_END)
382                 offset = max - samples;
383         if (whence != SEEK_FORCECUR) {
384                 offset = (offset > max) ? max : offset;
385         }
386         /* always protect the header space. */
387         offset = (offset < min) ? min : offset;
388         return fseeko(fs->f, offset, SEEK_SET);
389 }
390
391 static int au_trunc(struct ast_filestream *fs)
392 {
393         if (ftruncate(fileno(fs->f), ftell(fs->f)))
394                 return -1;
395         return update_header(fs->f);
396 }
397
398 static off_t au_tell(struct ast_filestream *fs)
399 {
400         off_t offset = ftello(fs->f);
401         return offset - AU_HEADER_SIZE;
402 }
403
404 static const struct ast_format alaw_f = {
405         .name = "alaw",
406         .exts = "alaw|al",
407         .format = AST_FORMAT_ALAW,
408         .write = pcm_write,
409         .seek = pcm_seek,
410         .trunc = pcm_trunc,
411         .tell = pcm_tell,
412         .read = pcm_read,
413         .buf_size = BUF_SIZE + AST_FRIENDLY_OFFSET,
414 #ifdef REALTIME_WRITE
415         .open = pcma_open,
416         .rewrite = pcma_rewrite,
417         .desc_size = sizeof(struct pcm_desc),
418 #endif
419 };
420
421 static const struct ast_format pcm_f = {
422         .name = "pcm",
423         .exts = "pcm|ulaw|ul|mu",
424         .format = AST_FORMAT_ULAW,
425         .write = pcm_write,
426         .seek = pcm_seek,
427         .trunc = pcm_trunc,
428         .tell = pcm_tell,
429         .read = pcm_read,
430         .buf_size = BUF_SIZE + AST_FRIENDLY_OFFSET,
431 };
432
433 static const struct ast_format g722_f = {
434         .name = "g722",
435         .exts = "g722",
436         .format = AST_FORMAT_G722,
437         .write = pcm_write,
438         .seek = pcm_seek,
439         .trunc = pcm_trunc,
440         .tell = pcm_tell,
441         .read = pcm_read,
442         .buf_size = (BUF_SIZE * 2) + AST_FRIENDLY_OFFSET,
443 };
444
445 static const struct ast_format au_f = {
446         .name = "au",
447         .exts = "au",
448         .format = AST_FORMAT_ULAW,
449         .open = au_open,
450         .rewrite = au_rewrite,
451         .write = pcm_write,
452         .seek = au_seek,
453         .trunc = au_trunc,
454         .tell = au_tell,
455         .read = pcm_read,
456         .buf_size = BUF_SIZE + AST_FRIENDLY_OFFSET,     /* this many shorts */
457 };
458
459 static int load_module(void)
460 {
461         int index;
462
463         /* XXX better init ? */
464         for (index = 0; index < (sizeof(ulaw_silence) / sizeof(ulaw_silence[0])); index++)
465                 ulaw_silence[index] = AST_LIN2MU(0);
466         for (index = 0; index < (sizeof(alaw_silence) / sizeof(alaw_silence[0])); index++)
467                 alaw_silence[index] = AST_LIN2A(0);
468
469         if ( ast_format_register(&pcm_f)
470                 || ast_format_register(&alaw_f)
471                 || ast_format_register(&au_f)
472                 || ast_format_register(&g722_f) )
473                 return AST_MODULE_LOAD_FAILURE;
474         return AST_MODULE_LOAD_SUCCESS;
475 }
476
477 static int unload_module(void)
478 {
479         return ast_format_unregister(pcm_f.name)
480                 || ast_format_unregister(alaw_f.name)
481                 || ast_format_unregister(au_f.name)
482                 || ast_format_unregister(g722_f.name);
483 }       
484
485 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Raw/Sun uLaw/ALaw 8KHz (PCM,PCMA,AU), G.722 16Khz");