99223cd8904dfe21dbaaabdc262b27dbb8e11ffd
[Faustine.git] / interpretor / lib / src / libsndfile-1.0.25 / src / ogg_vorbis.c
1 /*
2 ** Copyright (C) 2002-2011 Erik de Castro Lopo <erikd@mega-nerd.com>
3 ** Copyright (C) 2002-2005 Michael Smith <msmith@xiph.org>
4 ** Copyright (C) 2007 John ffitch
5 **
6 ** This program is free software ; you can redistribute it and/or modify
7 ** it under the terms of the GNU Lesser General Public License as published by
8 ** the Free Software Foundation ; either version 2.1 of the License, or
9 ** (at your option) any later version.
10 **
11 ** This program is distributed in the hope that it will be useful,
12 ** but WITHOUT ANY WARRANTY ; without even the implied warranty of
13 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ** GNU Lesser General Public License for more details.
15 **
16 ** You should have received a copy of the GNU Lesser General Public License
17 ** along with this program ; if not, write to the Free Software
18 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20
21 /*
22 ** Much of this code is based on the examples in libvorbis from the
23 ** XIPHOPHORUS Company http://www.xiph.org/ which has a BSD-style Licence
24 ** Copyright (c) 2002, Xiph.org Foundation
25 **
26 ** Redistribution and use in source and binary forms, with or without
27 ** modification, are permitted provided that the following conditions
28 ** are met:
29 **
30 ** - Redistributions of source code must retain the above copyright
31 ** notice, this list of conditions and the following disclaimer.
32 **
33 ** - Redistributions in binary form must reproduce the above copyright
34 ** notice, this list of conditions and the following disclaimer in the
35 ** documentation and/or other materials provided with the distribution.
36 **
37 ** - Neither the name of the Xiph.org Foundation nor the names of its
38 ** contributors may be used to endorse or promote products derived from
39 ** this software without specific prior written permission.
40 **
41 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
42 ** ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
43 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
44 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
45 ** OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
47 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE,
48 ** DATA, OR PROFITS ; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
49 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
50 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
51 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
52 */
53
54 #include "sfconfig.h"
55
56 #include <stdio.h>
57 #include <fcntl.h>
58 #include <string.h>
59 #include <ctype.h>
60 #include <time.h>
61 #include <math.h>
62
63 #if HAVE_UNISTD_H
64 #include <unistd.h>
65 #endif
66
67 #include "sndfile.h"
68 #include "sfendian.h"
69 #include "common.h"
70
71 #if HAVE_EXTERNAL_LIBS
72
73 #include <ogg/ogg.h>
74 #include <vorbis/codec.h>
75 #include <vorbis/vorbisenc.h>
76
77 #include "ogg.h"
78
79 typedef int convert_func (int, void *, int, int, float **) ;
80
81 static int vorbis_read_header (SF_PRIVATE *psf, int log_data) ;
82 static int vorbis_write_header (SF_PRIVATE *psf, int calc_length) ;
83 static int vorbis_close (SF_PRIVATE *psf) ;
84 static int vorbis_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
85 static sf_count_t vorbis_seek (SF_PRIVATE *psf, int mode, sf_count_t offset) ;
86 static sf_count_t vorbis_read_s (SF_PRIVATE *psf, short *ptr, sf_count_t len) ;
87 static sf_count_t vorbis_read_i (SF_PRIVATE *psf, int *ptr, sf_count_t len) ;
88 static sf_count_t vorbis_read_f (SF_PRIVATE *psf, float *ptr, sf_count_t len) ;
89 static sf_count_t vorbis_read_d (SF_PRIVATE *psf, double *ptr, sf_count_t len) ;
90 static sf_count_t vorbis_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t len) ;
91 static sf_count_t vorbis_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t len) ;
92 static sf_count_t vorbis_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t len) ;
93 static sf_count_t vorbis_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t len) ;
94 static sf_count_t vorbis_read_sample (SF_PRIVATE *psf, void *ptr, sf_count_t lens, convert_func *transfn) ;
95 static sf_count_t vorbis_length (SF_PRIVATE *psf) ;
96
97 typedef struct
98 { int id ;
99 const char *name ;
100 } STR_PAIRS ;
101
102 static STR_PAIRS vorbis_metatypes [] =
103 { { SF_STR_TITLE, "Title" },
104 { SF_STR_COPYRIGHT, "Copyright" },
105 { SF_STR_SOFTWARE, "Software" },
106 { SF_STR_ARTIST, "Artist" },
107 { SF_STR_COMMENT, "Comment" },
108 { SF_STR_DATE, "Date" },
109 { SF_STR_ALBUM, "Album" },
110 { SF_STR_LICENSE, "License" },
111 } ;
112
113 typedef struct
114 { /* Count current location */
115 sf_count_t loc ;
116 /* Struct that stores all the static vorbis bitstream settings */
117 vorbis_info vinfo ;
118 /* Struct that stores all the bitstream user comments */
119 vorbis_comment vcomment ;
120 /* Ventral working state for the packet->PCM decoder */
121 vorbis_dsp_state vdsp ;
122 /* Local working space for packet->PCM decode */
123 vorbis_block vblock ;
124
125 /* Encoding quality in range [0.0, 1.0]. */
126 double quality ;
127 } VORBIS_PRIVATE ;
128
129 static int
130 vorbis_read_header (SF_PRIVATE *psf, int log_data)
131 {
132 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
133 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
134 char *buffer ;
135 int bytes ;
136 int i, nn ;
137
138 odata->eos = 0 ;
139
140 /* Weird stuff happens if these aren't called. */
141 ogg_stream_reset (&odata->ostream) ;
142 ogg_sync_reset (&odata->osync) ;
143
144 /*
145 ** Grab some data at the head of the stream. We want the first page
146 ** (which is guaranteed to be small and only contain the Vorbis
147 ** stream initial header) We need the first page to get the stream
148 ** serialno.
149 */
150
151 /* Expose the buffer */
152 buffer = ogg_sync_buffer (&odata->osync, 4096L) ;
153
154 /* Grab the part of the header that has already been read. */
155 memcpy (buffer, psf->header, psf->headindex) ;
156 bytes = psf->headindex ;
157
158 /* Submit a 4k block to libvorbis' Ogg layer */
159 bytes += psf_fread (buffer + psf->headindex, 1, 4096 - psf->headindex, psf) ;
160 ogg_sync_wrote (&odata->osync, bytes) ;
161
162 /* Get the first page. */
163 if ((nn = ogg_sync_pageout (&odata->osync, &odata->opage)) != 1)
164 {
165 /* Have we simply run out of data? If so, we're done. */
166 if (bytes < 4096)
167 return 0 ;
168
169 /* Error case. Must not be Vorbis data */
170 psf_log_printf (psf, "Input does not appear to be an Ogg bitstream.\n") ;
171 return SFE_MALFORMED_FILE ;
172 } ;
173
174 /*
175 ** Get the serial number and set up the rest of decode.
176 ** Serialno first ; use it to set up a logical stream.
177 */
178 ogg_stream_clear (&odata->ostream) ;
179 ogg_stream_init (&odata->ostream, ogg_page_serialno (&odata->opage)) ;
180
181 if (ogg_stream_pagein (&odata->ostream, &odata->opage) < 0)
182 { /* Error ; stream version mismatch perhaps. */
183 psf_log_printf (psf, "Error reading first page of Ogg bitstream data\n") ;
184 return SFE_MALFORMED_FILE ;
185 } ;
186
187 if (ogg_stream_packetout (&odata->ostream, &odata->opacket) != 1)
188 { /* No page? must not be vorbis. */
189 psf_log_printf (psf, "Error reading initial header packet.\n") ;
190 return SFE_MALFORMED_FILE ;
191 } ;
192
193 /*
194 ** This function (vorbis_read_header) gets called multiple times, so the OGG
195 ** and vorbis structs have to be cleared every time we pass through to
196 ** prevent memory leaks.
197 */
198 vorbis_block_clear (&vdata->vblock) ;
199 vorbis_dsp_clear (&vdata->vdsp) ;
200 vorbis_comment_clear (&vdata->vcomment) ;
201 vorbis_info_clear (&vdata->vinfo) ;
202
203 /*
204 ** Extract the initial header from the first page and verify that the
205 ** Ogg bitstream is in fact Vorbis data.
206 **
207 ** I handle the initial header first instead of just having the code
208 ** read all three Vorbis headers at once because reading the initial
209 ** header is an easy way to identify a Vorbis bitstream and it's
210 ** useful to see that functionality seperated out.
211 */
212 vorbis_info_init (&vdata->vinfo) ;
213 vorbis_comment_init (&vdata->vcomment) ;
214
215 if (vorbis_synthesis_headerin (&vdata->vinfo, &vdata->vcomment, &odata->opacket) < 0)
216 { /* Error case ; not a vorbis header. */
217 psf_log_printf (psf, "Found Vorbis in stream header, but vorbis_synthesis_headerin failed.\n") ;
218 return SFE_MALFORMED_FILE ;
219 } ;
220
221 /*
222 ** Common Ogg metadata fields?
223 ** TITLE, VERSION, ALBUM, TRACKNUMBER, ARTIST, PERFORMER, COPYRIGHT, LICENSE,
224 ** ORGANIZATION, DESCRIPTION, GENRE, DATE, LOCATION, CONTACT, ISRC,
225 */
226
227 if (log_data)
228 { int k ;
229
230 for (k = 0 ; k < ARRAY_LEN (vorbis_metatypes) ; k++)
231 { char *dd ;
232
233 dd = vorbis_comment_query (&vdata->vcomment, vorbis_metatypes [k].name, 0) ;
234 if (dd == NULL)
235 continue ;
236 psf_store_string (psf, vorbis_metatypes [k].id, dd) ;
237 } ;
238 } ;
239
240 /*
241 ** At this point, we're sure we're Vorbis. We've set up the logical (Ogg)
242 ** bitstream decoder. Get the comment and codebook headers and set up the
243 ** Vorbis decoder.
244 **
245 ** The next two packets in order are the comment and codebook headers.
246 ** They're likely large and may span multiple pages. Thus we reead
247 ** and submit data until we get our two pacakets, watching that no
248 ** pages are missing. If a page is missing, error out ; losing a
249 ** header page is the only place where missing data is fatal.
250 */
251
252 i = 0 ; /* Count of number of packets read */
253 while (i < 2)
254 { int result = ogg_sync_pageout (&odata->osync, &odata->opage) ;
255 if (result == 0)
256 { /* Need more data */
257 buffer = ogg_sync_buffer (&odata->osync, 4096) ;
258 bytes = psf_fread (buffer, 1, 4096, psf) ;
259
260 if (bytes == 0 && i < 2)
261 { psf_log_printf (psf, "End of file before finding all Vorbis headers!\n") ;
262 return SFE_MALFORMED_FILE ;
263 } ;
264 nn = ogg_sync_wrote (&odata->osync, bytes) ;
265 }
266 else if (result == 1)
267 { /*
268 ** Don't complain about missing or corrupt data yet. We'll
269 ** catch it at the packet output phase.
270 **
271 ** We can ignore any errors here as they'll also become apparent
272 ** at packetout.
273 */
274 nn = ogg_stream_pagein (&odata->ostream, &odata->opage) ;
275 while (i < 2)
276 { result = ogg_stream_packetout (&odata->ostream, &odata->opacket) ;
277 if (result == 0)
278 break ;
279 if (result < 0)
280 { /* Uh oh ; data at some point was corrupted or missing!
281 ** We can't tolerate that in a header. Die. */
282 psf_log_printf (psf, "Corrupt secondary header. Exiting.\n") ;
283 return SFE_MALFORMED_FILE ;
284 } ;
285
286 vorbis_synthesis_headerin (&vdata->vinfo, &vdata->vcomment, &odata->opacket) ;
287 i++ ;
288 } ;
289 } ;
290 } ;
291
292 if (log_data)
293 { int printed_metadata_msg = 0 ;
294 int k ;
295
296 psf_log_printf (psf, "Bitstream is %d channel, %D Hz\n", vdata->vinfo.channels, vdata->vinfo.rate) ;
297 psf_log_printf (psf, "Encoded by : %s\n", vdata->vcomment.vendor) ;
298
299 /* Throw the comments plus a few lines about the bitstream we're decoding. */
300 for (k = 0 ; k < ARRAY_LEN (vorbis_metatypes) ; k++)
301 { char *dd ;
302
303 dd = vorbis_comment_query (&vdata->vcomment, vorbis_metatypes [k].name, 0) ;
304 if (dd == NULL)
305 continue ;
306
307 if (printed_metadata_msg == 0)
308 { psf_log_printf (psf, "Metadata :\n") ;
309 printed_metadata_msg = 1 ;
310 } ;
311
312 psf_store_string (psf, vorbis_metatypes [k].id, dd) ;
313 psf_log_printf (psf, " %-10s : %s\n", vorbis_metatypes [k].name, dd) ;
314 } ;
315
316 psf_log_printf (psf, "End\n") ;
317 } ;
318
319 psf->sf.samplerate = vdata->vinfo.rate ;
320 psf->sf.channels = vdata->vinfo.channels ;
321 psf->sf.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS ;
322
323 /* OK, got and parsed all three headers. Initialize the Vorbis
324 ** packet->PCM decoder.
325 ** Central decode state. */
326 vorbis_synthesis_init (&vdata->vdsp, &vdata->vinfo) ;
327
328 /* Local state for most of the decode so multiple block decodes can
329 ** proceed in parallel. We could init multiple vorbis_block structures
330 ** for vd here. */
331 vorbis_block_init (&vdata->vdsp, &vdata->vblock) ;
332
333 vdata->loc = 0 ;
334
335 return 0 ;
336 } /* vorbis_read_header */
337
338 static int
339 vorbis_write_header (SF_PRIVATE *psf, int UNUSED (calc_length))
340 {
341 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
342 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
343 int k, ret ;
344
345 vorbis_info_init (&vdata->vinfo) ;
346
347 /* The style of encoding should be selectable here, VBR quality mode. */
348 ret = vorbis_encode_init_vbr (&vdata->vinfo, psf->sf.channels, psf->sf.samplerate, vdata->quality) ;
349
350 #if 0
351 ret = vorbis_encode_init (&vdata->vinfo, psf->sf.channels, psf->sf.samplerate, -1, 128000, -1) ; /* average bitrate mode */
352 ret = ( vorbis_encode_setup_managed (&vdata->vinfo, psf->sf.channels,
353 psf->sf.samplerate, -1, 128000, -1) ||
354 vorbis_encode_ctl (&vdata->vinfo, OV_ECTL_RATEMANAGE_AVG, NULL) ||
355 vorbis_encode_setup_init (&vdata->vinfo)) ;
356 #endif
357 if (ret)
358 return SFE_BAD_OPEN_FORMAT ;
359
360 vdata->loc = 0 ;
361
362 /* add a comment */
363 vorbis_comment_init (&vdata->vcomment) ;
364
365 vorbis_comment_add_tag (&vdata->vcomment, "ENCODER", "libsndfile") ;
366 for (k = 0 ; k < SF_MAX_STRINGS ; k++)
367 { const char * name ;
368
369 if (psf->strings [k].type == 0)
370 break ;
371
372 switch (psf->strings [k].type)
373 { case SF_STR_TITLE : name = "TITLE" ; break ;
374 case SF_STR_COPYRIGHT : name = "COPYRIGHT" ; break ;
375 case SF_STR_SOFTWARE : name = "SOFTWARE" ; break ;
376 case SF_STR_ARTIST : name = "ARTIST" ; break ;
377 case SF_STR_COMMENT : name = "COMMENT" ; break ;
378 case SF_STR_DATE : name = "DATE" ; break ;
379 case SF_STR_ALBUM : name = "ALBUM" ; break ;
380 case SF_STR_LICENSE : name = "LICENSE" ; break ;
381 default : continue ;
382 } ;
383
384 vorbis_comment_add_tag (&vdata->vcomment, name, psf->strings [k].str) ;
385 } ;
386
387 /* set up the analysis state and auxiliary encoding storage */
388 vorbis_analysis_init (&vdata->vdsp, &vdata->vinfo) ;
389 vorbis_block_init (&vdata->vdsp, &vdata->vblock) ;
390
391 /*
392 ** Set up our packet->stream encoder.
393 ** Pick a random serial number ; that way we can more likely build
394 ** chained streams just by concatenation.
395 */
396
397 ogg_stream_init (&odata->ostream, psf_rand_int32 ()) ;
398
399 /* Vorbis streams begin with three headers ; the initial header (with
400 most of the codec setup parameters) which is mandated by the Ogg
401 bitstream spec. The second header holds any comment fields. The
402 third header holds the bitstream codebook. We merely need to
403 make the headers, then pass them to libvorbis one at a time ;
404 libvorbis handles the additional Ogg bitstream constraints */
405
406 { ogg_packet header ;
407 ogg_packet header_comm ;
408 ogg_packet header_code ;
409 int result ;
410
411 vorbis_analysis_headerout (&vdata->vdsp, &vdata->vcomment, &header, &header_comm, &header_code) ;
412 ogg_stream_packetin (&odata->ostream, &header) ; /* automatically placed in its own page */
413 ogg_stream_packetin (&odata->ostream, &header_comm) ;
414 ogg_stream_packetin (&odata->ostream, &header_code) ;
415
416 /* This ensures the actual
417 * audio data will start on a new page, as per spec
418 */
419 while ((result = ogg_stream_flush (&odata->ostream, &odata->opage)) != 0)
420 { psf_fwrite (odata->opage.header, 1, odata->opage.header_len, psf) ;
421 psf_fwrite (odata->opage.body, 1, odata->opage.body_len, psf) ;
422 } ;
423 }
424
425 return 0 ;
426 } /* vorbis_write_header */
427
428 static int
429 vorbis_close (SF_PRIVATE *psf)
430 { OGG_PRIVATE* odata = psf->container_data ;
431 VORBIS_PRIVATE *vdata = psf->codec_data ;
432
433 if (odata == NULL || vdata == NULL)
434 return 0 ;
435
436 /* Clean up this logical bitstream ; before exit we shuld see if we're
437 ** followed by another [chained]. */
438
439 if (psf->file.mode == SFM_WRITE)
440 {
441 if (psf->write_current <= 0)
442 vorbis_write_header (psf, 0) ;
443
444 vorbis_analysis_wrote (&vdata->vdsp, 0) ;
445 while (vorbis_analysis_blockout (&vdata->vdsp, &vdata->vblock) == 1)
446 {
447
448 /* analysis, assume we want to use bitrate management */
449 vorbis_analysis (&vdata->vblock, NULL) ;
450 vorbis_bitrate_addblock (&vdata->vblock) ;
451
452 while (vorbis_bitrate_flushpacket (&vdata->vdsp, &odata->opacket))
453 { /* weld the packet into the bitstream */
454 ogg_stream_packetin (&odata->ostream, &odata->opacket) ;
455
456 /* write out pages (if any) */
457 while (!odata->eos)
458 { int result = ogg_stream_pageout (&odata->ostream, &odata->opage) ;
459 if (result == 0) break ;
460 psf_fwrite (odata->opage.header, 1, odata->opage.header_len, psf) ;
461 psf_fwrite (odata->opage.body, 1, odata->opage.body_len, psf) ;
462
463 /* this could be set above, but for illustrative purposes, I do
464 it here (to show that vorbis does know where the stream ends) */
465
466 if (ogg_page_eos (&odata->opage)) odata->eos = 1 ;
467 }
468 }
469 }
470 }
471
472 /* ogg_page and ogg_packet structs always point to storage in
473 libvorbis. They are never freed or manipulated directly */
474
475 vorbis_block_clear (&vdata->vblock) ;
476 vorbis_dsp_clear (&vdata->vdsp) ;
477 vorbis_comment_clear (&vdata->vcomment) ;
478 vorbis_info_clear (&vdata->vinfo) ;
479
480 return 0 ;
481 } /* vorbis_close */
482
483 int
484 ogg_vorbis_open (SF_PRIVATE *psf)
485 { OGG_PRIVATE* odata = psf->container_data ;
486 VORBIS_PRIVATE* vdata = calloc (1, sizeof (VORBIS_PRIVATE)) ;
487 int error = 0 ;
488
489 if (odata == NULL)
490 { psf_log_printf (psf, "%s : odata is NULL???\n", __func__) ;
491 return SFE_INTERNAL ;
492 } ;
493
494 psf->codec_data = vdata ;
495
496 if (psf->file.mode == SFM_RDWR)
497 return SFE_BAD_MODE_RW ;
498
499 psf_log_printf (psf, "Vorbis library version : %s\n", vorbis_version_string ()) ;
500
501 if (psf->file.mode == SFM_READ)
502 { /* Call this here so it only gets called once, so no memory is leaked. */
503 ogg_sync_init (&odata->osync) ;
504
505 if ((error = vorbis_read_header (psf, 1)))
506 return error ;
507
508 psf->read_short = vorbis_read_s ;
509 psf->read_int = vorbis_read_i ;
510 psf->read_float = vorbis_read_f ;
511 psf->read_double = vorbis_read_d ;
512 psf->sf.frames = vorbis_length (psf) ;
513 } ;
514
515 psf->codec_close = vorbis_close ;
516 if (psf->file.mode == SFM_WRITE)
517 {
518 /* Set the default vorbis quality here. */
519 vdata->quality = 0.4 ;
520
521 psf->write_header = vorbis_write_header ;
522 psf->write_short = vorbis_write_s ;
523 psf->write_int = vorbis_write_i ;
524 psf->write_float = vorbis_write_f ;
525 psf->write_double = vorbis_write_d ;
526
527 psf->sf.frames = SF_COUNT_MAX ; /* Unknown really */
528 psf->str_flags = SF_STR_ALLOW_START ;
529 } ;
530
531 psf->bytewidth = 1 ;
532 psf->blockwidth = psf->bytewidth * psf->sf.channels ;
533
534 psf->seek = vorbis_seek ;
535 psf->command = vorbis_command ;
536
537 /* FIXME, FIXME, FIXME : Hack these here for now and correct later. */
538 psf->sf.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS ;
539 psf->sf.sections = 1 ;
540
541 psf->datalength = 1 ;
542 psf->dataoffset = 0 ;
543 /* End FIXME. */
544
545 return error ;
546 } /* ogg_vorbis_open */
547
548 static int
549 vorbis_command (SF_PRIVATE *psf, int command, void * data, int datasize)
550 { VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
551
552 switch (command)
553 { case SFC_SET_VBR_ENCODING_QUALITY :
554 if (data == NULL || datasize != sizeof (double))
555 return SF_FALSE ;
556
557 if (psf->have_written)
558 return SF_FALSE ;
559
560 vdata->quality = *((double *) data) ;
561
562 /* Clip range. */
563 vdata->quality = SF_MAX (0.0, SF_MIN (1.0, vdata->quality)) ;
564
565 psf_log_printf (psf, "%s : Setting SFC_SET_VBR_ENCODING_QUALITY to %f.\n", __func__, vdata->quality) ;
566 return SF_TRUE ;
567
568 default :
569 return SF_FALSE ;
570 } ;
571
572 return SF_FALSE ;
573 } /* vorbis_command */
574
575 static int
576 vorbis_rnull (int samples, void *UNUSED (vptr), int UNUSED (off) , int channels, float **UNUSED (pcm))
577 {
578 return samples * channels ;
579 } /* vorbis_rnull */
580
581 static int
582 vorbis_rshort (int samples, void *vptr, int off, int channels, float **pcm)
583 {
584 short *ptr = (short*) vptr + off ;
585 int i = 0, j, n ;
586 for (j = 0 ; j < samples ; j++)
587 for (n = 0 ; n < channels ; n++)
588 ptr [i++] = lrintf (pcm [n][j] * 32767.0f) ;
589 return i ;
590 } /* vorbis_rshort */
591
592 static int
593 vorbis_rint (int samples, void *vptr, int off, int channels, float **pcm)
594 {
595 int *ptr = (int*) vptr + off ;
596 int i = 0, j, n ;
597
598 for (j = 0 ; j < samples ; j++)
599 for (n = 0 ; n < channels ; n++)
600 ptr [i++] = lrintf (pcm [n][j] * 2147483647.0f) ;
601 return i ;
602 } /* vorbis_rint */
603
604 static int
605 vorbis_rfloat (int samples, void *vptr, int off, int channels, float **pcm)
606 {
607 float *ptr = (float*) vptr + off ;
608 int i = 0, j, n ;
609 for (j = 0 ; j < samples ; j++)
610 for (n = 0 ; n < channels ; n++)
611 ptr [i++] = pcm [n][j] ;
612 return i ;
613 } /* vorbis_rfloat */
614
615 static int
616 vorbis_rdouble (int samples, void *vptr, int off, int channels, float **pcm)
617 {
618 double *ptr = (double*) vptr + off ;
619 int i = 0, j, n ;
620 for (j = 0 ; j < samples ; j++)
621 for (n = 0 ; n < channels ; n++)
622 ptr [i++] = pcm [n][j] ;
623 return i ;
624 } /* vorbis_rdouble */
625
626
627 static sf_count_t
628 vorbis_read_sample (SF_PRIVATE *psf, void *ptr, sf_count_t lens, convert_func *transfn)
629 {
630 VORBIS_PRIVATE *vdata = psf->codec_data ;
631 OGG_PRIVATE *odata = psf->container_data ;
632 int len, samples, i = 0 ;
633 float **pcm ;
634
635 len = lens / psf->sf.channels ;
636
637 while ((samples = vorbis_synthesis_pcmout (&vdata->vdsp, &pcm)) > 0)
638 { if (samples > len) samples = len ;
639 i += transfn (samples, ptr, i, psf->sf.channels, pcm) ;
640 len -= samples ;
641 /* tell libvorbis how many samples we actually consumed */
642 vorbis_synthesis_read (&vdata->vdsp, samples) ;
643 vdata->loc += samples ;
644 if (len == 0)
645 return i ; /* Is this necessary */
646 }
647 goto start0 ; /* Jump into the nasty nest */
648 while (len > 0 && !odata->eos)
649 {
650 while (len > 0 && !odata->eos)
651 { int result = ogg_sync_pageout (&odata->osync, &odata->opage) ;
652 if (result == 0) break ; /* need more data */
653 if (result < 0)
654 { /* missing or corrupt data at this page position */
655 psf_log_printf (psf, "Corrupt or missing data in bitstream ; continuing...\n") ;
656 }
657 else
658 { /* can safely ignore errors at this point */
659 ogg_stream_pagein (&odata->ostream, &odata->opage) ;
660 start0:
661 while (1)
662 { result = ogg_stream_packetout (&odata->ostream, &odata->opacket) ;
663 if (result == 0)
664 break ; /* need more data */
665 if (result < 0)
666 { /* missing or corrupt data at this page position */
667 /* no reason to complain ; already complained above */
668 }
669 else
670 { /* we have a packet. Decode it */
671 if (vorbis_synthesis (&vdata->vblock, &odata->opacket) == 0) /* test for success! */
672 vorbis_synthesis_blockin (&vdata->vdsp, &vdata->vblock) ;
673 /*
674 **pcm is a multichannel float vector. In stereo, for
675 example, pcm [0] is left, and pcm [1] is right. samples is
676 the size of each channel. Convert the float values
677 (-1.<=range<=1.) to whatever PCM format and write it out */
678
679 while ((samples = vorbis_synthesis_pcmout (&vdata->vdsp, &pcm)) > 0)
680 { if (samples>len) samples = len ;
681 i += transfn (samples, ptr, i, psf->sf.channels, pcm) ;
682 len -= samples ;
683 /* tell libvorbis how many samples we actually consumed */
684 vorbis_synthesis_read (&vdata->vdsp, samples) ;
685 vdata->loc += samples ;
686 if (len == 0)
687 return i ; /* Is this necessary */
688 } ;
689 }
690 }
691 if (ogg_page_eos (&odata->opage)) odata->eos = 1 ;
692 }
693 }
694 if (!odata->eos)
695 { char *buffer ;
696 int bytes ;
697 buffer = ogg_sync_buffer (&odata->osync, 4096) ;
698 bytes = psf_fread (buffer, 1, 4096, psf) ;
699 ogg_sync_wrote (&odata->osync, bytes) ;
700 if (bytes == 0) odata->eos = 1 ;
701 }
702 }
703 return i ;
704 } /* vorbis_read_sample */
705
706 static sf_count_t
707 vorbis_read_s (SF_PRIVATE *psf, short *ptr, sf_count_t lens)
708 { return vorbis_read_sample (psf, (void*) ptr, lens, vorbis_rshort) ;
709 } /* vorbis_read_s */
710
711 static sf_count_t
712 vorbis_read_i (SF_PRIVATE *psf, int *ptr, sf_count_t lens)
713 { return vorbis_read_sample (psf, (void*) ptr, lens, vorbis_rint) ;
714 } /* vorbis_read_i */
715
716 static sf_count_t
717 vorbis_read_f (SF_PRIVATE *psf, float *ptr, sf_count_t lens)
718 { return vorbis_read_sample (psf, (void*) ptr, lens, vorbis_rfloat) ;
719 } /* vorbis_read_f */
720
721 static sf_count_t
722 vorbis_read_d (SF_PRIVATE *psf, double *ptr, sf_count_t lens)
723 { return vorbis_read_sample (psf, (void*) ptr, lens, vorbis_rdouble) ;
724 } /* vorbis_read_d */
725
726 /*==============================================================================
727 */
728
729 static void
730 vorbis_write_samples (SF_PRIVATE *psf, OGG_PRIVATE *odata, VORBIS_PRIVATE *vdata, int in_frames)
731 {
732 vorbis_analysis_wrote (&vdata->vdsp, in_frames) ;
733
734 /*
735 ** Vorbis does some data preanalysis, then divvies up blocks for
736 ** more involved (potentially parallel) processing. Get a single
737 ** block for encoding now.
738 */
739 while (vorbis_analysis_blockout (&vdata->vdsp, &vdata->vblock) == 1)
740 {
741 /* analysis, assume we want to use bitrate management */
742 vorbis_analysis (&vdata->vblock, NULL) ;
743 vorbis_bitrate_addblock (&vdata->vblock) ;
744
745 while (vorbis_bitrate_flushpacket (&vdata->vdsp, &odata->opacket))
746 {
747 /* weld the packet into the bitstream */
748 ogg_stream_packetin (&odata->ostream, &odata->opacket) ;
749
750 /* write out pages (if any) */
751 while (!odata->eos)
752 { int result = ogg_stream_pageout (&odata->ostream, &odata->opage) ;
753 if (result == 0)
754 break ;
755 psf_fwrite (odata->opage.header, 1, odata->opage.header_len, psf) ;
756 psf_fwrite (odata->opage.body, 1, odata->opage.body_len, psf) ;
757
758 /* This could be set above, but for illustrative purposes, I do
759 ** it here (to show that vorbis does know where the stream ends) */
760 if (ogg_page_eos (&odata->opage))
761 odata->eos = 1 ;
762 } ;
763 } ;
764 } ;
765
766 vdata->loc += in_frames ;
767 } /* vorbis_write_data */
768
769
770 static sf_count_t
771 vorbis_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t lens)
772 {
773 int i, m, j = 0 ;
774 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
775 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
776 int in_frames = lens / psf->sf.channels ;
777 float **buffer = vorbis_analysis_buffer (&vdata->vdsp, in_frames) ;
778 for (i = 0 ; i < in_frames ; i++)
779 for (m = 0 ; m < psf->sf.channels ; m++)
780 buffer [m][i] = (float) (ptr [j++]) / 32767.0f ;
781
782 vorbis_write_samples (psf, odata, vdata, in_frames) ;
783
784 return lens ;
785 } /* vorbis_write_s */
786
787 static sf_count_t
788 vorbis_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t lens)
789 { int i, m, j = 0 ;
790 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
791 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
792 int in_frames = lens / psf->sf.channels ;
793 float **buffer = vorbis_analysis_buffer (&vdata->vdsp, in_frames) ;
794 for (i = 0 ; i < in_frames ; i++)
795 for (m = 0 ; m < psf->sf.channels ; m++)
796 buffer [m][i] = (float) (ptr [j++]) / 2147483647.0f ;
797
798 vorbis_write_samples (psf, odata, vdata, in_frames) ;
799
800 return lens ;
801 } /* vorbis_write_i */
802
803 static sf_count_t
804 vorbis_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t lens)
805 { int i, m, j = 0 ;
806 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
807 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
808 int in_frames = lens / psf->sf.channels ;
809 float **buffer = vorbis_analysis_buffer (&vdata->vdsp, in_frames) ;
810 for (i = 0 ; i < in_frames ; i++)
811 for (m = 0 ; m < psf->sf.channels ; m++)
812 buffer [m][i] = ptr [j++] ;
813
814 vorbis_write_samples (psf, odata, vdata, in_frames) ;
815
816 return lens ;
817 } /* vorbis_write_f */
818
819 static sf_count_t
820 vorbis_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t lens)
821 { int i, m, j = 0 ;
822 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
823 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
824 int in_frames = lens / psf->sf.channels ;
825 float **buffer = vorbis_analysis_buffer (&vdata->vdsp, in_frames) ;
826 for (i = 0 ; i < in_frames ; i++)
827 for (m = 0 ; m < psf->sf.channels ; m++)
828 buffer [m][i] = (float) ptr [j++] ;
829
830 vorbis_write_samples (psf, odata, vdata, in_frames) ;
831
832 return lens ;
833 } /* vorbis_write_d */
834
835 static sf_count_t
836 vorbis_seek (SF_PRIVATE *psf, int UNUSED (mode), sf_count_t offset)
837 {
838 OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
839 VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ;
840
841 if (odata == NULL || vdata == NULL)
842 return 0 ;
843
844 if (offset < 0)
845 { psf->error = SFE_BAD_SEEK ;
846 return ((sf_count_t) -1) ;
847 } ;
848
849 if (psf->file.mode == SFM_READ)
850 { sf_count_t target = offset - vdata->loc ;
851
852 if (target < 0)
853 { /* 12 to allow for OggS bit */
854 psf_fseek (psf, 12, SEEK_SET) ;
855 vorbis_read_header (psf, 0) ; /* Reset state */
856 target = offset ;
857 } ;
858
859 while (target > 0)
860 { sf_count_t m = target > 4096 ? 4096 : target ;
861
862 /*
863 ** Need to multiply by channels here because the seek is done in
864 ** terms of frames and the read function is done in terms of
865 ** samples.
866 */
867 vorbis_read_sample (psf, (void *) NULL, m * psf->sf.channels, vorbis_rnull) ;
868
869 target -= m ;
870 } ;
871
872 return vdata->loc ;
873 } ;
874
875 return 0 ;
876 } /* vorbis_seek */
877
878 /*==============================================================================
879 ** Most of the following code was snipped from Mike Smith's ogginfo utility
880 ** which is part of vorbis-tools.
881 ** Vorbis tools is released under the GPL but Mike has kindly allowed the
882 ** following to be relicensed as LGPL for libsndfile.
883 */
884
885 typedef struct
886 {
887 int isillegal ;
888 int shownillegal ;
889 int isnew ;
890 int end ;
891
892 uint32_t serial ; /* must be 32 bit unsigned */
893 ogg_stream_state ostream ;
894
895 vorbis_info vinfo ;
896 vorbis_comment vcomment ;
897 sf_count_t lastgranulepos ;
898 int doneheaders ;
899 } stream_processor ;
900
901 typedef struct
902 {
903 stream_processor *streams ;
904 int allocated ;
905 int used ;
906 int in_headers ;
907 } stream_set ;
908
909 static stream_set *
910 create_stream_set (void)
911 { stream_set *set = calloc (1, sizeof (stream_set)) ;
912
913 set->streams = calloc (5, sizeof (stream_processor)) ;
914 set->allocated = 5 ;
915 set->used = 0 ;
916
917 return set ;
918 } /* create_stream_set */
919
920 static void
921 vorbis_end (stream_processor *stream, sf_count_t * len)
922 { *len += stream->lastgranulepos ;
923 vorbis_comment_clear (&stream->vcomment) ;
924 vorbis_info_clear (&stream->vinfo) ;
925 } /* vorbis_end */
926
927 static void
928 free_stream_set (stream_set *set, sf_count_t * len)
929 { int i ;
930
931 for (i = 0 ; i < set->used ; i++)
932 { if (!set->streams [i].end)
933 vorbis_end (&set->streams [i], len) ;
934 ogg_stream_clear (&set->streams [i].ostream) ;
935 } ;
936
937 free (set->streams) ;
938 free (set) ;
939 } /* free_stream_set */
940
941 static int
942 streams_open (stream_set *set)
943 { int i, res = 0 ;
944
945 for (i = 0 ; i < set->used ; i++)
946 if (!set->streams [i].end)
947 res ++ ;
948 return res ;
949 } /* streams_open */
950
951 static stream_processor *
952 find_stream_processor (stream_set *set, ogg_page *page)
953 { uint32_t serial = ogg_page_serialno (page) ;
954 int i, invalid = 0 ;
955
956 stream_processor *stream ;
957
958 for (i = 0 ; i < set->used ; i++)
959 {
960 if (serial == set->streams [i].serial)
961 { /* We have a match! */
962 stream = & (set->streams [i]) ;
963
964 set->in_headers = 0 ;
965 /* if we have detected EOS, then this can't occur here. */
966 if (stream->end)
967 { stream->isillegal = 1 ;
968 return stream ;
969 }
970
971 stream->isnew = 0 ;
972 stream->end = ogg_page_eos (page) ;
973 stream->serial = serial ;
974 return stream ;
975 } ;
976 } ;
977
978 /* If there are streams open, and we've reached the end of the
979 ** headers, then we can't be starting a new stream.
980 ** XXX: might this sometimes catch ok streams if EOS flag is missing,
981 ** but the stream is otherwise ok?
982 */
983 if (streams_open (set) && !set->in_headers)
984 invalid = 1 ;
985
986 set->in_headers = 1 ;
987
988 if (set->allocated < set->used)
989 stream = &set->streams [set->used] ;
990 else
991 { set->allocated += 5 ;
992 set->streams = realloc (set->streams, sizeof (stream_processor) * set->allocated) ;
993 stream = &set->streams [set->used] ;
994 } ;
995
996 set->used++ ;
997
998 stream->isnew = 1 ;
999 stream->isillegal = invalid ;
1000
1001 {
1002 int res ;
1003 ogg_packet packet ;
1004
1005 /* We end up processing the header page twice, but that's ok. */
1006 ogg_stream_init (&stream->ostream, serial) ;
1007 ogg_stream_pagein (&stream->ostream, page) ;
1008 res = ogg_stream_packetout (&stream->ostream, &packet) ;
1009 if (res <= 0)
1010 return NULL ;
1011 else if (packet.bytes >= 7 && memcmp (packet.packet, "\x01vorbis", 7) == 0)
1012 {
1013 stream->lastgranulepos = 0 ;
1014 vorbis_comment_init (&stream->vcomment) ;
1015 vorbis_info_init (&stream->vinfo) ;
1016 } ;
1017
1018 res = ogg_stream_packetout (&stream->ostream, &packet) ;
1019
1020 /* re-init, ready for processing */
1021 ogg_stream_clear (&stream->ostream) ;
1022 ogg_stream_init (&stream->ostream, serial) ;
1023 }
1024
1025 stream->end = ogg_page_eos (page) ;
1026 stream->serial = serial ;
1027
1028 return stream ;
1029 } /* find_stream_processor */
1030
1031 static int
1032 vorbis_length_get_next_page (SF_PRIVATE *psf, ogg_sync_state * osync, ogg_page *page)
1033 { static const int CHUNK_SIZE = 4500 ;
1034
1035 while (ogg_sync_pageout (osync, page) <= 0)
1036 { char * buffer = ogg_sync_buffer (osync, CHUNK_SIZE) ;
1037 int bytes = psf_fread (buffer, 1, 4096, psf) ;
1038
1039 if (bytes <= 0)
1040 { ogg_sync_wrote (osync, 0) ;
1041 return 0 ;
1042 } ;
1043
1044 ogg_sync_wrote (osync, bytes) ;
1045 } ;
1046
1047 return 1 ;
1048 } /* vorbis_length_get_next_page */
1049
1050 static sf_count_t
1051 vorbis_length_aux (SF_PRIVATE * psf)
1052 {
1053 ogg_sync_state osync ;
1054 ogg_page page ;
1055 sf_count_t len = 0 ;
1056 stream_set *processors ;
1057
1058 processors = create_stream_set () ;
1059 if (processors == NULL)
1060 return 0 ; // out of memory?
1061
1062 ogg_sync_init (&osync) ;
1063
1064 while (vorbis_length_get_next_page (psf, &osync, &page))
1065 {
1066 stream_processor *p = find_stream_processor (processors, &page) ;
1067
1068 if (!p)
1069 { len = 0 ;
1070 break ;
1071 } ;
1072
1073 if (p->isillegal && !p->shownillegal)
1074 {
1075 p->shownillegal = 1 ;
1076 /* If it's a new stream, we want to continue processing this page
1077 ** anyway to suppress additional spurious errors
1078 */
1079 if (!p->isnew) continue ;
1080 } ;
1081
1082 if (!p->isillegal)
1083 { ogg_packet packet ;
1084 int header = 0 ;
1085
1086 ogg_stream_pagein (&p->ostream, &page) ;
1087 if (p->doneheaders < 3)
1088 header = 1 ;
1089
1090 while (ogg_stream_packetout (&p->ostream, &packet) > 0)
1091 {
1092 if (p->doneheaders < 3)
1093 { if (vorbis_synthesis_headerin (&p->vinfo, &p->vcomment, &packet) < 0)
1094 continue ;
1095 p->doneheaders ++ ;
1096 } ;
1097 } ;
1098 if (!header)
1099 { sf_count_t gp = ogg_page_granulepos (&page) ;
1100 if (gp > 0) p->lastgranulepos = gp ;
1101 } ;
1102 if (p->end)
1103 { vorbis_end (p, &len) ;
1104 p->isillegal = 1 ;
1105 } ;
1106 } ;
1107 } ;
1108
1109 ogg_sync_clear (&osync) ;
1110 free_stream_set (processors, &len) ;
1111
1112 return len ;
1113 } /* vorbis_length_aux */
1114
1115 static sf_count_t
1116 vorbis_length (SF_PRIVATE *psf)
1117 { sf_count_t length ;
1118 int error ;
1119
1120 if (psf->sf.seekable == 0)
1121 return SF_COUNT_MAX ;
1122
1123 psf_fseek (psf, 0, SEEK_SET) ;
1124 length = vorbis_length_aux (psf) ;
1125
1126 psf_fseek (psf, 12, SEEK_SET) ;
1127 if ((error = vorbis_read_header (psf, 0)) != 0)
1128 psf->error = error ;
1129
1130 return length ;
1131 } /* vorbis_length */
1132
1133 #else /* HAVE_EXTERNAL_LIBS */
1134
1135 int
1136 ogg_vorbis_open (SF_PRIVATE *psf)
1137 {
1138 psf_log_printf (psf, "This version of libsndfile was compiled without Ogg/Vorbis support.\n") ;
1139 return SFE_UNIMPLEMENTED ;
1140 } /* ogg_vorbis_open */
1141
1142 #endif