• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ** Copyright (C) 2013-2020 Erik de Castro Lopo <erikd@mega-nerd.com>
3 ** Copyright (C) 2018 Arthur Taylor <art@ified.ca>
4 **
5 ** This program is free software ; you can redistribute it and/or modify
6 ** it under the terms of the GNU Lesser General Public License as published by
7 ** the Free Software Foundation ; either version 2.1 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY ; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
13 ** GNU Lesser General Public License for more details.
14 **
15 ** You should have received a copy of the GNU Lesser General Public License
16 ** along with this program ; if not, write to the Free Software
17 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 */
19 
20 /*
21 ** This file contains code based on OpusFile and Opus-Tools, both by
22 ** Xiph.Org. COPYING from each is identical and is as follows:
23 **
24 ** Copyright (c) 1994-2013 Xiph.Org Foundation and contributors
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 /*
55 ** TODO:
56 **  - Channel mapping modification / reporting
57 **	 - connect psf->channel_map and Opus channel mapping somehow?
58 **  - Gain parameters and their mappings
59 */
60 
61 /*
62 ** Opus Sample, Frame, and Samples/Channel Terminology
63 **
64 ** libsndfile refers to one PCM value as a 'sample,' and a group of samples of
65 ** the same sample time, one for each channel, as a 'frame.' This differs from
66 ** Opus, which has no corresponding name for sample, and refers to a group of
67 ** PCM values, one per channel (aka libsndfile frames) as 'samples.'
68 ** Further, Opus has an object called a 'frame' that is made up of multiple
69 ** Opus-samples.
70 ** All this means that one has to be careful with what is meant by each term.
71 ** In an attempt to avoid ambiguity, this file adopts the following terms:
72 **  - Samples shall refer to discrete PCM values, regardless of any channel
73 **	considerations. This is the same as what libsndfile calls samples.
74 **  - Samples/channel shall refer to groups of samples, one for each channel.
75 **	This is what Opus calles samples, and what libsndfile calles frames. It
76 **	has the advantage that its name is also the formula to calculate it.
77 **
78 **
79 ** Opus vs OggOpus
80 **
81 ** In this file a distinction is made between Opus and OggOpus. Opus refers to
82 ** the codec alone, support for which is by libopus. OggOpus refers to an Opus
83 ** payload encapsulated in an Ogg stream. This is also know as an "Opus file."
84 ** The OggOpus spec includes information on header and granule position
85 ** interpretation, which is outside of the scope of the Opus spec. As such, an
86 ** attempt here is made to refer to either Opus or OggOpus depending on which
87 ** spec is being referenced. See https://wiki.xiph.org/OggOpus
88 **
89 **
90 ** Opus Sample Rates
91 **
92 ** Opus only supports a fixed number of sample rates: 48kHz, 24kHz, 16kHz,
93 ** 12kHz, 8kHz. Audio may be decoded or encoded at any of these rates,
94 ** independent of the rate it was encoded at or to be decoded at respectively.
95 ** Other sample rates must be converted to one of these rates.
96 **
97 ** As 44.1kHz (CD sample rate) and 22.5kHz are popular sample rates, and to
98 ** support any other sample rate there may be, the Opus header includes a field
99 ** to save the input (original) sample rate before converting it to a supported
100 ** one. Implementations are recommended by the Opus spec to do a sample rate
101 ** conversion at encode, but decode at 48kHz if outputting to hardware, or do
102 ** the reverse sample rate conversion if outputting to file.
103 **
104 ** Heretofore libsndfile does not contain a sample rate converter, so doing the
105 ** sample rate conversion is not supported. Instead audio must be provided by
106 ** the user at a supported rate. However, the input sample rate field can be
107 ** set and retrieved by the user using sf_command(). At decode we choose to
108 ** decode at the lowest valid rate that is greater than or equal to the input
109 ** sample rate.
110 **
111 **
112 ** OggOpus Granule Positions
113 **
114 ** Ogg streams include a strictly increasing granule position value. The
115 ** interpretation of this value is dependent on the payload type. For Opus
116 ** streams the granule position is the count of samples in the stream when
117 ** encoding/decoding at 48kHz. Note that the actual position of the output
118 ** sample relative to the granule position is offset by the preskip amount.
119 ** That is, if a packet ends with a granule position of x, the last sample
120 ** output when decoding is actually sample (x - preskip).
121 **
122 ** Further, to allow for clipping off of the front of a stream without
123 ** rewriting all following granule positions, an Opus stream granule position
124 ** may be offset by a constant amount. This amount is evident by comparing the
125 ** granule position of the first page of an Opus stream on which an audio
126 ** packet completes is greater than the sum of the samples of all audio
127 ** packets completed on the page. Only the first such page is allows to have an
128 ** 'excessive' granule position, and only if it is not also the last page of
129 ** the stream (e_o_s bit is not set.)
130 **
131 ** The granule position is an unsigned 64-bit integer, with the special value
132 ** of UINT64_MAX/-1 being treated as invalid. However, as not all platforms
133 ** support unsigned 64-bit integers, libOgg uses signed 64-bit integers for the
134 ** granule position.
135 **
136 ** Remembering that signed integer overflow/underflow is explicitly undefined
137 ** in C, and as we already assume support for unsigned 64-bit integers, the
138 ** easiest way to deal with this problem is to modify granule positions as
139 ** unsigned integers.
140 */
141 
142 
143 #include "sfconfig.h"
144 
145 #include <stdio.h>
146 #include <fcntl.h>
147 #include <string.h>
148 #include <ctype.h>
149 #include <time.h>
150 #include <math.h>
151 
152 #if HAVE_UNISTD_H
153 #include <unistd.h>
154 #else
155 #include "sf_unistd.h"
156 #endif
157 
158 #include "sndfile.h"
159 #include "sfendian.h"
160 #include "common.h"
161 
162 #if HAVE_EXTERNAL_XIPH_LIBS
163 
164 #include <ogg/ogg.h>
165 #include <opus/opus.h>
166 #include <opus/opus_multistream.h>
167 
168 #include "ogg.h"
169 #include "ogg_vcomment.h"
170 
171 #define OGG_OPUS_COMMENT_PAD (512) /* Same as oggenc default */
172 
173 /*
174 ** Opus packets can be any multiple of 2.5ms (at 48kHz). We use the recommended
175 ** default for non-realtime of 20ms. While longer packets reduce the overhead
176 ** data somewhat, it also decreases the quality.
177 */
178 #define OGG_OPUS_ENCODE_PACKET_LEN(samplerate) ((20 * (samplerate)) / 1000)
179 
180 /*
181 ** How long does it take for a decoder to converge (avoiding flush on seek.
182 */
183 #define OGG_OPUS_PREROLL (80 * 48) /* 80 milliseconds */
184 
185 typedef struct
186 {	uint8_t version ;
187 
188 	/* Number of channels, 1...255 */
189 	uint8_t channels ;
190 
191 	/* Encoder latency, the amount to skip before valid data comes out. */
192 	uint16_t preskip ;
193 
194 	/* The sample rate of a the encoded source, as it may have been converted. */
195 	int32_t input_samplerate ;
196 
197 	/* 'baked-in' gain to apply, dB S7.8 format. Should be zero when possible. */
198 	int16_t gain ;
199 
200 	/* Channel mapping type. See OggOpus spec */
201 	uint8_t channel_mapping ;
202 
203 	/* The rest is only used if channel_mapping != 0 */
204 	/* How many streams are there? */
205 	uint8_t nb_streams ;
206 
207 	/* How man of those streams are coupled? (aka stereo) */
208 	uint8_t nb_coupled ;
209 
210 	/* Mapping of opus streams to output channels */
211 	uint8_t stream_map [255] ;
212 } OpusHeader ;
213 
214 typedef struct
215 {	uint32_t serialno ;
216 	OpusHeader header ;
217 
218 	/* Granule position before the current packet */
219 	uint64_t pkt_pos ;
220 
221 	/* Granule position at the end of the current page (encode: last completed) */
222 	uint64_t pg_pos ;
223 
224 	/* integer coefficient of (current sample rate) / 48000Hz */
225 	int sr_factor ;
226 
227 	/* Current position in buffer expressed as samples/channel */
228 	int loc ;
229 
230 	/* Current data fill (decode) or target (encode) of buffer expressed in samples/channel */
231 	int len ;
232 
233 	/* Size of the buffer storage, in sizeof (float) * channels */
234 	int buffersize ;
235 
236 	/* Samples, either decoded from a packet, or assembling for encode. */
237 	float *buffer ;
238 
239 	union {
240 		/* decode only members */
241 		struct {
242 			OpusMSDecoder *state ;
243 			uint64_t gp_start ;
244 			uint64_t gp_end ;
245 			sf_count_t last_offset ;
246 		} decode ;
247 
248 		/* encode only members */
249 		struct {
250 			OpusMSEncoder *state ;
251 
252 			/* How many Ogg page segments are in Ogg page currently being assembled. */
253 			int last_segments ;
254 
255 			int bitrate ;
256 			unsigned long latency ;
257 
258 			/* Least significant bit of the source (aka bitwidth) */
259 			int lsb ;
260 			int lsb_last ;
261 		} encode ;
262 	} u ;
263 } OPUS_PRIVATE ;
264 
265 /*-----------------------------------------------------------------------------------------------
266 ** Private function prototypes.
267 */
268 
269 static int			ogg_opus_close (SF_PRIVATE *psf) ;
270 static void			opus_print_header (SF_PRIVATE *psf, OpusHeader *h) ;
271 static int			opus_read_header_packet (SF_PRIVATE *psf, OpusHeader *h, ogg_packet *opacket) ;
272 static int			ogg_opus_read_header (SF_PRIVATE * psf) ;
273 static int			ogg_opus_setup_decoder (SF_PRIVATE *psf, int input_samplerate) ;
274 
275 static int			ogg_opus_setup_encoder (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus) ;
276 static int			ogg_opus_write_header (SF_PRIVATE * psf, int calc_length) ;
277 static void			ogg_opus_flush (SF_PRIVATE *psf) ;
278 static int			ogg_opus_unpack_next_page (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus) ;
279 static int			ogg_opus_calculate_page_duration (OGG_PRIVATE *odata) ;
280 static int			ogg_opus_read_refill (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus) ;
281 static int			ogg_opus_write_out (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus) ;
282 
283 static sf_count_t	ogg_opus_read_s (SF_PRIVATE *psf, short *ptr, sf_count_t len) ;
284 static sf_count_t	ogg_opus_read_i (SF_PRIVATE *psf, int *ptr, sf_count_t len) ;
285 static sf_count_t	ogg_opus_read_f (SF_PRIVATE *psf, float *ptr, sf_count_t len) ;
286 static sf_count_t	ogg_opus_read_d (SF_PRIVATE *psf, double *ptr, sf_count_t len) ;
287 
288 static sf_count_t	ogg_opus_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t len) ;
289 static sf_count_t	ogg_opus_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t len) ;
290 static sf_count_t	ogg_opus_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t len) ;
291 static sf_count_t	ogg_opus_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t len) ;
292 
293 static sf_count_t	ogg_opus_seek (SF_PRIVATE *psf, int mode, sf_count_t offset) ;
294 static sf_count_t	ogg_opus_seek_null_read (SF_PRIVATE *psf, sf_count_t offset) ;
295 static sf_count_t	ogg_opus_seek_manual (SF_PRIVATE *psf, uint64_t target_gp) ;
296 static int			ogg_opus_seek_page_search (SF_PRIVATE *psf, uint64_t target_gp) ;
297 
298 static int			ogg_opus_analyze_file (SF_PRIVATE *psf) ;
299 static int			ogg_opus_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
300 static int			ogg_opus_byterate (SF_PRIVATE *psf) ;
301 
302 /*-----------------------------------------------------------------------------------------------
303 */
304 
305 static vorbiscomment_ident opustags_ident =	{ "OpusTags", 8 } ;
306 
307 /*-----------------------------------------------------------------------------------------------
308 ** Exported functions.
309 */
310 
311 int
ogg_opus_open(SF_PRIVATE * psf)312 ogg_opus_open (SF_PRIVATE *psf)
313 {	OGG_PRIVATE* odata = psf->container_data ;
314 	OPUS_PRIVATE* oopus = calloc (1, sizeof (OPUS_PRIVATE)) ;
315 	int	error = 0 ;
316 
317 	if (odata == NULL)
318 	{	psf_log_printf (psf, "%s : odata is NULL???\n", __func__) ;
319 		free (oopus) ;
320 		return SFE_INTERNAL ;
321 		} ;
322 
323 	psf->codec_data = oopus ;
324 	if (oopus == NULL)
325 		return SFE_MALLOC_FAILED ;
326 
327 	if (psf->file.mode == SFM_RDWR)
328 		return SFE_BAD_MODE_RW ;
329 
330 	psf_log_printf (psf, "Opus library version: %s\n", opus_get_version_string ()) ;
331 
332 	psf->codec_close = ogg_opus_close ;
333 	if (psf->file.mode == SFM_READ)
334 	{	if ((error = ogg_opus_read_header (psf)))
335 			return error ;
336 		if ((error = ogg_opus_analyze_file (psf)))
337 			return error ;
338 
339 		psf->read_short		= ogg_opus_read_s ;
340 		psf->read_int		= ogg_opus_read_i ;
341 		psf->read_float		= ogg_opus_read_f ;
342 		psf->read_double	= ogg_opus_read_d ;
343 		} ;
344 
345 	if (psf->file.mode == SFM_WRITE)
346 	{	if ((error = ogg_opus_setup_encoder (psf, odata, oopus)))
347 			return error ;
348 
349 		psf->write_header	= ogg_opus_write_header ;
350 		psf->write_short	= ogg_opus_write_s ;
351 		psf->write_int		= ogg_opus_write_i ;
352 		psf->write_float	= ogg_opus_write_f ;
353 		psf->write_double	= ogg_opus_write_d ;
354 
355 		psf->sf.frames = SF_COUNT_MAX ; /* Unknown really */
356 		psf->strings.flags = SF_STR_ALLOW_START ;
357 		psf->datalength = 0 ;
358 		psf->dataoffset = 0 ; /* will be updated */
359 		} ;
360 
361 	psf->seek = ogg_opus_seek ;
362 	psf->command = ogg_opus_command ;
363 	psf->byterate = ogg_opus_byterate ;
364 	psf->sf.format = SF_FORMAT_OGG | SF_FORMAT_OPUS ;
365 
366 	return error ;
367 } /* ogg_opus_open */
368 
369 /*==============================================================================
370 ** Private functions.
371 */
372 
373 static int
ogg_opus_close(SF_PRIVATE * psf)374 ogg_opus_close (SF_PRIVATE *psf)
375 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
376 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
377 
378 	if (!oopus)
379 		return 0 ;
380 
381 	if (psf->file.mode == SFM_WRITE)
382 	{	if (psf->have_written)
383 			ogg_opus_flush (psf) ;
384 		else {
385 			/* Write a header... it is expected. */
386 			ogg_opus_write_header (psf, 0) ;
387 			} ;
388 		ogg_packet_clear (&odata->opacket) ;
389 		if (oopus->u.encode.state)
390 		{	opus_multistream_encoder_destroy (oopus->u.encode.state) ;
391 			oopus->u.encode.state = NULL ;
392 			} ;
393 		}
394 	else if (psf->file.mode == SFM_READ)
395 	{	if (oopus->u.decode.state)
396 		{	opus_multistream_decoder_destroy (oopus->u.decode.state) ;
397 			oopus->u.decode.state = NULL ;
398 			} ;
399 		} ;
400 
401 	psf->codec_data = NULL ;
402 	if (oopus->buffer)
403 		free (oopus->buffer) ;
404 	free (oopus) ;
405 
406 	return 0 ;
407 } /* ogg_opus_close */
408 
409 static void
opus_print_header(SF_PRIVATE * psf,OpusHeader * h)410 opus_print_header (SF_PRIVATE *psf, OpusHeader *h)
411 {	psf_log_printf (psf, "Opus Header Metadata\n") ;
412 	psf_log_printf (psf, "  OggOpus version  : %d\n", h->version) ;
413 	psf_log_printf (psf, "  Channels		 : %d\n", h->channels) ;
414 	psf_log_printf (psf, "  Preskip		  : %d samples @48kHz\n", h->preskip) ;
415 	psf_log_printf (psf, "  Input Samplerate : %d Hz\n", h->input_samplerate) ;
416 	psf_log_printf (psf, "  Gain			 : %d.%d\n", arith_shift_right (h->gain & 0xF0, 8), h->gain & 0x0F) ;
417 	psf_log_printf (psf, "  Channel Mapping  : ") ;
418 	switch (h->channel_mapping)
419 	{	case 0 :	psf_log_printf (psf, "0 (mono or stereo)\n") ; break ;
420 		case 1 :	psf_log_printf (psf, "1 (surround, AC3 channel order)\n") ; break ;
421 		case 255 :	psf_log_printf (psf, "255 (no channel order)\n") ; break ;
422 		default :	psf_log_printf (psf, "%d (unknown or unsupported)\n", h->channel_mapping) ; break ;
423 		} ;
424 
425 	if (h->channel_mapping > 0)
426 	{	int i ;
427 		psf_log_printf (psf, "   streams total   : %d\n", h->nb_streams) ;
428 		psf_log_printf (psf, "   streams coupled : %d\n", h->nb_coupled) ;
429 		psf_log_printf (psf, "	stream mapping : [") ;
430 		for (i = 0 ; i < h->channels - 1 ; i++)
431 			psf_log_printf (psf, "%d,", h->stream_map [i]) ;
432 		psf_log_printf (psf, "%d]\n", h->stream_map [i]) ;
433 		} ;
434 } /* opus_print_header */
435 
436 static int
opus_read_header_packet(SF_PRIVATE * psf,OpusHeader * h,ogg_packet * opacket)437 opus_read_header_packet (SF_PRIVATE *psf, OpusHeader *h, ogg_packet *opacket)
438 {	int count, i ;
439 
440 	/*
441 	** Opus headers are 19 bytes, in the case of type 0 channel mapping,
442 	** or 19 + 2 + (1 * channel count) bytes for other channel mappings, to a
443 	** maximum of 276 (255 channels).
444 	*/
445 
446 	if (opacket->bytes < 19 || opacket->bytes > 276)
447 		return SFE_MALFORMED_FILE ;
448 
449 	if (memcmp (opacket->packet, "OpusHead", 8) != 0)
450 		return SFE_MALFORMED_FILE ;
451 
452 	/*
453 	** Copy the header page into the binheader so we can use binheader
454 	** functions to safely unpack it.
455 	*/
456 	count = psf_binheader_writef (psf, "ob", BHWo (0), BHWv (opacket->packet), BHWz (opacket->bytes)) ;
457 	psf->header.end = count ;
458 
459 	count = psf_binheader_readf (psf, "ep1", 8, &h->version) ;
460 	if (! (h->version == 1 || h->version == 0))
461 	{	psf_log_printf (psf, "Opus : Unknown / unsupported embedding scheme version: %d.\n", h->version) ;
462 		return SFE_UNIMPLEMENTED ;
463 		} ;
464 
465 	count += psf_binheader_readf (psf, "e12421", &h->channels, &h->preskip,
466 		&h->input_samplerate, &h->gain, &h->channel_mapping) ;
467 
468 	if (h->channel_mapping == 0)
469 	{	if (h->channels > 2)
470 			return SFE_MALFORMED_FILE ;
471 
472 		/*
473 		** Setup the stream mapping, so we can use the multistream decoder,
474 		** rather than have to deal with two decoder pointer types
475 		*/
476 		h->nb_streams = 1 ;
477 		h->nb_coupled = h->channels - 1 ;
478 		h->stream_map [0] = 0 ;
479 		h->stream_map [1] = 1 ;
480 		}
481 	else
482 	{	if (opacket->bytes < 19 + 2 + h->channels)
483 			return SFE_MALFORMED_FILE ;
484 
485 		if (h->channel_mapping == 1 && h->channels > 8)
486 			return SFE_MALFORMED_FILE ;
487 
488 		count += psf_binheader_readf (psf, "11", &h->nb_streams, &h->nb_coupled) ;
489 
490 		if (h->nb_streams < 1 ||
491 			h->nb_coupled > h->nb_streams ||
492 			h->nb_coupled + h->nb_streams > 255)
493 			return SFE_MALFORMED_FILE ;
494 
495 		for (i = 0 ; i < h->channels ; i++)
496 		{	count += psf_binheader_readf (psf, "1", &(h->stream_map [i])) ;
497 			if (h->stream_map [i] > h->nb_streams + h->nb_coupled && h->stream_map [i] != 255)
498 				return SFE_MALFORMED_FILE ;
499 			} ;
500 		} ;
501 
502 	if (count != opacket->bytes)
503 	{	/* OggOpus spec mandates that this is a hard error. */
504 		psf_log_printf (psf, "Opus : Error, extra data in Ogg Opus header.\n") ;
505 		return SFE_MALFORMED_FILE ;
506 		} ;
507 
508 	opus_print_header (psf, h) ;
509 
510 	return 0 ;
511 } /* ogg_opus_read_header_packet */
512 
513 static int
ogg_opus_read_header(SF_PRIVATE * psf)514 ogg_opus_read_header (SF_PRIVATE *psf)
515 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
516 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
517 	int error ;
518 
519 	/*
520 	** First page is already loaded by the ogg container code when it
521 	** classified the stream, no need to re-load it now.
522 	*/
523 
524 	if (ogg_page_packets (&odata->opage) != 1 || !ogg_page_bos (&odata->opage))
525 		return SFE_MALFORMED_FILE ;
526 
527 	oopus->serialno = ogg_page_serialno (&odata->opage) ;
528 	if ((error = opus_read_header_packet (psf, &oopus->header, &odata->opacket)))
529 		return error ;
530 
531 	/*
532 	** The comment header MUST be next. It is one packet, that packet MUST begin
533 	** on the second page of the stream, but it MAY span multiple pages.
534 	*/
535 
536 	while (ogg_stream_packetout (&odata->ostream, &odata->opacket) != 1)
537 	{	if (ogg_stream_next_page (psf, odata) != 1)
538 		{	/* out of data... technically that's malformed. */
539 			return psf->error ? psf->error : SFE_MALFORMED_FILE ;
540 			} ;
541 		} ;
542 
543 	if ((error = vorbiscomment_read_tags (psf, &odata->opacket, &opustags_ident)))
544 		return error ;
545 
546 	return ogg_opus_setup_decoder (psf, oopus->header.input_samplerate) ;
547 } /* ogg_opus_read_header */
548 
549 static int
ogg_opus_setup_decoder(SF_PRIVATE * psf,int input_samplerate)550 ogg_opus_setup_decoder (SF_PRIVATE *psf, int input_samplerate)
551 {	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
552 	OpusMSDecoder *decoder ;
553 	int sr_factor ;
554 	int error ;
555 
556 	/*
557 	** Decide what sample rate to decode at. We choose the lowest valid rate
558 	** that is greater or equal to the original rate.
559 	**
560 	** Opus documentation recommends always decoding at 48000Hz if the file is
561 	** being decoded for playback, since most hardware will resample it back to
562 	** 48000Hz anyways. We don't know if that's true, maybe the user is
563 	** decoding for editing or transcoding purposes.
564 	*/
565 	if (input_samplerate > 24000)
566 		sr_factor = 1 ;
567 	else if (input_samplerate > 16000)
568 		sr_factor = 2 ;
569 	else if (input_samplerate > 12000)
570 		sr_factor = 3 ;
571 	else if (input_samplerate > 8000)
572 		sr_factor = 4 ;
573 	else
574 		sr_factor = 6 ;
575 
576 	decoder = opus_multistream_decoder_create (
577 		48000 / sr_factor,
578 		oopus->header.channels,
579 		oopus->header.nb_streams,
580 		oopus->header.nb_coupled,
581 		oopus->header.stream_map,
582 		&error) ;
583 
584 	if (error != OPUS_OK)
585 	{	psf_log_printf (psf, "Opus : Failed to create multistream decoder: %s\n",
586 			opus_strerror (error)) ;
587 		return SFE_INTERNAL ;
588 		}
589 
590 	/*
591 	** Replace the decoder, if one was already initialized (see
592 	** SFC_GET_ORIGINAL_SAMPLERATE)
593 	*/
594 	if (oopus->u.decode.state)
595 		opus_multistream_decoder_destroy (oopus->u.decode.state) ;
596 	oopus->u.decode.state = decoder ;
597 
598 	oopus->sr_factor = sr_factor ;
599 	psf->sf.samplerate = 48000 / sr_factor ;
600 	psf->sf.channels = oopus->header.channels ;
601 	oopus->loc = oopus->len = 0 ;
602 
603 	/*
604 	** The Opus decoder can do our gain for us. The OggOpus header contains a
605 	** gain field. This field, unlike various gain-related tags, is intended to
606 	** be a perminent baked-in gain applied before any user-configurable gain
607 	** (eg replay-gain.) This is so the gain of track can be set without having
608 	** to re-encode.
609 	**
610 	** Both the header.gain field and the parameter are in the Q7.8 format.
611 	**
612 	** TODO: Make this configurable? Include other gain sources too?
613 	*/
614 	opus_multistream_decoder_ctl (oopus->u.decode.state, OPUS_SET_GAIN (oopus->header.gain)) ;
615 
616 	/*
617 	** Opus packets can vary in length, with the legal values being 2.5, 5, 10,
618 	** 20, 40 or 60ms. The recommended default for non-realtime is 20ms. As
619 	** such, allocate a buffer of that size now, we'll realloc later if a
620 	** larger one is needed.
621 	**
622 	** buffersize is expressed in samples/channel, as that is what opus_decode
623 	** expects.
624 	*/
625 	if (oopus->buffer)
626 	{	free (oopus->buffer) ;
627 		oopus->buffer = NULL ;
628 		} ;
629 	oopus->buffersize = 20 * psf->sf.samplerate / 1000 ;
630 	oopus->buffer = malloc (sizeof (float) * psf->sf.channels * oopus->buffersize) ;
631 	if (oopus->buffer == NULL)
632 		return SFE_MALLOC_FAILED ;
633 
634 	return 0 ;
635 } /* ogg_opus_setup_decoder */
636 
637 static int
ogg_opus_setup_encoder(SF_PRIVATE * psf,OGG_PRIVATE * odata,OPUS_PRIVATE * oopus)638 ogg_opus_setup_encoder (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus)
639 {	int error ;
640 	int lookahead ;
641 	int nb_streams ;
642 	int nb_coupled ;
643 
644 	/* default page latency value (1000ms) */
645 	oopus->u.encode.latency = 1000 * 48 ;
646 
647 	switch (psf->sf.samplerate)
648 	{	case 8000 :
649 		case 12000 :
650 		case 16000 :
651 		case 24000 :
652 		case 48000 :
653 			oopus->sr_factor = 48000 / psf->sf.samplerate ;
654 			break ;
655 		default :
656 			return SFE_OPUS_BAD_SAMPLERATE ;
657 		} ;
658 
659 	if (psf->sf.channels <= 2)
660 	{	oopus->header.channel_mapping = 0 ;
661 		nb_streams = 1 ;
662 		nb_coupled = psf->sf.channels - 1 ;
663 		oopus->header.stream_map [0] = 0 ;
664 		oopus->header.stream_map [1] = 1 ;
665 
666 		oopus->u.encode.state = opus_multistream_encoder_create (
667 			psf->sf.samplerate,
668 			psf->sf.channels,
669 			nb_streams,
670 			nb_coupled,
671 			oopus->header.stream_map,
672 			OPUS_APPLICATION_AUDIO,
673 			&error) ;
674 		}
675 	else
676 	{	if (psf->sf.channels <= 8)
677 		{	/* Use Vorbis/AC3 channel mappings for surround. */
678 			oopus->header.channel_mapping = 1 ;
679 			}
680 		else
681 		{	/* There is no channel mapping, just audio, in parallel, good luck */
682 			oopus->header.channel_mapping = 255 ;
683 			}
684 
685 		oopus->u.encode.state = opus_multistream_surround_encoder_create (
686 			psf->sf.samplerate,
687 			psf->sf.channels,
688 			oopus->header.channel_mapping,
689 			&nb_streams,
690 			&nb_coupled,
691 			oopus->header.stream_map,
692 			OPUS_APPLICATION_AUDIO,
693 			&error) ;
694 
695 		}
696 
697 	if (error != OPUS_OK)
698 	{	psf_log_printf (psf, "Opus : Error, opus_multistream_encoder_create returned %s\n", opus_strerror (error)) ;
699 		return SFE_BAD_OPEN_FORMAT ;
700 		} ;
701 	oopus->header.nb_streams = nb_streams ;
702 	oopus->header.nb_coupled = nb_coupled ;
703 
704 	opus_multistream_encoder_ctl (oopus->u.encode.state, OPUS_GET_BITRATE (&oopus->u.encode.bitrate)) ;
705 	psf_log_printf (psf, "Encoding at target bitrate of %dbps\n", oopus->u.encode.bitrate) ;
706 
707 	/* TODO: Make configurable? */
708 	error = opus_multistream_encoder_ctl (oopus->u.encode.state, OPUS_SET_COMPLEXITY (10)) ;
709 	if (error != OPUS_OK)
710 	{	/* Non-fatal */
711 		psf_log_printf (psf, "Opus : OPUS_SET_COMPLEXITY returned: %s\n", opus_strerror (error)) ;
712 		}
713 
714 	/*
715 	** Get the encoder delay. This can vary depending on implementation and
716 	** encoder configuration.
717 	** GOTCHA: This returns the preskip at the encoder samplerate, not the
718 	** granulepos rate of 48000Hz needed for header.preskip.
719 	*/
720 	error = opus_multistream_encoder_ctl (oopus->u.encode.state, OPUS_GET_LOOKAHEAD (&lookahead)) ;
721 	if (error != OPUS_OK)
722 	{	psf_log_printf (psf, "Opus : OPUS_GET_LOOKAHEAD returned: %s\n", opus_strerror (error)) ;
723 		return SFE_BAD_OPEN_FORMAT ;
724 		} ;
725 	oopus->header.preskip = lookahead * oopus->sr_factor ;
726 
727 	oopus->len = OGG_OPUS_ENCODE_PACKET_LEN (psf->sf.samplerate) ;
728 	oopus->buffer = malloc (sizeof (float) * psf->sf.channels * oopus->len) ;
729 	if (oopus->buffer == NULL)
730 		return SFE_MALLOC_FAILED ;
731 
732 	/*
733 	** Set up the resident ogg packet structure, ready for writing into.
734 	** 1275 * 3 + 7 bytes of packet per stream is from opusenc from opus-tools
735 	*/
736 	ogg_packet_clear (&odata->opacket) ;
737 	oopus->buffersize = (1275 * 3 + 7) * oopus->header.nb_streams ;
738 	odata->opacket.packet = malloc (oopus->buffersize) ;
739 	odata->opacket.packetno = 2 ;
740 	if (odata->opacket.packet == NULL)
741 		return SFE_MALLOC_FAILED ;
742 
743 	oopus->serialno = psf_rand_int32 () ;
744 	ogg_stream_init (&odata->ostream, oopus->serialno) ;
745 
746 	return 0 ;
747 } /* ogg_opus_setup_encoder */
748 
749 static int
ogg_opus_write_header(SF_PRIVATE * psf,int UNUSED (calc_length))750 ogg_opus_write_header (SF_PRIVATE *psf, int UNUSED (calc_length))
751 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
752 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
753 	int nn ;
754 	ogg_packet op ;
755 
756 	oopus->header.version = 1 ;
757 	oopus->header.channels = psf->sf.channels ;
758 
759 	/* FIXME: Allow the user to set this ?! */
760 	oopus->header.gain = 0 ;
761 
762 	if (psf->dataoffset > 0)
763 	{	if (psf->have_written)
764 		{	/*
765 			** Might be possible to deal with this, but it's difficult as we
766 			** have to take Ogg Page header sizes in to account, not just
767 			** packet sizes.
768 			*/
769 			return SFE_UNIMPLEMENTED ;
770 			}
771 		if (psf_is_pipe (psf))
772 			return SFE_NOT_SEEKABLE ;
773 		if (psf_fseek (psf, 0, SEEK_SET) < 0)
774 			return SFE_SEEK_FAILED ;
775 		ogg_stream_reset_serialno (&odata->ostream, oopus->serialno) ;
776 		psf->dataoffset = 0 ;
777 		}
778 	else
779 		opus_print_header (psf, &oopus->header) ;
780 
781 	psf->header.ptr [0] = 0 ;
782 	psf->header.indx = 0 ;
783 
784 	/* Opus Header Marker */
785 	psf_binheader_writef (psf, "eb", BHWv ("OpusHead"), BHWz (8)) ;
786 
787 	/* Ogg Embedding scheme version, Channel Count, Preskip Samples */
788 	psf_binheader_writef (psf, "e112", BHW1 (oopus->header.version), BHW1 (psf->sf.channels), BHW2 (oopus->header.preskip)) ;
789 
790 	/*
791 	** If an original samplerate has not been set by the user command
792 	** SFC_SET_ORIGINAL_SAMPLERATE, write the current samplerate.
793 	*/
794 	if (oopus->header.input_samplerate)
795 		psf_binheader_writef (psf, "e4", BHW4 (oopus->header.input_samplerate)) ;
796 	else
797 		psf_binheader_writef (psf, "e4", BHW4 (psf->sf.samplerate)) ;
798 
799 	/* Input Sample Rate, Gain (S7.8 format), Channel Mapping Type */
800 	psf_binheader_writef (psf, "e21", BHW2 (oopus->header.gain), BHW1 (oopus->header.channel_mapping)) ;
801 
802 	/* Channel mappings, required if not using type 0 (mono/stereo) */
803 	if (oopus->header.channel_mapping > 0)
804 	{	psf_binheader_writef (psf, "11", BHW1 (oopus->header.nb_streams), BHW1 (oopus->header.nb_coupled)) ;
805 		for (nn = 0 ; nn < oopus->header.channels ; nn++)
806 			psf_binheader_writef (psf, "1", BHW1 (oopus->header.stream_map [nn])) ;
807 		} ;
808 
809 	op.packet = psf->header.ptr ;
810 	op.bytes = psf->header.indx ;
811 	op.b_o_s = 1 ;
812 	op.e_o_s = 0 ;
813 	op.granulepos = 0 ;
814 	op.packetno = 1 ;
815 
816 	/* The first page MUST only contain the header, so flush it out now */
817 	ogg_stream_packetin (&odata->ostream, &op) ;
818 	for ( ; (nn = ogg_stream_flush (&odata->ostream, &odata->opage)) ; )
819 	{	if (! (nn = ogg_write_page (psf, &odata->opage)))
820 		{	psf_log_printf (psf, "Opus : Failed to write header!\n") ;
821 			if (psf->error)
822 				return psf->error ;
823 			return SFE_INTERNAL ;
824 			} ;
825 		psf->dataoffset += nn ;
826 		}
827 
828 	/*
829 	** Metadata Tags (manditory)
830 	**
831 	** All tags must be in one packet, which may span pages, and these pages
832 	** must not contain any other packets, so flush. The vendor string should
833 	** be the libopus library version, as it is doing the actual encoding. We
834 	** put the libsndfile identifier in the ENCODER tag.
835 	**
836 	** See: https://wiki.xiph.org/VorbisComment#ENCODER
837 	*/
838 	vorbiscomment_write_tags (psf, &op, &opustags_ident, opus_get_version_string (), - (OGG_OPUS_COMMENT_PAD)) ;
839 	op.packetno = 2 ;
840 	ogg_stream_packetin (&odata->ostream, &op) ;
841 	for ( ; (nn = ogg_stream_flush (&odata->ostream, &odata->opage)) ; )
842 	{	if (! (nn = ogg_write_page (psf, &odata->opage)))
843 		{	psf_log_printf (psf, "Opus : Failed to write comments!\n") ;
844 			if (psf->error)
845 				return psf->error ;
846 			return SFE_INTERNAL ;
847 			} ;
848 		psf->dataoffset += nn ;
849 		}
850 
851 	return 0 ;
852 } /* ogg_opus_write_header */
853 
854 static void
ogg_opus_flush(SF_PRIVATE * psf)855 ogg_opus_flush (SF_PRIVATE *psf)
856 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
857 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
858 	uint64_t last_granulepos ;
859 	int nbytes ;
860 	int len ;
861 	int last_packet ;
862 
863 	/*
864 	** Need to flush both samples waiting for a complete packet and samples
865 	** currently 'inside' the encoder because of its latency. In the case of
866 	** the latter, we need to encode an equivalent amount of silence to push
867 	** them out.
868 	**
869 	** Note that the last packet's granule position might be less than the
870 	** total number of samples completed in it. This is how Ogg embedded Opus
871 	** encodes the amount of appended padding to truncate for gapless playback.
872 	*/
873 
874 	last_granulepos = oopus->pkt_pos + (oopus->sr_factor * oopus->loc) + oopus->header.preskip ;
875 	last_packet = SF_FALSE ;
876 	memset (&(oopus->buffer [oopus->loc * psf->sf.channels]), 0, sizeof (float) * psf->sf.channels * (oopus->len - oopus->loc)) ;
877 
878 	for (last_packet = SF_FALSE ; last_packet == SF_FALSE ; )
879 	{	oopus->pkt_pos += oopus->len * oopus->sr_factor ;
880 		if (oopus->pkt_pos >= last_granulepos)
881 		{	last_packet = SF_TRUE ;
882 			/*
883 			** Try to shorten the last packet to the smallest valid packet size
884 			** to minimize padding samples.
885 			*/
886 			len = (oopus->len * oopus->sr_factor) - (oopus->pkt_pos - last_granulepos) ;
887 			if (len <= 120) /* 2.5 ms */
888 				len = 120 / oopus->sr_factor ;
889 			else if (len <= 240) /* 5 ms */
890 				len = 240 / oopus->sr_factor ;
891 			else if (len <= 480) /* 10 ms */
892 				len = 480 / oopus->sr_factor ;
893 			else
894 				len = oopus->len ;
895 			}
896 		else
897 			len = oopus->len ;
898 
899 		nbytes = opus_multistream_encode_float (oopus->u.encode.state, oopus->buffer,
900 					len, odata->opacket.packet, oopus->buffersize) ;
901 
902 		if (nbytes < 0)
903 		{	psf_log_printf (psf, "Opus : opus_multistream_encode_float returned: %s\n", opus_strerror (nbytes)) ;
904 			break ;
905 			}
906 
907 		odata->opacket.bytes = nbytes ;
908 		odata->opacket.packetno++ ;
909 		if (last_packet)
910 		{	odata->opacket.granulepos = (ogg_int64_t) last_granulepos ;
911 			odata->opacket.e_o_s = 1 ;
912 			}
913 		else
914 			odata->opacket.granulepos = (ogg_int64_t) oopus->pkt_pos ;
915 
916 		ogg_stream_packetin (&odata->ostream, &odata->opacket) ;
917 		while (ogg_stream_pageout (&odata->ostream, &odata->opage))
918 			ogg_write_page (psf, &odata->opage) ;
919 		} ;
920 
921 	while (ogg_stream_flush (&odata->ostream, &odata->opage))
922 		ogg_write_page (psf, &odata->opage) ;
923 } /* ogg_opus_flush */
924 
925 static int
ogg_opus_calculate_page_duration(OGG_PRIVATE * odata)926 ogg_opus_calculate_page_duration (OGG_PRIVATE *odata)
927 {	int i, samples, duration ;
928 	ogg_packet *ppkt ;
929 
930 	duration = 0 ;
931 	for (i = 0 , ppkt = odata->pkt ; i < odata->pkt_len ; i++, ppkt++)
932 	{	/* Use 48kHz to get the sample count for use with granule positions. */
933 		samples = opus_packet_get_nb_samples (ppkt->packet, ppkt->bytes, 48000) ;
934 		if (samples > 0)
935 			duration += samples ;
936 		} ;
937 	return duration ;
938 } /* ogg_opus_calculate_page_duration */
939 
940 static int
ogg_opus_unpack_next_page(SF_PRIVATE * psf,OGG_PRIVATE * odata,OPUS_PRIVATE * oopus)941 ogg_opus_unpack_next_page (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus)
942 {	int nn ;
943 
944 	nn = ogg_stream_unpack_page (psf, odata) ;
945 
946 	if (nn == 1)
947 	{	oopus->pkt_pos = oopus->pg_pos ;
948 		oopus->pg_pos = odata->pkt [odata->pkt_len - 1].granulepos ;
949 		}
950 	else if (nn == 2)
951 	{	uint64_t gp, last_page ;
952 
953 		/* Found a hole. Need to recalculated pkt_pos from pg_pos */
954 		last_page = oopus->pg_pos ;
955 		oopus->pg_pos = odata->pkt [odata->pkt_len - 1].granulepos ;
956 		gp = ogg_opus_calculate_page_duration (odata) ;
957 		oopus->pkt_pos = oopus->pg_pos - gp ;
958 		psf_log_printf (psf, "Opus : Hole found appears to be of length %d samples.\n",
959 				(oopus->pkt_pos - last_page) / oopus->sr_factor) ;
960 		/*
961 		** Could save the hole size here, and have ogg_opus_read_refill()
962 		** do packet loss concealment until the hole is gone, but libopus does
963 		** PLC by generating white-noise for the duration of the hole. That is
964 		** the correct thing for use in telephony, but it isn't generally
965 		** appropriate here. It actually sounds better with no PLC, as the
966 		** lapped nature of full-width Opus means the two edges of the hole
967 		** will be blended together.
968 		*/
969 		return 1 ;
970 		}
971 
972 	return nn ;
973 } /* ogg_opus_unpack_next_page */
974 
975 static int
ogg_opus_read_refill(SF_PRIVATE * psf,OGG_PRIVATE * odata,OPUS_PRIVATE * oopus)976 ogg_opus_read_refill (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus)
977 {	uint64_t pkt_granulepos ;
978 	int nn, nsamp ;
979 	ogg_packet *ppkt ;
980 
981 	if (odata->pkt_indx == odata->pkt_len)
982 	{	nn = ogg_opus_unpack_next_page (psf, odata, oopus) ;
983 		if (nn <= 0)
984 			return nn ;
985 		}
986 
987 	if (odata->pkt_indx == odata->pkt_len)
988 		return 0 ;
989 
990 	ppkt = odata->pkt + odata->pkt_indx ;
991 	nsamp = opus_multistream_decode_float (oopus->u.decode.state,
992 				ppkt->packet, ppkt->bytes, oopus->buffer, oopus->buffersize, 0) ;
993 
994 	if (nsamp == OPUS_BUFFER_TOO_SMALL)
995 	{	nsamp = opus_packet_get_nb_samples (ppkt->packet, ppkt->bytes, psf->sf.samplerate) ;
996 		psf_log_printf (psf, "Growing decode buffer to hold %d samples from %d\n",
997 			nsamp, oopus->buffersize) ;
998 		if (nsamp > 5760)
999 		{	psf_log_printf (psf, "Packet is larger than maximum allowable of 120ms!? Skipping.\n") ;
1000 			return 0 ;
1001 			} ;
1002 		oopus->buffersize = nsamp ;
1003 
1004 		free (oopus->buffer) ;
1005 		oopus->buffer = NULL ;
1006 		oopus->buffer = malloc (sizeof (float) * oopus->buffersize * psf->sf.channels) ;
1007 		if (oopus->buffer == NULL)
1008 		{	psf->error = SFE_MALLOC_FAILED ;
1009 			oopus->buffersize = 0 ;
1010 			return -1 ;
1011 			} ;
1012 
1013 		nsamp = opus_multistream_decode_float (oopus->u.decode.state,
1014 				ppkt->packet, ppkt->bytes, oopus->buffer, oopus->buffersize, 0) ;
1015 		} ;
1016 	odata->pkt_indx ++ ;
1017 
1018 	if (nsamp < 0)
1019 	{	psf_log_printf (psf, "Opus : opus_multistream_decode returned: %s\n",
1020 			opus_strerror (nsamp)) ;
1021 		psf->error = SFE_INTERNAL ;
1022 		return nsamp ;
1023 		} ;
1024 
1025 	/*
1026 	** Check for if this decoded packet is the last of the stream, in
1027 	** which case a page granule position which is shorter than the
1028 	** sample count of all packets in the page indicates that the last
1029 	** samples are padding and should be dropped.
1030 	*/
1031 	pkt_granulepos = oopus->pkt_pos + (nsamp * oopus->sr_factor) ;
1032 	if (pkt_granulepos <= oopus->pg_pos)
1033 	{	oopus->len = nsamp ;
1034 		}
1035 	else
1036 	{	if (ogg_page_eos (&odata->opage))
1037 		{	/*
1038 			** Possible for pg_pos < pkt_pos if there is a trailing
1039 			** packet. It's not supposed to happen, but could.
1040 			*/
1041 			oopus->len = SF_MAX ((int) (oopus->pg_pos - oopus->pkt_pos) / oopus->sr_factor, 0) ;
1042 			}
1043 		else
1044 		{	/*
1045 			** From https://wiki.xiph.org/OggOpus#Granule_Position
1046 			**	A decoder MUST reject as invalid any stream where the granule
1047 			**	position is smaller than the number of samples contained in
1048 			**	packets that complete on the first page with a completed
1049 			**	packet, unless that page has the 'end of stream' flag set. It
1050 			**	MAY defer this action until it decodes the last packet
1051 			**	completed on that page.
1052 			*/
1053 			psf_log_printf (psf, "Opus : Mid-strem page's granule position %d is less than total samples of %d\n", oopus->pg_pos, pkt_granulepos) ;
1054 			psf->error = SFE_MALFORMED_FILE ;
1055 			return -1 ;
1056 			} ;
1057 		} ;
1058 
1059 	if (oopus->len > oopus->buffersize)
1060 	{	free (oopus->buffer) ;
1061 		oopus->buffersize = oopus->len ;
1062 		oopus->buffer = malloc (sizeof (float) * oopus->buffersize * psf->sf.channels) ;
1063 		if (oopus->buffer == NULL)
1064 		{	psf->error = SFE_MALLOC_FAILED ;
1065 			oopus->buffersize = 0 ;
1066 			return -1 ;
1067 			} ;
1068 		} ;
1069 
1070 	/*
1071 	** Check for if this decoded packet contains samples from before the pre-
1072 	** skip point, indicating that these samples are padding to get the decoder
1073 	** to converge and should be dropped.
1074 	*/
1075 	if (oopus->pkt_pos < (unsigned) oopus->header.preskip)
1076 		oopus->loc = SF_MIN ((oopus->header.preskip - (int) oopus->pkt_pos) / oopus->sr_factor, oopus->len) ;
1077 	else
1078 		oopus->loc = 0 ;
1079 
1080 	oopus->pkt_pos = pkt_granulepos ;
1081 
1082 	return nsamp ;
1083 } /* ogg_opus_read_refill */
1084 
1085 static int
ogg_opus_write_out(SF_PRIVATE * psf,OGG_PRIVATE * odata,OPUS_PRIVATE * oopus)1086 ogg_opus_write_out (SF_PRIVATE *psf, OGG_PRIVATE *odata, OPUS_PRIVATE *oopus)
1087 {	int nbytes ;
1088 
1089 	if (oopus->u.encode.lsb != oopus->u.encode.lsb_last)
1090 		opus_multistream_encoder_ctl (oopus->u.encode.state, OPUS_SET_LSB_DEPTH (oopus->u.encode.lsb)) ;
1091 
1092 	nbytes = opus_multistream_encode_float (oopus->u.encode.state,
1093 		oopus->buffer, oopus->len,
1094 		odata->opacket.packet, oopus->buffersize) ;
1095 
1096 	if (nbytes < 0)
1097 	{	psf_log_printf (psf, "Opus : Error, opus_multistream_encode_float returned: %s\n", opus_strerror (nbytes)) ;
1098 		psf->error = SFE_INTERNAL ;
1099 		return nbytes ;
1100 		} ;
1101 
1102 	oopus->u.encode.last_segments += (nbytes + 255) / 255 ;
1103 	oopus->pkt_pos += oopus->len * oopus->sr_factor ;
1104 	odata->opacket.bytes = nbytes ;
1105 	odata->opacket.granulepos = oopus->pkt_pos ;
1106 	odata->opacket.packetno++ ;
1107 
1108 	/*
1109 	** Decide whether to flush the Ogg page *before* adding the new packet to
1110 	** it. Check both for if there is more than 1 second of audio (our default
1111 	** Ogg page latency, this latency can be modified using sf_command())
1112 	** or if adding the packet would cause a continued page,
1113 	** in which case we might as well make a new page anyways.
1114 	*/
1115 	for ( ; ; )
1116 	{	if (oopus->pkt_pos - oopus->pg_pos >= oopus->u.encode.latency || oopus->u.encode.last_segments >= 255)
1117 			nbytes = ogg_stream_flush_fill (&odata->ostream, &odata->opage, 255 * 255) ;
1118 		else
1119 			nbytes = ogg_stream_pageout_fill (&odata->ostream, &odata->opage, 255 * 255) ;
1120 		if (nbytes > 0)
1121 		{	/*
1122 			** LibOgg documentation is noted as being bad by it's author. Ogg
1123 			** page header byte 26 is the segment count.
1124 			*/
1125 			oopus->u.encode.last_segments -= odata->opage.header [26] ;
1126 			oopus->pg_pos = oopus->pkt_pos ;
1127 			ogg_write_page (psf, &odata->opage) ;
1128 			}
1129 		else
1130 			break ;
1131 		} ;
1132 
1133 	ogg_stream_packetin (&odata->ostream, &odata->opacket) ;
1134 	oopus->loc = 0 ;
1135 	oopus->u.encode.lsb_last = oopus->u.encode.lsb ;
1136 	oopus->u.encode.lsb = 0 ;
1137 
1138 	return 1 ;
1139 } /* ogg_opus_write_out */
1140 
1141 static sf_count_t
ogg_opus_read_s(SF_PRIVATE * psf,short * ptr,sf_count_t len)1142 ogg_opus_read_s (SF_PRIVATE *psf, short *ptr, sf_count_t len)
1143 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1144 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1145 	sf_count_t total = 0 ;
1146 	sf_count_t readlen, i ;
1147 	float *iptr ;
1148 
1149 	while (total < len)
1150 	{	if (oopus->loc == oopus->len)
1151 		{	if (ogg_opus_read_refill (psf, odata, oopus) <= 0)
1152 				return total ;
1153 			} ;
1154 
1155 		readlen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1156 		if (readlen > 0)
1157 		{	iptr = oopus->buffer + oopus->loc * psf->sf.channels ;
1158 			i = total ;
1159 			total += readlen ;
1160 
1161 			if (psf->float_int_mult)
1162 			{	float inverse = 1.0 / psf->float_max ;
1163 				for ( ; i < total ; i++)
1164 				{	ptr [i] = psf_lrintf (((*(iptr++)) * inverse) * 32767.0f) ;
1165 					} ;
1166 				}
1167 			else
1168 			{	for ( ; i < total ; i++)
1169 				{	ptr [i] = psf_lrintf ((*(iptr++)) * 32767.0f) ;
1170 					} ;
1171 				} ;
1172 			oopus->loc += (readlen / psf->sf.channels) ;
1173 			} ;
1174 		} ;
1175 	return total ;
1176 } /* ogg_opus_read_s */
1177 
1178 static sf_count_t
ogg_opus_read_i(SF_PRIVATE * psf,int * ptr,sf_count_t len)1179 ogg_opus_read_i (SF_PRIVATE *psf, int *ptr, sf_count_t len)
1180 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1181 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1182 	sf_count_t total = 0 ;
1183 	sf_count_t readlen, i ;
1184 	float *iptr ;
1185 
1186 	while (total < len)
1187 	{	if (oopus->loc == oopus->len)
1188 		{	if (ogg_opus_read_refill (psf, odata, oopus) <= 0)
1189 				return total ;
1190 			} ;
1191 
1192 		readlen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1193 		if (readlen > 0)
1194 		{	iptr = oopus->buffer + oopus->loc * psf->sf.channels ;
1195 			i = total ;
1196 			total += readlen ;
1197 
1198 			if (psf->float_int_mult)
1199 			{	float inverse = 1.0 / psf->float_max ;
1200 				for ( ; i < total ; i++)
1201 				{	ptr [i] = psf_lrintf (((*(iptr++)) * inverse) * 2147483647.0f) ;
1202 					}
1203 				}
1204 			else
1205 			{	for ( ; i < total ; i++)
1206 				{	ptr [i] = psf_lrintf ((*(iptr++)) * 2147483647.0f) ;
1207 					}
1208 				} ;
1209 			oopus->loc += (readlen / psf->sf.channels) ;
1210 			} ;
1211 		} ;
1212 	return total ;
1213 } /* ogg_opus_read_i */
1214 
1215 static sf_count_t
ogg_opus_read_f(SF_PRIVATE * psf,float * ptr,sf_count_t len)1216 ogg_opus_read_f (SF_PRIVATE *psf, float *ptr, sf_count_t len)
1217 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1218 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1219 	sf_count_t total = 0 ;
1220 	sf_count_t readlen ;
1221 
1222 	while (total < len)
1223 	{	if (oopus->loc == oopus->len)
1224 		{	if (ogg_opus_read_refill (psf, odata, oopus) <= 0)
1225 				return total ;
1226 			} ;
1227 
1228 		readlen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1229 		if (readlen > 0)
1230 		{	memcpy (&(ptr [total]), &(oopus->buffer [oopus->loc * psf->sf.channels]), sizeof (float) * readlen) ;
1231 			total += readlen ;
1232 			oopus->loc += (readlen / psf->sf.channels) ;
1233 			} ;
1234 		} ;
1235 	return total ;
1236 } /* ogg_opus_read_f */
1237 
1238 static sf_count_t
ogg_opus_read_d(SF_PRIVATE * psf,double * ptr,sf_count_t len)1239 ogg_opus_read_d (SF_PRIVATE *psf, double *ptr, sf_count_t len)
1240 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1241 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1242 	sf_count_t total = 0 ;
1243 	sf_count_t readlen, i ;
1244 	float *fptr ;
1245 
1246 	while (total < len)
1247 	{	if (oopus->loc >= oopus->len)
1248 		{	if (ogg_opus_read_refill (psf, odata, oopus) <= 0)
1249 				return total ;
1250 			} ;
1251 
1252 		readlen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1253 
1254 		if (readlen > 0)
1255 		{	fptr = oopus->buffer + oopus->loc * psf->sf.channels ;
1256 			i = total ;
1257 			total += readlen ;
1258 			for ( ; i < total ; i++)
1259 			{	ptr [i] = *fptr++ ;
1260 				} ;
1261 			oopus->loc += readlen / psf->sf.channels ;
1262 			} ;
1263 		} ;
1264 	return total ;
1265 } /* ogg_opus_read_d */
1266 
1267 static sf_count_t
ogg_opus_write_s(SF_PRIVATE * psf,const short * ptr,sf_count_t len)1268 ogg_opus_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t len)
1269 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1270 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1271 	sf_count_t total, i ;
1272 	int writelen ;
1273 	float *optr ;
1274 
1275 	if (oopus->u.encode.lsb < 16)
1276 		oopus->u.encode.lsb = 16 ;
1277 
1278 	for (total = 0 ; total < len ; )
1279 	{	if (oopus->loc >= oopus->len)
1280 		{	/* Need to encode the buffer */
1281 			if (ogg_opus_write_out (psf, odata, oopus) <= 0)
1282 				return total ;
1283 			} ;
1284 
1285 		writelen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1286 		if (writelen)
1287 		{	optr = oopus->buffer + oopus->loc * psf->sf.channels ;
1288 			i = total ;
1289 			total += writelen ;
1290 			for ( ; i < total ; i++)
1291 			{	*optr++ = (float) (ptr [i]) / 32767.0f ;
1292 				}
1293 			oopus->loc += (writelen / psf->sf.channels) ;
1294 			} ;
1295 		} ;
1296 	return total ;
1297 } /* ogg_opus_write_s */
1298 
1299 static sf_count_t
ogg_opus_write_i(SF_PRIVATE * psf,const int * ptr,sf_count_t len)1300 ogg_opus_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t len)
1301 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1302 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1303 	sf_count_t total, i ;
1304 	int writelen ;
1305 	float *optr ;
1306 
1307 	if (oopus->u.encode.lsb < 24)
1308 		oopus->u.encode.lsb = 24 ;
1309 
1310 	for (total = 0 ; total < len ; )
1311 	{	if (oopus->loc >= oopus->len)
1312 		{	/* Need to encode the buffer */
1313 			if (ogg_opus_write_out (psf, odata, oopus) <= 0)
1314 				return total ;
1315 			} ;
1316 
1317 		writelen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1318 		if (writelen)
1319 		{	optr = oopus->buffer + oopus->loc * psf->sf.channels ;
1320 			i = total ;
1321 			total += writelen ;
1322 			for ( ; i < total ; i++)
1323 			{	*optr++ = (float) (ptr [i]) / 2147483647.0f ;
1324 				} ;
1325 			oopus->loc += (writelen / psf->sf.channels) ;
1326 			} ;
1327 		} ;
1328 	return total ;
1329 } /* ogg_opus_write_i */
1330 
1331 static sf_count_t
ogg_opus_write_f(SF_PRIVATE * psf,const float * ptr,sf_count_t len)1332 ogg_opus_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t len)
1333 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1334 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1335 	sf_count_t total ;
1336 	int writelen ;
1337 
1338 	if (oopus->u.encode.lsb < 24)
1339 		oopus->u.encode.lsb = 24 ;
1340 
1341 	for (total = 0 ; total < len ; )
1342 	{	if (oopus->loc >= oopus->len)
1343 		{	/* Need to encode the buffer */
1344 			if (ogg_opus_write_out (psf, odata, oopus) <= 0)
1345 				return total ;
1346 			} ;
1347 
1348 		writelen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1349 		if (writelen)
1350 		{	memcpy (&(oopus->buffer [oopus->loc * psf->sf.channels]), &(ptr [total]), sizeof (float) * writelen) ;
1351 			total += writelen ;
1352 			oopus->loc += (writelen / psf->sf.channels) ;
1353 			} ;
1354 		} ;
1355 	return total ;
1356 } /* ogg_opus_write_f */
1357 
1358 static sf_count_t
ogg_opus_write_d(SF_PRIVATE * psf,const double * ptr,sf_count_t len)1359 ogg_opus_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t len)
1360 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1361 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1362 	sf_count_t total, i ;
1363 	int writelen ;
1364 	float *optr ;
1365 
1366 	if (oopus->u.encode.lsb < 24)
1367 		oopus->u.encode.lsb = 24 ;
1368 
1369 	for (total = 0 ; total < len ; )
1370 	{	if (oopus->loc >= oopus->len)
1371 		{	/* Need to encode the buffer */
1372 			if (ogg_opus_write_out (psf, odata, oopus) <= 0)
1373 				return total ;
1374 			} ;
1375 
1376 		writelen = SF_MIN (len - total, (sf_count_t) (oopus->len - oopus->loc) * psf->sf.channels) ;
1377 		if (writelen)
1378 		{	optr = oopus->buffer + oopus->loc * psf->sf.channels ;
1379 			i = total ;
1380 			total += writelen ;
1381 			for ( ; i < total ; i++)
1382 			{	*optr++ = (float) (ptr [i]) ;
1383 				} ;
1384 			oopus->loc += (writelen / psf->sf.channels) ;
1385 			} ;
1386 		} ;
1387 	return total ;
1388 } /* ogg_opus_write_d */
1389 
1390 static int
ogg_opus_analyze_file(SF_PRIVATE * psf)1391 ogg_opus_analyze_file (SF_PRIVATE *psf)
1392 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1393 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1394 	uint64_t gp ;
1395 	sf_count_t saved_offset, last_page ;
1396 	int error ;
1397 
1398 	psf->sf.sections = 1 ;
1399 	psf->sf.frames	= SF_COUNT_MAX ;
1400 	oopus->u.decode.gp_end = (uint64_t) -1 ;
1401 	oopus->u.decode.last_offset = SF_COUNT_MAX ;
1402 
1403 	psf->dataoffset = ogg_sync_ftell (psf) ;
1404 	if (psf->filelength != SF_COUNT_MAX)
1405 		psf->datalength = psf->filelength - psf->dataoffset ;
1406 	else
1407 		psf->datalength = SF_COUNT_MAX ;
1408 
1409 	/*
1410 	** Calculate the start granule position offset
1411 	**
1412 	** OggOpus streams are allowed to start with a granule position other than
1413 	** zero. This allows for cutting the beginning off of streams without
1414 	** having to modify all following granule positions, or for recording/
1415 	** joining a live stream in the middle. To figure out the offset, we need
1416 	** to sum up how many samples are in all the packets that complete in the
1417 	** page and subtract it from the page granule position.
1418 	**
1419 	** If this is the last page of the steam (EOS set), this is not possible,
1420 	** as the granule position may be /less/ than the number of samples, to
1421 	** indicate how many samples are end-padding. In this case the granule
1422 	** position offset of the file must be 0, as otherwise it is considered
1423 	** malformed.
1424 	*/
1425 	error = ogg_opus_unpack_next_page (psf, odata, oopus) ;
1426 	if (error < 0 && psf->error)
1427 		return psf->error ;
1428 
1429 	gp = ogg_opus_calculate_page_duration (odata) ;
1430 	if (gp <= 0)
1431 	{	psf_log_printf (psf, "Opus : Page duration of zero!\n") ;
1432 		return SFE_MALFORMED_FILE ;
1433 		} ;
1434 
1435 	if (!ogg_page_eos (&odata->opage))
1436 	{	if (gp > oopus->pg_pos)
1437 		{	psf_log_printf (psf, "Opus : First data page's granule position is less than total number of samples on the page!\n") ;
1438 			return SFE_MALFORMED_FILE ;
1439 			}
1440 		oopus->pkt_pos = oopus->pg_pos - gp ;
1441 		}
1442 	else if (gp < oopus->pg_pos)
1443 	{	psf_log_printf (psf, "Opus : First data page is also the last, and granule position has an (ambigious) offset.\n") ;
1444 		return SFE_MALFORMED_FILE ;
1445 		} ;
1446 	oopus->u.decode.gp_start = oopus->pkt_pos ;
1447 
1448 	if (!psf->sf.seekable)
1449 		return 0 ;
1450 
1451 	/*
1452 	** Find the last page and fetch the last granule position.
1453 	** First, save were we are now.
1454 	*/
1455 	saved_offset = ogg_sync_ftell (psf) ;
1456 
1457 	/* This uses the sync page buffer, the stream page buffer is untouched. */
1458 	last_page = ogg_sync_last_page_before (psf, odata, &oopus->u.decode.gp_end, psf->filelength, oopus->serialno) ;
1459 	if (last_page > 0)
1460 	{	if (!ogg_page_eos (&odata->opage))
1461 			psf_log_printf (psf, "Ogg : Last page lacks an end-of-stream bit.\n") ;
1462 		if (last_page + odata->opage.header_len + odata->opage.body_len < psf->filelength)
1463 			psf_log_printf (psf, "Ogg : Junk after the last page.\n") ;
1464 		oopus->u.decode.last_offset = last_page ;
1465 
1466 		if (oopus->u.decode.gp_end != (uint64_t) -1)
1467 		{	psf->sf.frames = (oopus->u.decode.gp_end - oopus->u.decode.gp_start
1468 				- oopus->header.preskip) / oopus->sr_factor ;
1469 			} ;
1470 	}
1471 
1472 	/* Go back to where we left off. */
1473 	ogg_sync_fseek (psf, saved_offset, SEEK_SET) ;
1474 	return 0 ;
1475 } /* ogg_opus_analyze_file */
1476 
1477 /*
1478 ** ogg_opus_seek_null_read
1479 **
1480 ** Decode samples, doing nothing with them, until the desired granule position
1481 ** is reached.
1482 */
1483 static sf_count_t
ogg_opus_seek_null_read(SF_PRIVATE * psf,sf_count_t offset)1484 ogg_opus_seek_null_read (SF_PRIVATE *psf, sf_count_t offset)
1485 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1486 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1487 	sf_count_t total ;
1488 	sf_count_t readlen ;
1489 
1490 	total = oopus->pkt_pos / oopus->sr_factor ;
1491 	total += oopus->loc ;
1492 
1493 	for ( ; total < offset ; )
1494 	{	if (oopus->loc == oopus->len)
1495 		{	if (ogg_opus_read_refill (psf, odata, oopus) <= 0)
1496 				return total ;
1497 			/*
1498 			** Ignore pre-skip skipping. The preskip was accounted for in the
1499 			** arugment to offset, so we need to count it.
1500 			*/
1501 			oopus->loc = 0 ;
1502 			} ;
1503 
1504 		readlen = SF_MIN ((int) (offset - total), (oopus->len - oopus->loc)) ;
1505 		if (readlen > 0)
1506 		{	total += readlen ;
1507 			oopus->loc += readlen ;
1508 			} ;
1509 		} ;
1510 	return total ;
1511 } /* ogg_opus_seek_null_read */
1512 
1513 /*
1514 ** Search within the file for the page with the highest granule position at or
1515 ** before our target.
1516 */
1517 static int
ogg_opus_seek_page_search(SF_PRIVATE * psf,uint64_t target_gp)1518 ogg_opus_seek_page_search (SF_PRIVATE *psf, uint64_t target_gp)
1519 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1520 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1521 	uint64_t pcm_start ;
1522 	uint64_t pcm_end ;
1523 	uint64_t best_gp ;
1524 	sf_count_t begin ;
1525 	sf_count_t end ;
1526 	int ret ;
1527 
1528 	best_gp = pcm_start = oopus->u.decode.gp_start ;
1529 	pcm_end = oopus->u.decode.gp_end ;
1530 	begin = psf->dataoffset ;
1531 
1532 	/* Adjust the target to give time to converge. */
1533 	if (target_gp >= OGG_OPUS_PREROLL)
1534 		target_gp -= OGG_OPUS_PREROLL ;
1535 	if (target_gp < pcm_start)
1536 		target_gp = pcm_start ;
1537 
1538 	/* Seek to beginning special case */
1539 	if (target_gp < pcm_start + (uint64_t) oopus->header.preskip)
1540 		end = begin ;
1541 	else
1542 		end = oopus->u.decode.last_offset ;
1543 
1544 	ogg_stream_seek_page_search (psf, odata, target_gp, pcm_start, pcm_end, &best_gp, begin, end) ;
1545 
1546 	oopus->loc = 0 ;
1547 	oopus->len = 0 ;
1548 	if ((ret = ogg_opus_unpack_next_page (psf, odata, oopus)) != 1)
1549 		return ret ;
1550 	oopus->pkt_pos = best_gp ;
1551 	opus_multistream_decoder_ctl (oopus->u.decode.state, OPUS_RESET_STATE) ;
1552 	/* Gain decoder settings survive resets. */
1553 
1554 	return 0 ;
1555 } /* ogg_opus_seek_page_search */
1556 
1557 static sf_count_t
ogg_opus_seek_manual(SF_PRIVATE * psf,uint64_t target_gp)1558 ogg_opus_seek_manual (SF_PRIVATE *psf, uint64_t target_gp)
1559 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1560 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1561 	sf_count_t pos ;
1562 	int nn ;
1563 
1564 	if (target_gp > OGG_OPUS_PREROLL)
1565 		target_gp -= OGG_OPUS_PREROLL ;
1566 	if (target_gp < oopus->pg_pos)
1567 		target_gp = oopus->pg_pos ;
1568 
1569 	if (oopus->pg_pos > target_gp)
1570 	{	ogg_stream_reset (&odata->ostream) ;
1571 		pos = ogg_sync_fseek (psf, psf->dataoffset, SEEK_SET) ;
1572 		if (pos < 0)
1573 			return pos ;
1574 		oopus->pg_pos = oopus->u.decode.gp_start ;
1575 		opus_multistream_decoder_ctl (oopus->u.decode.state, OPUS_RESET_STATE) ;
1576 		} ;
1577 
1578 	while (oopus->pg_pos < target_gp)
1579 	{	nn = ogg_opus_unpack_next_page (psf, odata, oopus) ;
1580 		if (nn <= 0)
1581 			return nn ;
1582 		} ;
1583 
1584 	return 1 ;
1585 } /* ogg_opus_seek_manual */
1586 
1587 static sf_count_t
ogg_opus_seek(SF_PRIVATE * psf,int mode,sf_count_t offset)1588 ogg_opus_seek (SF_PRIVATE *psf, int mode, sf_count_t offset)
1589 {	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1590 	uint64_t target_gp ;
1591 	uint64_t current ;
1592 	int ret ;
1593 
1594 	/* Only support seeking in read mode. */
1595 	if (mode != SFM_READ || psf->file.mode != SFM_READ)
1596 	{	psf->error = SFE_BAD_SEEK ;
1597 		return PSF_SEEK_ERROR ;
1598 		} ;
1599 
1600 	current = oopus->pkt_pos + oopus->loc * oopus->sr_factor ;
1601 	/*
1602 	** Remember, there are preskip granulepos worth of samples at the front of
1603 	** the stream which are bunk. Also, granule positions can be offset.
1604 	*/
1605 	target_gp = offset * oopus->sr_factor + oopus->u.decode.gp_start + oopus->header.preskip ;
1606 
1607 	if (oopus->u.decode.gp_end == (uint64_t) -1)
1608 	{	/*
1609 		** Don't know the end of the file. Could be a chained file we don't yet
1610 		** support. Oh well, just do it manually.
1611 		*/
1612 		ogg_opus_seek_manual (psf, target_gp) ;
1613 		}
1614 	else
1615 	{	/*
1616 		** Avoid seeking in the file if where we want is just ahead or exactly
1617 		** were we are. To avoid needing to flush the decoder we choose pre-
1618 		** roll plus 10ms.
1619 		*/
1620 		if (target_gp < current || target_gp - current > OGG_OPUS_PREROLL + 10 * 48)
1621 		{	ret = ogg_opus_seek_page_search (psf, target_gp) ;
1622 			if (ret < 0)
1623 			{	/*
1624 				** Page seek failed, what to do? Could be bad data. We can
1625 				** either fall-back to manual seeking or bail. Manaul seeking
1626 				** from the beginning has the advantage of finding where the
1627 				** file goes bad.
1628 				*/
1629 				ret = ogg_opus_seek_manual (psf, target_gp) ;
1630 				if (ret < 0)
1631 				{	/*
1632 					** If were here, and there is no error, we can be pretty
1633 					** sure that it's the file that is to blame.
1634 					*/
1635 					if (!psf->error)
1636 						psf->error = SFE_MALFORMED_FILE ;
1637 					return ret ;
1638 					} ;
1639 				} ;
1640 			} ;
1641 		} ;
1642 
1643 	/*
1644 	** We've seeked or skipped through pages until just before our target,
1645 	** now decode until we hit it.
1646 	*/
1647 	offset = ogg_opus_seek_null_read (psf, target_gp / oopus->sr_factor) ;
1648 	return offset - ((oopus->header.preskip + oopus->u.decode.gp_start) / oopus->sr_factor) ;
1649 
1650 } /* ogg_opus_seek */
1651 
1652 static int
ogg_opus_command(SF_PRIVATE * psf,int command,void * data,int datasize)1653 ogg_opus_command (SF_PRIVATE *psf, int command, void *data, int datasize)
1654 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1655 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1656 	double quality ;
1657 	double latency ;
1658 	int error ;
1659 
1660 	switch (command)
1661 	{	case SFC_SET_CHANNEL_MAP_INFO :
1662 			/* TODO: figure this out */
1663 			break ;
1664 
1665 		case SFC_SET_OGG_PAGE_LATENCY :
1666 			/*
1667 			** Argument: double, range 50 to 1600.
1668 			** Average length of OGG page in ms.
1669 			** This length drive the flush of pages.
1670 			*/
1671 			if (data == NULL || datasize != SIGNED_SIZEOF (double))
1672 				return SFE_BAD_COMMAND_PARAM ;
1673 
1674 			latency = *((double *) data) ;
1675 			if (latency < 50)
1676 				latency = 50 ;
1677 
1678 			if (latency > 1600)
1679 				latency = 1600 ;
1680 
1681 			oopus->u.encode.latency = ((unsigned long) latency) * 48 ;
1682 			break ;
1683 
1684 		case SFC_SET_COMPRESSION_LEVEL :
1685 			/*
1686 			** Argument: double, range 0.0 (lest compressed, best quality) to
1687 			** 1.0 (most compressed, worst quality)
1688 			*/
1689 			if (data == NULL || datasize != SIGNED_SIZEOF (double))
1690 				return SFE_BAD_COMMAND_PARAM ;
1691 
1692 			/* Usable bitrate range is  [6, 256] kbps per channel. */
1693 			quality = *((double *) data) ;
1694 			oopus->u.encode.bitrate = (int) (((1.0 - quality) * (250000.0)) + 6000.0) * psf->sf.channels ;
1695 			if (opus_multistream_encoder_ctl (oopus->u.encode.state, OPUS_SET_BITRATE (oopus->u.encode.bitrate)) == OPUS_OK)
1696 			{	psf_log_printf (psf, "User changed encoding target bitrate to %dbps\n", oopus->u.encode.bitrate) ;
1697 				return SF_TRUE ;
1698 				}
1699 			psf_log_printf (psf, "Failed to set user encoding target bitrate of %dbps\n", oopus->u.encode.bitrate) ;
1700 			return SF_FALSE ;
1701 			break ;
1702 
1703 		case SFC_SET_ORIGINAL_SAMPLERATE :
1704 			if (data == NULL || datasize != SIGNED_SIZEOF (int))
1705 				return SFE_BAD_COMMAND_PARAM ;
1706 			/*
1707 			** Only allow changing the input samplerate if at the beginning
1708 			** of the stream, because while it might be possible to change
1709 			** samplerate mid-decode, or to re-write the header for encode,
1710 			** ain't nobody got time to implement and test that.
1711 			*/
1712 			if (psf->file.mode == SFM_WRITE)
1713 			{	if (psf->have_written)
1714 					return SF_FALSE ;
1715 				oopus->header.input_samplerate = *((int *) data) ;
1716 				}
1717 			else {
1718 				if (oopus->pkt_pos > oopus->u.decode.gp_start || oopus->loc > 0)
1719 					return SF_FALSE ;
1720 				if ((error = ogg_opus_setup_decoder (psf, *((int *) data))))
1721 					return error ;
1722 				odata->pkt_indx = 0 ;
1723 				/* Adjust file frames count. */
1724 				if (oopus->u.decode.gp_end != (uint64_t) -1)
1725 					psf->sf.frames = (oopus->u.decode.gp_end - oopus->u.decode.gp_start
1726 						- oopus->header.preskip) / oopus->sr_factor ;
1727 				} ;
1728 			return SF_TRUE ;
1729 
1730 		case SFC_GET_ORIGINAL_SAMPLERATE :
1731 			if (data == NULL || datasize != SIGNED_SIZEOF (int))
1732 				return SFE_BAD_COMMAND_PARAM ;
1733 			*((int *) data) = oopus->header.input_samplerate ;
1734 			return SF_TRUE ;
1735 
1736 		default :
1737 			break ;
1738 	}
1739 
1740 	return SF_FALSE ;
1741 } /* ogg_opus_command */
1742 
1743 static int
ogg_opus_byterate(SF_PRIVATE * psf)1744 ogg_opus_byterate (SF_PRIVATE *psf)
1745 {	OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ;
1746 	OPUS_PRIVATE *oopus = (OPUS_PRIVATE *) psf->codec_data ;
1747 
1748 	if (psf->file.mode == SFM_READ)
1749 	{	if (odata->pkt_indx == odata->pkt_len)
1750 		{	if (ogg_opus_unpack_next_page (psf, odata, oopus) < 0)
1751 				return -1 ;
1752 			} ;
1753 
1754 		if (odata->pkt_indx < odata->pkt_len)
1755 		{	ogg_packet *ppkt = &odata->pkt [odata->pkt_indx] ;
1756 			return (ppkt->bytes * 8000) / opus_packet_get_nb_samples (ppkt->packet, ppkt->bytes, 8000) ;
1757 			} ;
1758 
1759 		if (psf->datalength != SF_COUNT_MAX)
1760 			return (psf->datalength * psf->sf.samplerate) / psf->sf.frames ;
1761 		} ;
1762 
1763 	if (psf->file.mode == SFM_WRITE && oopus->u.encode.state != NULL)
1764 		return (oopus->u.encode.bitrate + 7) / 8 ;
1765 
1766 	return -1 ;
1767 } /* ogg_opus_byterate */
1768 
1769 #else /* HAVE_EXTERNAL_XIPH_LIBS */
1770 
1771 int
ogg_opus_open(SF_PRIVATE * psf)1772 ogg_opus_open (SF_PRIVATE *psf)
1773 {
1774 	psf_log_printf (psf, "This version of libsndfile was compiled without Ogg/Opus support.\n") ;
1775 	return SFE_UNIMPLEMENTED ;
1776 } /* ogg_opus_open */
1777 
1778 #endif
1779