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