Merged revisions 90155 via svnmerge from
[asterisk/asterisk.git] / formats / format_ogg_vorbis.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2005, Jeff Ollie
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*! \file
18  *
19  * \brief OGG/Vorbis streams.
20  * \arg File name extension: ogg
21  * \ingroup formats
22  */
23
24 /* the order of these dependencies is important... it also specifies
25    the link order of the libraries during linking
26 */
27
28 /*** MODULEINFO
29         <depend>vorbis</depend>
30         <depend>ogg</depend>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <vorbis/codec.h>
38 #include <vorbis/vorbisenc.h>
39
40 #ifdef _WIN32
41 #include <io.h>
42 #endif
43
44 #include "asterisk/mod_format.h"
45 #include "asterisk/module.h"
46
47 /*
48  * this is the number of samples we deal with. Samples are converted
49  * to SLINEAR so each one uses 2 bytes in the buffer.
50  */
51 #define SAMPLES_MAX 160
52 #define BUF_SIZE        (2*SAMPLES_MAX)
53
54 #define BLOCK_SIZE 4096         /* used internally in the vorbis routines */
55
56 struct vorbis_desc {    /* format specific parameters */
57         /* structures for handling the Ogg container */
58         ogg_sync_state oy;
59         ogg_stream_state os;
60         ogg_page og;
61         ogg_packet op;
62         
63         /* structures for handling Vorbis audio data */
64         vorbis_info vi;
65         vorbis_comment vc;
66         vorbis_dsp_state vd;
67         vorbis_block vb;
68         
69         /*! \brief Indicates whether this filestream is set up for reading or writing. */
70         int writing;
71         
72         /*! \brief Indicates whether an End of Stream condition has been detected. */
73         int eos;
74 };
75
76 /*!
77  * \brief Create a new OGG/Vorbis filestream and set it up for reading.
78  * \param s File that points to on disk storage of the OGG/Vorbis data.
79  * \return The new filestream.
80  */
81 static int ogg_vorbis_open(struct ast_filestream *s)
82 {
83         int i;
84         int bytes;
85         int result;
86         char **ptr;
87         char *buffer;
88         struct vorbis_desc *tmp = (struct vorbis_desc *)s->_private;
89
90         tmp->writing = 0;
91
92         ogg_sync_init(&tmp->oy);
93
94         buffer = ogg_sync_buffer(&tmp->oy, BLOCK_SIZE);
95         bytes = fread(buffer, 1, BLOCK_SIZE, s->f);
96         ogg_sync_wrote(&tmp->oy, bytes);
97
98         result = ogg_sync_pageout(&tmp->oy, &tmp->og);
99         if (result != 1) {
100                 if(bytes < BLOCK_SIZE) {
101                         ast_log(LOG_ERROR, "Run out of data...\n");
102                 } else {
103                         ast_log(LOG_ERROR, "Input does not appear to be an Ogg bitstream.\n");
104                 }
105                 ogg_sync_clear(&tmp->oy);
106                 return -1;
107         }
108         
109         ogg_stream_init(&tmp->os, ogg_page_serialno(&tmp->og));
110         vorbis_info_init(&tmp->vi);
111         vorbis_comment_init(&tmp->vc);
112
113         if (ogg_stream_pagein(&tmp->os, &tmp->og) < 0) { 
114                 ast_log(LOG_ERROR, "Error reading first page of Ogg bitstream data.\n");
115 error:
116                 ogg_stream_clear(&tmp->os);
117                 vorbis_comment_clear(&tmp->vc);
118                 vorbis_info_clear(&tmp->vi);
119                 ogg_sync_clear(&tmp->oy);
120                 return -1;
121         }
122         
123         if (ogg_stream_packetout(&tmp->os, &tmp->op) != 1) { 
124                 ast_log(LOG_ERROR, "Error reading initial header packet.\n");
125                 goto error;
126         }
127         
128         if (vorbis_synthesis_headerin(&tmp->vi, &tmp->vc, &tmp->op) < 0) { 
129                 ast_log(LOG_ERROR, "This Ogg bitstream does not contain Vorbis audio data.\n");
130                 goto error;
131         }
132         
133         for (i = 0; i < 2 ; ) {
134                 while (i < 2) {
135                         result = ogg_sync_pageout(&tmp->oy, &tmp->og);
136                         if (result == 0)
137                                 break;
138                         if (result == 1) {
139                                 ogg_stream_pagein(&tmp->os, &tmp->og);
140                                 while(i < 2) {
141                                         result = ogg_stream_packetout(&tmp->os,&tmp->op);
142                                         if(result == 0)
143                                                 break;
144                                         if(result < 0) {
145                                                 ast_log(LOG_ERROR, "Corrupt secondary header.  Exiting.\n");
146                                                 goto error;
147                                         }
148                                         vorbis_synthesis_headerin(&tmp->vi, &tmp->vc, &tmp->op);
149                                         i++;
150                                 }
151                         }
152                 }
153
154                 buffer = ogg_sync_buffer(&tmp->oy, BLOCK_SIZE);
155                 bytes = fread(buffer, 1, BLOCK_SIZE, s->f);
156                 if (bytes == 0 && i < 2) {
157                         ast_log(LOG_ERROR, "End of file before finding all Vorbis headers!\n");
158                         goto error;
159                 }
160                 ogg_sync_wrote(&tmp->oy, bytes);
161         }
162         
163         for (ptr = tmp->vc.user_comments; *ptr; ptr++)
164                 ast_debug(1, "OGG/Vorbis comment: %s\n", *ptr);
165                 ast_debug(1, "OGG/Vorbis bitstream is %d channel, %ldHz\n", tmp->vi.channels, tmp->vi.rate);
166                 ast_debug(1, "OGG/Vorbis file encoded by: %s\n", tmp->vc.vendor);
167
168         if (tmp->vi.channels != 1) {
169                 ast_log(LOG_ERROR, "Only monophonic OGG/Vorbis files are currently supported!\n");
170                 goto error;
171         }
172         
173         if (tmp->vi.rate != DEFAULT_SAMPLE_RATE) {
174                 ast_log(LOG_ERROR, "Only 8000Hz OGG/Vorbis files are currently supported!\n");
175                 vorbis_block_clear(&tmp->vb);
176                 vorbis_dsp_clear(&tmp->vd);
177                 goto error;
178         }
179         
180         vorbis_synthesis_init(&tmp->vd, &tmp->vi);
181         vorbis_block_init(&tmp->vd, &tmp->vb);
182
183         return 0;
184 }
185
186 /*!
187  * \brief Create a new OGG/Vorbis filestream and set it up for writing.
188  * \param s File pointer that points to on-disk storage.
189  * \param comment Comment that should be embedded in the OGG/Vorbis file.
190  * \return A new filestream.
191  */
192 static int ogg_vorbis_rewrite(struct ast_filestream *s,
193                                                  const char *comment)
194 {
195         ogg_packet header;
196         ogg_packet header_comm;
197         ogg_packet header_code;
198         struct vorbis_desc *tmp = (struct vorbis_desc *)s->_private;
199
200         tmp->writing = 1;
201
202         vorbis_info_init(&tmp->vi);
203
204         if (vorbis_encode_init_vbr(&tmp->vi, 1, DEFAULT_SAMPLE_RATE, 0.4)) {
205                 ast_log(LOG_ERROR, "Unable to initialize Vorbis encoder!\n");
206                 return -1;
207         }
208
209         vorbis_comment_init(&tmp->vc);
210         vorbis_comment_add_tag(&tmp->vc, "ENCODER", "Asterisk PBX");
211         if (comment)
212                 vorbis_comment_add_tag(&tmp->vc, "COMMENT", (char *) comment);
213
214         vorbis_analysis_init(&tmp->vd, &tmp->vi);
215         vorbis_block_init(&tmp->vd, &tmp->vb);
216
217         ogg_stream_init(&tmp->os, ast_random());
218
219         vorbis_analysis_headerout(&tmp->vd, &tmp->vc, &header, &header_comm,
220                                   &header_code);
221         ogg_stream_packetin(&tmp->os, &header);
222         ogg_stream_packetin(&tmp->os, &header_comm);
223         ogg_stream_packetin(&tmp->os, &header_code);
224
225         while (!tmp->eos) {
226                 if (ogg_stream_flush(&tmp->os, &tmp->og) == 0)
227                         break;
228                 fwrite(tmp->og.header, 1, tmp->og.header_len, s->f);
229                 fwrite(tmp->og.body, 1, tmp->og.body_len, s->f);
230                 if (ogg_page_eos(&tmp->og))
231                         tmp->eos = 1;
232         }
233
234         return 0;
235 }
236
237 /*!
238  * \brief Write out any pending encoded data.
239  * \param s An OGG/Vorbis filestream.
240  * \param f The file to write to.
241  */
242 static void write_stream(struct vorbis_desc *s, FILE *f)
243 {
244         while (vorbis_analysis_blockout(&s->vd, &s->vb) == 1) {
245                 vorbis_analysis(&s->vb, NULL);
246                 vorbis_bitrate_addblock(&s->vb);
247
248                 while (vorbis_bitrate_flushpacket(&s->vd, &s->op)) {
249                         ogg_stream_packetin(&s->os, &s->op);
250                         while (!s->eos) {
251                                 if (ogg_stream_pageout(&s->os, &s->og) == 0) {
252                                         break;
253                                 }
254                                 fwrite(s->og.header, 1, s->og.header_len, f);
255                                 fwrite(s->og.body, 1, s->og.body_len, f);
256                                 if (ogg_page_eos(&s->og)) {
257                                         s->eos = 1;
258                                 }
259                         }
260                 }
261         }
262 }
263
264 /*!
265  * \brief Write audio data from a frame to an OGG/Vorbis filestream.
266  * \param fs An OGG/Vorbis filestream.
267  * \param f A frame containing audio to be written to the filestream.
268  * \return -1 if there was an error, 0 on success.
269  */
270 static int ogg_vorbis_write(struct ast_filestream *fs, struct ast_frame *f)
271 {
272         int i;
273         float **buffer;
274         short *data;
275         struct vorbis_desc *s = (struct vorbis_desc *)fs->_private;
276
277         if (!s->writing) {
278                 ast_log(LOG_ERROR, "This stream is not set up for writing!\n");
279                 return -1;
280         }
281
282         if (f->frametype != AST_FRAME_VOICE) {
283                 ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
284                 return -1;
285         }
286         if (f->subclass != AST_FORMAT_SLINEAR) {
287                 ast_log(LOG_WARNING, "Asked to write non-SLINEAR frame (%d)!\n",
288                                 f->subclass);
289                 return -1;
290         }
291         if (!f->datalen)
292                 return -1;
293
294         data = (short *) f->data;
295
296         buffer = vorbis_analysis_buffer(&s->vd, f->samples);
297
298         for (i = 0; i < f->samples; i++)
299                 buffer[0][i] = (double)data[i] / 32768.0;
300
301         vorbis_analysis_wrote(&s->vd, f->samples);
302
303         write_stream(s, fs->f);
304
305         return 0;
306 }
307
308 /*!
309  * \brief Close a OGG/Vorbis filestream.
310  * \param fs A OGG/Vorbis filestream.
311  */
312 static void ogg_vorbis_close(struct ast_filestream *fs)
313 {
314         struct vorbis_desc *s = (struct vorbis_desc *)fs->_private;
315
316         if (s->writing) {
317                 /* Tell the Vorbis encoder that the stream is finished
318                  * and write out the rest of the data */
319                 vorbis_analysis_wrote(&s->vd, 0);
320                 write_stream(s, fs->f);
321         }
322
323         ogg_stream_clear(&s->os);
324         vorbis_block_clear(&s->vb);
325         vorbis_dsp_clear(&s->vd);
326         vorbis_comment_clear(&s->vc);
327         vorbis_info_clear(&s->vi);
328
329         if (s->writing) {
330                 ogg_sync_clear(&s->oy);
331         }
332 }
333
334 /*!
335  * \brief Get audio data.
336  * \param fs An OGG/Vorbis filestream.
337  * \param pcm Pointer to a buffere to store audio data in.
338  */
339
340 static int read_samples(struct ast_filestream *fs, float ***pcm)
341 {
342         int samples_in;
343         int result;
344         char *buffer;
345         int bytes;
346         struct vorbis_desc *s = (struct vorbis_desc *)fs->_private;
347
348         while (1) {
349                 samples_in = vorbis_synthesis_pcmout(&s->vd, pcm);
350                 if (samples_in > 0) {
351                         return samples_in;
352                 }
353
354                 /* The Vorbis decoder needs more data... */
355                 /* See ifOGG has any packets in the current page for the Vorbis decoder. */
356                 result = ogg_stream_packetout(&s->os, &s->op);
357                 if (result > 0) {
358                         /* Yes OGG had some more packets for the Vorbis decoder. */
359                         if (vorbis_synthesis(&s->vb, &s->op) == 0) {
360                                 vorbis_synthesis_blockin(&s->vd, &s->vb);
361                         }
362
363                         continue;
364                 }
365
366                 if (result < 0)
367                         ast_log(LOG_WARNING,
368                                         "Corrupt or missing data at this page position; continuing...\n");
369
370                 /* No more packets left in the current page... */
371
372                 if (s->eos) {
373                         /* No more pages left in the stream */
374                         return -1;
375                 }
376
377                 while (!s->eos) {
378                         /* See ifOGG has any pages in it's internal buffers */
379                         result = ogg_sync_pageout(&s->oy, &s->og);
380                         if (result > 0) {
381                                 /* Yes, OGG has more pages in it's internal buffers,
382                                    add the page to the stream state */
383                                 result = ogg_stream_pagein(&s->os, &s->og);
384                                 if (result == 0) {
385                                         /* Yes, got a new,valid page */
386                                         if (ogg_page_eos(&s->og)) {
387                                                 s->eos = 1;
388                                         }
389                                         break;
390                                 }
391                                 ast_log(LOG_WARNING,
392                                                 "Invalid page in the bitstream; continuing...\n");
393                         }
394
395                         if (result < 0)
396                                 ast_log(LOG_WARNING,
397                                                 "Corrupt or missing data in bitstream; continuing...\n");
398
399                         /* No, we need to read more data from the file descrptor */
400                         /* get a buffer from OGG to read the data into */
401                         buffer = ogg_sync_buffer(&s->oy, BLOCK_SIZE);
402                         /* read more data from the file descriptor */
403                         bytes = fread(buffer, 1, BLOCK_SIZE, fs->f);
404                         /* Tell OGG how many bytes we actually read into the buffer */
405                         ogg_sync_wrote(&s->oy, bytes);
406                         if (bytes == 0) {
407                                 s->eos = 1;
408                         }
409                 }
410         }
411 }
412
413 /*!
414  * \brief Read a frame full of audio data from the filestream.
415  * \param fs The filestream.
416  * \param whennext Number of sample times to schedule the next call.
417  * \return A pointer to a frame containing audio data or NULL ifthere is no more audio data.
418  */
419 static struct ast_frame *ogg_vorbis_read(struct ast_filestream *fs,
420                                          int *whennext)
421 {
422         int clipflag = 0;
423         int i;
424         int j;
425         double accumulator[SAMPLES_MAX];
426         int val;
427         int samples_in;
428         int samples_out = 0;
429         struct vorbis_desc *s = (struct vorbis_desc *)fs->_private;
430         short *buf;     /* SLIN data buffer */
431
432         fs->fr.frametype = AST_FRAME_VOICE;
433         fs->fr.subclass = AST_FORMAT_SLINEAR;
434         fs->fr.mallocd = 0;
435         AST_FRAME_SET_BUFFER(&fs->fr, fs->buf, AST_FRIENDLY_OFFSET, BUF_SIZE);
436         buf = (short *)(fs->fr.data);   /* SLIN data buffer */
437
438         while (samples_out != SAMPLES_MAX) {
439                 float **pcm;
440                 int len = SAMPLES_MAX - samples_out;
441
442                 /* See ifVorbis decoder has some audio data for us ... */
443                 samples_in = read_samples(fs, &pcm);
444                 if (samples_in <= 0)
445                         break;
446
447                 /* Got some audio data from Vorbis... */
448                 /* Convert the float audio data to 16-bit signed linear */
449
450                 clipflag = 0;
451                 if (samples_in > len)
452                         samples_in = len;
453                 for (j = 0; j < samples_in; j++)
454                         accumulator[j] = 0.0;
455
456                 for (i = 0; i < s->vi.channels; i++) {
457                         float *mono = pcm[i];
458                         for (j = 0; j < samples_in; j++)
459                                 accumulator[j] += mono[j];
460                 }
461
462                 for (j = 0; j < samples_in; j++) {
463                         val = accumulator[j] * 32767.0 / s->vi.channels;
464                         if (val > 32767) {
465                                 val = 32767;
466                                 clipflag = 1;
467                         } else if (val < -32768) {
468                                 val = -32768;
469                                 clipflag = 1;
470                         }
471                         buf[samples_out + j] = val;
472                 }
473
474                 if (clipflag)
475                         ast_log(LOG_WARNING, "Clipping in frame %ld\n", (long) (s->vd.sequence));
476                 /* Tell the Vorbis decoder how many samples we actually used. */
477                 vorbis_synthesis_read(&s->vd, samples_in);
478                 samples_out += samples_in;
479         }
480
481         if (samples_out > 0) {
482                 fs->fr.datalen = samples_out * 2;
483                 fs->fr.samples = samples_out;
484                 *whennext = samples_out;
485
486                 return &fs->fr;
487         } else {
488                 return NULL;
489         }
490 }
491
492 /*!
493  * \brief Trucate an OGG/Vorbis filestream.
494  * \param s The filestream to truncate.
495  * \return 0 on success, -1 on failure.
496  */
497
498 static int ogg_vorbis_trunc(struct ast_filestream *s)
499 {
500         ast_log(LOG_WARNING, "Truncation is not supported on OGG/Vorbis streams!\n");
501         return -1;
502 }
503
504 /*!
505  * \brief Seek to a specific position in an OGG/Vorbis filestream.
506  * \param s The filestream to truncate.
507  * \param sample_offset New position for the filestream, measured in 8KHz samples.
508  * \param whence Location to measure 
509  * \return 0 on success, -1 on failure.
510  */
511 static int ogg_vorbis_seek(struct ast_filestream *s, off_t sample_offset, int whence)
512 {
513         ast_log(LOG_WARNING, "Seeking is not supported on OGG/Vorbis streams!\n");
514         return -1;
515 }
516
517 static off_t ogg_vorbis_tell(struct ast_filestream *s)
518 {
519         ast_log(LOG_WARNING, "Telling is not supported on OGG/Vorbis streams!\n");
520         return -1;
521 }
522
523 static const struct ast_format vorbis_f = {
524         .name = "ogg_vorbis",
525         .exts = "ogg",
526         .format = AST_FORMAT_SLINEAR,
527         .open = ogg_vorbis_open,
528         .rewrite = ogg_vorbis_rewrite,
529         .write = ogg_vorbis_write,
530         .seek = ogg_vorbis_seek,
531         .trunc = ogg_vorbis_trunc,
532         .tell = ogg_vorbis_tell,
533         .read = ogg_vorbis_read,
534         .close = ogg_vorbis_close,
535         .buf_size = BUF_SIZE + AST_FRIENDLY_OFFSET,
536         .desc_size = sizeof(struct vorbis_desc),
537 };
538
539 static int load_module(void)
540 {
541         if (ast_format_register(&vorbis_f))
542                 return AST_MODULE_LOAD_FAILURE;
543         return AST_MODULE_LOAD_SUCCESS;
544 }
545
546 static int unload_module(void)
547 {
548         return ast_format_unregister(vorbis_f.name);
549 }
550
551 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "OGG/Vorbis audio");
552