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