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