• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ** Copyright (C) 2004-2017 Erik de Castro Lopo <erikd@mega-nerd.com>
3 ** Copyright (C) 2004 Tobias Gehrig <tgehrig@ira.uka.de>
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 #include	"sfconfig.h"
21 
22 #include	<stdio.h>
23 #include	<stdlib.h>
24 #include	<fcntl.h>
25 #include	<string.h>
26 #include	<ctype.h>
27 #include	<math.h>
28 
29 #include	"sndfile.h"
30 #include	"common.h"
31 
32 #if HAVE_EXTERNAL_XIPH_LIBS
33 
34 #include	<FLAC/stream_decoder.h>
35 #include	<FLAC/stream_encoder.h>
36 #include	<FLAC/metadata.h>
37 
38 /*------------------------------------------------------------------------------
39 ** Private static functions.
40 */
41 
42 #define	FLAC_DEFAULT_COMPRESSION_LEVEL	5
43 
44 #define ENC_BUFFER_SIZE 8192
45 
46 /*
47 ** READ_LOOP_MAX_LEN is the maximum 'len' that will be passed to
48 ** flac_read_loop().  This is somewhat arbitrary, but must be less
49 ** than (UINT_MAX - FLAC__MAX_CHANNELS * FLAC__MAX_BLOCK_SIZE) to
50 ** avoid overflows, and must also be a multiple of the number of
51 ** channels (which is between 1 and 8.)
52 */
53 #define READ_LOOP_MAX_LEN (0x10000 * 3 * 5 * 7)
54 
55 typedef enum
56 {	PFLAC_PCM_SHORT = 50,
57 	PFLAC_PCM_INT = 51,
58 	PFLAC_PCM_FLOAT = 52,
59 	PFLAC_PCM_DOUBLE = 53
60 } PFLAC_PCM ;
61 
62 typedef struct
63 {
64 	FLAC__StreamDecoder *fsd ;
65 	FLAC__StreamEncoder *fse ;
66 
67 	PFLAC_PCM pcmtype ;
68 	void* ptr ;
69 	unsigned pos, len, remain ;
70 
71 	FLAC__StreamMetadata *metadata ;
72 
73 	const int32_t * const * wbuffer ;
74 	int32_t * rbuffer [FLAC__MAX_CHANNELS] ;
75 
76 	int32_t* encbuffer ;
77 	unsigned bufferpos ;
78 
79 	const FLAC__Frame *frame ;
80 
81 	unsigned compression ;
82 
83 } FLAC_PRIVATE ;
84 
85 typedef struct
86 {	const char *tag ;
87 	int type ;
88 } FLAC_TAG ;
89 
90 static sf_count_t	flac_seek (SF_PRIVATE *psf, int mode, sf_count_t offset) ;
91 static int			flac_byterate (SF_PRIVATE *psf) ;
92 static int			flac_close (SF_PRIVATE *psf) ;
93 
94 static int			flac_enc_init (SF_PRIVATE *psf) ;
95 static int			flac_read_header (SF_PRIVATE *psf) ;
96 
97 static sf_count_t	flac_read_flac2s (SF_PRIVATE *psf, short *ptr, sf_count_t len) ;
98 static sf_count_t	flac_read_flac2i (SF_PRIVATE *psf, int *ptr, sf_count_t len) ;
99 static sf_count_t	flac_read_flac2f (SF_PRIVATE *psf, float *ptr, sf_count_t len) ;
100 static sf_count_t	flac_read_flac2d (SF_PRIVATE *psf, double *ptr, sf_count_t len) ;
101 
102 static sf_count_t	flac_write_s2flac (SF_PRIVATE *psf, const short *ptr, sf_count_t len) ;
103 static sf_count_t	flac_write_i2flac (SF_PRIVATE *psf, const int *ptr, sf_count_t len) ;
104 static sf_count_t	flac_write_f2flac (SF_PRIVATE *psf, const float *ptr, sf_count_t len) ;
105 static sf_count_t	flac_write_d2flac (SF_PRIVATE *psf, const double *ptr, sf_count_t len) ;
106 
107 static void		f2flac8_array (const float *src, int32_t *dest, int count, int normalize) ;
108 static void		f2flac16_array (const float *src, int32_t *dest, int count, int normalize) ;
109 static void		f2flac24_array (const float *src, int32_t *dest, int count, int normalize) ;
110 static void		f2flac8_clip_array (const float *src, int32_t *dest, int count, int normalize) ;
111 static void		f2flac16_clip_array (const float *src, int32_t *dest, int count, int normalize) ;
112 static void		f2flac24_clip_array (const float *src, int32_t *dest, int count, int normalize) ;
113 static void		d2flac8_array (const double *src, int32_t *dest, int count, int normalize) ;
114 static void		d2flac16_array (const double *src, int32_t *dest, int count, int normalize) ;
115 static void		d2flac24_array (const double *src, int32_t *dest, int count, int normalize) ;
116 static void		d2flac8_clip_array (const double *src, int32_t *dest, int count, int normalize) ;
117 static void		d2flac16_clip_array (const double *src, int32_t *dest, int count, int normalize) ;
118 static void		d2flac24_clip_array (const double *src, int32_t *dest, int count, int normalize) ;
119 
120 static int flac_command (SF_PRIVATE *psf, int command, void *data, int datasize) ;
121 
122 /* Decoder Callbacks */
123 static FLAC__StreamDecoderReadStatus sf_flac_read_callback (const FLAC__StreamDecoder *decoder, FLAC__byte buffer [], size_t *bytes, void *client_data) ;
124 static FLAC__StreamDecoderSeekStatus sf_flac_seek_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) ;
125 static FLAC__StreamDecoderTellStatus sf_flac_tell_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) ;
126 static FLAC__StreamDecoderLengthStatus sf_flac_length_callback (const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) ;
127 static FLAC__bool sf_flac_eof_callback (const FLAC__StreamDecoder *decoder, void *client_data) ;
128 static FLAC__StreamDecoderWriteStatus sf_flac_write_callback (const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data) ;
129 static void sf_flac_meta_callback (const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data) ;
130 static void sf_flac_error_callback (const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data) ;
131 
132 /* Encoder Callbacks */
133 static FLAC__StreamEncoderSeekStatus sf_flac_enc_seek_callback (const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) ;
134 static FLAC__StreamEncoderTellStatus sf_flac_enc_tell_callback (const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) ;
135 static FLAC__StreamEncoderWriteStatus sf_flac_enc_write_callback (const FLAC__StreamEncoder *encoder, const FLAC__byte buffer [], size_t bytes, unsigned samples, unsigned current_frame, void *client_data) ;
136 
137 static void
s2flac8_array(const short * src,int32_t * dest,int count)138 s2flac8_array (const short *src, int32_t *dest, int count)
139 {	for (int i = 0 ; i < count ; i++)
140 		dest [i] = src [i] >> 8 ;
141 } /* s2flac8_array */
142 
143 static void
s2flac16_array(const short * src,int32_t * dest,int count)144 s2flac16_array (const short *src, int32_t *dest, int count)
145 {	for (int i = 0 ; i < count ; i++)
146 		dest [i] = src [i] ;
147 } /* s2flac16_array */
148 
149 static void
s2flac24_array(const short * src,int32_t * dest,int count)150 s2flac24_array (const short *src, int32_t *dest, int count)
151 {	for (int i = 0 ; i < count ; i++)
152 		dest [i] = src [i] << 8 ;
153 } /* s2flac24_array */
154 
155 static void
i2flac8_array(const int * src,int32_t * dest,int count)156 i2flac8_array (const int *src, int32_t *dest, int count)
157 {	for (int i = 0 ; i < count ; i++)
158 		dest [i] = src [i] >> 24 ;
159 } /* i2flac8_array */
160 
161 static void
i2flac16_array(const int * src,int32_t * dest,int count)162 i2flac16_array (const int *src, int32_t *dest, int count)
163 {
164 	for (int i = 0 ; i < count ; i++)
165 		dest [i] = src [i] >> 16 ;
166 } /* i2flac16_array */
167 
168 static void
i2flac24_array(const int * src,int32_t * dest,int count)169 i2flac24_array (const int *src, int32_t *dest, int count)
170 {	for (int i = 0 ; i < count ; i++)
171 		dest [i] = src [i] >> 8 ;
172 } /* i2flac24_array */
173 
174 static sf_count_t
flac_buffer_copy(SF_PRIVATE * psf)175 flac_buffer_copy (SF_PRIVATE *psf)
176 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
177 	const FLAC__Frame *frame = pflac->frame ;
178 	const int32_t* const *buffer = pflac->wbuffer ;
179 	unsigned i = 0, j, offset, channels, len ;
180 
181 	if (psf->sf.channels != (int) frame->header.channels)
182 	{	psf_log_printf (psf, "Error: FLAC frame changed from %d to %d channels\n"
183 									"Nothing to do but to error out.\n" ,
184 									psf->sf.channels, frame->header.channels) ;
185 		psf->error = SFE_FLAC_CHANNEL_COUNT_CHANGED ;
186 		return 0 ;
187 		} ;
188 
189 	/*
190 	**	frame->header.blocksize is variable and we're using a constant blocksize
191 	**	of FLAC__MAX_BLOCK_SIZE.
192 	**	Check our assumptions here.
193 	*/
194 	if (frame->header.blocksize > FLAC__MAX_BLOCK_SIZE)
195 	{	psf_log_printf (psf, "Ooops : frame->header.blocksize (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.blocksize, FLAC__MAX_BLOCK_SIZE) ;
196 		psf->error = SFE_INTERNAL ;
197 		return 0 ;
198 		} ;
199 
200 	if (frame->header.channels > FLAC__MAX_CHANNELS)
201 		psf_log_printf (psf, "Ooops : frame->header.channels (%d) > FLAC__MAX_BLOCK_SIZE (%d)\n", __func__, __LINE__, frame->header.channels, FLAC__MAX_CHANNELS) ;
202 
203 	channels = SF_MIN (frame->header.channels, FLAC__MAX_CHANNELS) ;
204 
205 	if (pflac->ptr == NULL)
206 	{	/*
207 		** This pointer is reset to NULL each time the current frame has been
208 		** decoded. Somehow its used during encoding and decoding.
209 		*/
210 		for (i = 0 ; i < channels ; i++)
211 		{
212 			if (pflac->rbuffer [i] == NULL)
213 				pflac->rbuffer [i] = calloc (FLAC__MAX_BLOCK_SIZE, sizeof (int32_t)) ;
214 
215 			memcpy (pflac->rbuffer [i], buffer [i], frame->header.blocksize * sizeof (int32_t)) ;
216 			} ;
217 		pflac->wbuffer = (const int32_t* const*) pflac->rbuffer ;
218 
219 		return 0 ;
220 		} ;
221 
222 	len = SF_MIN (pflac->len, frame->header.blocksize) ;
223 
224 	if (pflac->remain % channels != 0)
225 	{	psf_log_printf (psf, "Error: pflac->remain %u    channels %u\n", pflac->remain, channels) ;
226 		return 0 ;
227 		} ;
228 
229 	switch (pflac->pcmtype)
230 	{	case PFLAC_PCM_SHORT :
231 			{	short *retpcm = (short*) pflac->ptr ;
232 				int shift = 16 - frame->header.bits_per_sample ;
233 				if (shift < 0)
234 				{	shift = abs (shift) ;
235 					for (i = 0 ; i < len && pflac->remain > 0 ; i++)
236 					{	offset = pflac->pos + i * channels ;
237 
238 						if (pflac->bufferpos >= frame->header.blocksize)
239 							break ;
240 
241 						if (offset + channels > pflac->len)
242 							break ;
243 
244 						for (j = 0 ; j < channels ; j++)
245 							retpcm [offset + j] = buffer [j][pflac->bufferpos] >> shift ;
246 						pflac->remain -= channels ;
247 						pflac->bufferpos ++ ;
248 						}
249 					}
250 				else
251 				{	for (i = 0 ; i < len && pflac->remain > 0 ; i++)
252 					{	offset = pflac->pos + i * channels ;
253 
254 						if (pflac->bufferpos >= frame->header.blocksize)
255 							break ;
256 
257 						if (offset + channels > pflac->len)
258 							break ;
259 
260 						for (j = 0 ; j < channels ; j++)
261 							retpcm [offset + j] = ((uint16_t) buffer [j][pflac->bufferpos]) << shift ;
262 
263 						pflac->remain -= channels ;
264 						pflac->bufferpos ++ ;
265 						} ;
266 					} ;
267 				} ;
268 			break ;
269 
270 		case PFLAC_PCM_INT :
271 			{	int *retpcm = (int*) pflac->ptr ;
272 				int shift = 32 - frame->header.bits_per_sample ;
273 				for (i = 0 ; i < len && pflac->remain > 0 ; i++)
274 				{	offset = pflac->pos + i * channels ;
275 
276 					if (pflac->bufferpos >= frame->header.blocksize)
277 						break ;
278 
279 					if (offset + channels > pflac->len)
280 						break ;
281 
282 					for (j = 0 ; j < channels ; j++)
283 						retpcm [offset + j] = ((uint32_t) buffer [j][pflac->bufferpos]) << shift ;
284 					pflac->remain -= channels ;
285 					pflac->bufferpos++ ;
286 					} ;
287 				} ;
288 			break ;
289 
290 		case PFLAC_PCM_FLOAT :
291 			{	float *retpcm = (float*) pflac->ptr ;
292 				float norm = (psf->norm_float == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
293 
294 				for (i = 0 ; i < len && pflac->remain > 0 ; i++)
295 				{	offset = pflac->pos + i * channels ;
296 
297 					if (pflac->bufferpos >= frame->header.blocksize)
298 						break ;
299 
300 					if (offset + channels > pflac->len)
301 						break ;
302 
303 					for (j = 0 ; j < channels ; j++)
304 						retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
305 					pflac->remain -= channels ;
306 					pflac->bufferpos++ ;
307 					} ;
308 				} ;
309 			break ;
310 
311 		case PFLAC_PCM_DOUBLE :
312 			{	double *retpcm = (double*) pflac->ptr ;
313 				double norm = (psf->norm_double == SF_TRUE) ? 1.0 / (1 << (frame->header.bits_per_sample - 1)) : 1.0 ;
314 
315 				for (i = 0 ; i < len && pflac->remain > 0 ; i++)
316 				{	offset = pflac->pos + i * channels ;
317 
318 					if (pflac->bufferpos >= frame->header.blocksize)
319 						break ;
320 
321 					if (offset + channels > pflac->len)
322 						break ;
323 
324 					for (j = 0 ; j < channels ; j++)
325 						retpcm [offset + j] = buffer [j][pflac->bufferpos] * norm ;
326 					pflac->remain -= channels ;
327 					pflac->bufferpos++ ;
328 					} ;
329 				} ;
330 			break ;
331 
332 		default :
333 			return 0 ;
334 		} ;
335 
336 	offset = i * channels ;
337 	pflac->pos += i * channels ;
338 
339 	return offset ;
340 } /* flac_buffer_copy */
341 
342 
343 static FLAC__StreamDecoderReadStatus
sf_flac_read_callback(const FLAC__StreamDecoder * UNUSED (decoder),FLAC__byte buffer[],size_t * bytes,void * client_data)344 sf_flac_read_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__byte buffer [], size_t *bytes, void *client_data)
345 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
346 
347 	*bytes = psf_fread (buffer, 1, *bytes, psf) ;
348 	if (*bytes > 0 && psf->error == 0)
349 		return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE ;
350 
351 	return FLAC__STREAM_DECODER_READ_STATUS_ABORT ;
352 } /* sf_flac_read_callback */
353 
354 static FLAC__StreamDecoderSeekStatus
sf_flac_seek_callback(const FLAC__StreamDecoder * UNUSED (decoder),FLAC__uint64 absolute_byte_offset,void * client_data)355 sf_flac_seek_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 absolute_byte_offset, void *client_data)
356 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
357 
358 	psf_fseek (psf, absolute_byte_offset, SEEK_SET) ;
359 	if (psf->error)
360 		return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR ;
361 
362 	return FLAC__STREAM_DECODER_SEEK_STATUS_OK ;
363 } /* sf_flac_seek_callback */
364 
365 static FLAC__StreamDecoderTellStatus
sf_flac_tell_callback(const FLAC__StreamDecoder * UNUSED (decoder),FLAC__uint64 * absolute_byte_offset,void * client_data)366 sf_flac_tell_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 *absolute_byte_offset, void *client_data)
367 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
368 
369 	*absolute_byte_offset = psf_ftell (psf) ;
370 	if (psf->error)
371 		return FLAC__STREAM_DECODER_TELL_STATUS_ERROR ;
372 
373 	return FLAC__STREAM_DECODER_TELL_STATUS_OK ;
374 } /* sf_flac_tell_callback */
375 
376 static FLAC__StreamDecoderLengthStatus
sf_flac_length_callback(const FLAC__StreamDecoder * UNUSED (decoder),FLAC__uint64 * stream_length,void * client_data)377 sf_flac_length_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__uint64 *stream_length, void *client_data)
378 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
379 
380 	if ((*stream_length = psf->filelength) == 0)
381 		return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR ;
382 
383 	return FLAC__STREAM_DECODER_LENGTH_STATUS_OK ;
384 } /* sf_flac_length_callback */
385 
386 static FLAC__bool
sf_flac_eof_callback(const FLAC__StreamDecoder * UNUSED (decoder),void * client_data)387 sf_flac_eof_callback (const FLAC__StreamDecoder *UNUSED (decoder), void *client_data)
388 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
389 
390 	if (psf_ftell (psf) == psf->filelength)
391 		return SF_TRUE ;
392 
393 	return SF_FALSE ;
394 } /* sf_flac_eof_callback */
395 
396 static FLAC__StreamDecoderWriteStatus
sf_flac_write_callback(const FLAC__StreamDecoder * UNUSED (decoder),const FLAC__Frame * frame,const int32_t * const buffer[],void * client_data)397 sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data)
398 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
399 	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
400 
401 	pflac->frame = frame ;
402 	pflac->bufferpos = 0 ;
403 
404 	pflac->wbuffer = buffer ;
405 
406 	flac_buffer_copy (psf) ;
407 
408 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;
409 } /* sf_flac_write_callback */
410 
411 static void
sf_flac_meta_get_vorbiscomments(SF_PRIVATE * psf,const FLAC__StreamMetadata * metadata)412 sf_flac_meta_get_vorbiscomments (SF_PRIVATE *psf, const FLAC__StreamMetadata *metadata)
413 {	static FLAC_TAG tags [] =
414 	{ 	{ "title", SF_STR_TITLE },
415 		{ "copyright", SF_STR_COPYRIGHT },
416 		{ "software", SF_STR_SOFTWARE },
417 		{ "artist", SF_STR_ARTIST },
418 		{ "comment", SF_STR_COMMENT },
419 		{ "date", SF_STR_DATE },
420 		{ "album", SF_STR_ALBUM },
421 		{ "license", SF_STR_LICENSE },
422 		{ "tracknumber", SF_STR_TRACKNUMBER },
423 		{ "genre", SF_STR_GENRE }
424 		} ;
425 
426 	const char *value, *cptr ;
427 	int k, tag_num ;
428 
429 	for (k = 0 ; k < ARRAY_LEN (tags) ; k++)
430 	{	tag_num = FLAC__metadata_object_vorbiscomment_find_entry_from (metadata, 0, tags [k].tag) ;
431 
432 		if (tag_num < 0)
433 			continue ;
434 
435 		value = (const char*) metadata->data.vorbis_comment.comments [tag_num].entry ;
436 		if ((cptr = strchr (value, '=')) != NULL)
437 			value = cptr + 1 ;
438 
439 		psf_log_printf (psf, "  %-12s : %s\n", tags [k].tag, value) ;
440 		psf_store_string (psf, tags [k].type, value) ;
441 		} ;
442 
443 	return ;
444 } /* sf_flac_meta_get_vorbiscomments */
445 
446 static void
sf_flac_meta_callback(const FLAC__StreamDecoder * UNUSED (decoder),const FLAC__StreamMetadata * metadata,void * client_data)447 sf_flac_meta_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__StreamMetadata *metadata, void *client_data)
448 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
449 	int bitwidth = 0 ;
450 
451 	switch (metadata->type)
452 	{	case FLAC__METADATA_TYPE_STREAMINFO :
453 			if (psf->sf.channels > 0 && psf->sf.channels != (int) metadata->data.stream_info.channels)
454 			{	psf_log_printf (psf, "Error: FLAC stream changed from %d to %d channels\n"
455 									"Nothing to do but to error out.\n" ,
456 									psf->sf.channels, metadata->data.stream_info.channels) ;
457 				psf->error = SFE_FLAC_CHANNEL_COUNT_CHANGED ;
458 				return ;
459 				} ;
460 
461 			if (psf->sf.channels > 0 && psf->sf.samplerate != (int) metadata->data.stream_info.sample_rate)
462 			{	psf_log_printf (psf, "Warning: FLAC stream changed sample rates from %d to %d.\n"
463 									"Carrying on as if nothing happened.",
464 									psf->sf.samplerate, metadata->data.stream_info.sample_rate) ;
465 				} ;
466 			psf->sf.channels = metadata->data.stream_info.channels ;
467 			psf->sf.samplerate = metadata->data.stream_info.sample_rate ;
468 			psf->sf.frames = metadata->data.stream_info.total_samples ;
469 
470 			psf_log_printf (psf, "FLAC Stream Metadata\n  Channels    : %d\n  Sample rate : %d\n", psf->sf.channels, psf->sf.samplerate) ;
471 
472 			if (psf->sf.frames == 0)
473 			{	psf_log_printf (psf, "  Frames      : 0 (bumping to SF_COUNT_MAX)\n") ;
474 				psf->sf.frames = SF_COUNT_MAX ;
475 				}
476 			else
477 				psf_log_printf (psf, "  Frames      : %D\n", psf->sf.frames) ;
478 
479 			switch (metadata->data.stream_info.bits_per_sample)
480 			{	case 8 :
481 					psf->sf.format |= SF_FORMAT_PCM_S8 ;
482 					bitwidth = 8 ;
483 					break ;
484 				case 16 :
485 					psf->sf.format |= SF_FORMAT_PCM_16 ;
486 					bitwidth = 16 ;
487 					break ;
488 				case 24 :
489 					psf->sf.format |= SF_FORMAT_PCM_24 ;
490 					bitwidth = 24 ;
491 					break ;
492 				default :
493 					psf_log_printf (psf, "sf_flac_meta_callback : bits_per_sample %d not yet implemented.\n", metadata->data.stream_info.bits_per_sample) ;
494 					break ;
495 				} ;
496 
497 			if (bitwidth > 0)
498 				psf_log_printf (psf, "  Bit width   : %d\n", bitwidth) ;
499 			break ;
500 
501 		case FLAC__METADATA_TYPE_VORBIS_COMMENT :
502 			psf_log_printf (psf, "Vorbis Comment Metadata\n") ;
503 			sf_flac_meta_get_vorbiscomments (psf, metadata) ;
504 			break ;
505 
506 		case FLAC__METADATA_TYPE_PADDING :
507 			psf_log_printf (psf, "Padding Metadata\n") ;
508 			break ;
509 
510 		case FLAC__METADATA_TYPE_APPLICATION :
511 			psf_log_printf (psf, "Application Metadata\n") ;
512 			break ;
513 
514 		case FLAC__METADATA_TYPE_SEEKTABLE :
515 			psf_log_printf (psf, "Seektable Metadata\n") ;
516 			break ;
517 
518 		case FLAC__METADATA_TYPE_CUESHEET :
519 			psf_log_printf (psf, "Cuesheet Metadata\n") ;
520 			break ;
521 
522 		case FLAC__METADATA_TYPE_PICTURE :
523 			psf_log_printf (psf, "Picture Metadata\n") ;
524 			break ;
525 
526 		case FLAC__METADATA_TYPE_UNDEFINED :
527 			psf_log_printf (psf, "Undefined Metadata\n") ;
528 			break ;
529 
530 		default :
531 			psf_log_printf (psf, "sf_flac_meta_callback : metadata-type %d not yet implemented.\n", metadata->type) ;
532 			break ;
533 		} ;
534 
535 	return ;
536 } /* sf_flac_meta_callback */
537 
538 static void
sf_flac_error_callback(const FLAC__StreamDecoder * UNUSED (decoder),FLAC__StreamDecoderErrorStatus status,void * client_data)539 sf_flac_error_callback (const FLAC__StreamDecoder * UNUSED (decoder), FLAC__StreamDecoderErrorStatus status, void *client_data)
540 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
541 
542 	psf_log_printf (psf, "ERROR : %s\n", FLAC__StreamDecoderErrorStatusString [status]) ;
543 
544 	switch (status)
545 	{	case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC :
546 			psf->error = SFE_FLAC_LOST_SYNC ;
547 			break ;
548 		case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER :
549 			psf->error = SFE_FLAC_BAD_HEADER ;
550 			break ;
551 		default :
552 			psf->error = SFE_FLAC_UNKOWN_ERROR ;
553 			break ;
554 		} ;
555 
556 	return ;
557 } /* sf_flac_error_callback */
558 
559 static FLAC__StreamEncoderSeekStatus
sf_flac_enc_seek_callback(const FLAC__StreamEncoder * UNUSED (encoder),FLAC__uint64 absolute_byte_offset,void * client_data)560 sf_flac_enc_seek_callback (const FLAC__StreamEncoder * UNUSED (encoder), FLAC__uint64 absolute_byte_offset, void *client_data)
561 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
562 
563 	psf_fseek (psf, absolute_byte_offset, SEEK_SET) ;
564 	if (psf->error)
565 		return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR ;
566 
567 	return FLAC__STREAM_ENCODER_SEEK_STATUS_OK ;
568 } /* sf_flac_enc_seek_callback */
569 
570 static FLAC__StreamEncoderTellStatus
sf_flac_enc_tell_callback(const FLAC__StreamEncoder * UNUSED (encoder),FLAC__uint64 * absolute_byte_offset,void * client_data)571 sf_flac_enc_tell_callback (const FLAC__StreamEncoder *UNUSED (encoder), FLAC__uint64 *absolute_byte_offset, void *client_data)
572 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
573 
574 	*absolute_byte_offset = psf_ftell (psf) ;
575 	if (psf->error)
576 		return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR ;
577 
578 	return FLAC__STREAM_ENCODER_TELL_STATUS_OK ;
579 } /* sf_flac_enc_tell_callback */
580 
581 static FLAC__StreamEncoderWriteStatus
sf_flac_enc_write_callback(const FLAC__StreamEncoder * UNUSED (encoder),const FLAC__byte buffer[],size_t bytes,unsigned UNUSED (samples),unsigned UNUSED (current_frame),void * client_data)582 sf_flac_enc_write_callback (const FLAC__StreamEncoder * UNUSED (encoder), const FLAC__byte buffer [], size_t bytes, unsigned UNUSED (samples), unsigned UNUSED (current_frame), void *client_data)
583 {	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
584 
585 	if (psf_fwrite (buffer, 1, bytes, psf) == (sf_count_t) bytes && psf->error == 0)
586 		return FLAC__STREAM_ENCODER_WRITE_STATUS_OK ;
587 
588 	return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR ;
589 } /* sf_flac_enc_write_callback */
590 
591 static void
flac_write_strings(SF_PRIVATE * psf,FLAC_PRIVATE * pflac)592 flac_write_strings (SF_PRIVATE *psf, FLAC_PRIVATE* pflac)
593 {	FLAC__StreamMetadata_VorbisComment_Entry entry ;
594 	int	k, string_count = 0 ;
595 
596 	for (k = 0 ; k < SF_MAX_STRINGS ; k++)
597 	{	if (psf->strings.data [k].type != 0)
598 			string_count ++ ;
599 		} ;
600 
601 	if (string_count == 0)
602 		return ;
603 
604 	if (pflac->metadata == NULL && (pflac->metadata = FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL)
605 	{	psf_log_printf (psf, "FLAC__metadata_object_new returned NULL\n") ;
606 		return ;
607 		} ;
608 
609 	for (k = 0 ; k < SF_MAX_STRINGS && psf->strings.data [k].type != 0 ; k++)
610 	{	const char * key, * value ;
611 
612 		switch (psf->strings.data [k].type)
613 		{	case SF_STR_SOFTWARE :
614 				key = "software" ;
615 				break ;
616 			case SF_STR_TITLE :
617 				key = "title" ;
618 				break ;
619 			case SF_STR_COPYRIGHT :
620 				key = "copyright" ;
621 				break ;
622 			case SF_STR_ARTIST :
623 				key = "artist" ;
624 				break ;
625 			case SF_STR_COMMENT :
626 				key = "comment" ;
627 				break ;
628 			case SF_STR_DATE :
629 				key = "date" ;
630 				break ;
631 			case SF_STR_ALBUM :
632 				key = "album" ;
633 				break ;
634 			case SF_STR_LICENSE :
635 				key = "license" ;
636 				break ;
637 			case SF_STR_TRACKNUMBER :
638 				key = "tracknumber" ;
639 				break ;
640 			case SF_STR_GENRE :
641 				key = "genre" ;
642 				break ;
643 			default :
644 				continue ;
645 			} ;
646 
647 		value = psf->strings.storage + psf->strings.data [k].offset ;
648 
649 		FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair (&entry, key, value) ;
650 		FLAC__metadata_object_vorbiscomment_append_comment (pflac->metadata, entry, /* copy */ SF_FALSE) ;
651 		} ;
652 
653 	if (! FLAC__stream_encoder_set_metadata (pflac->fse, &pflac->metadata, 1))
654 	{	printf ("%s %d : fail\n", __func__, __LINE__) ;
655 		return ;
656 		} ;
657 
658 	return ;
659 } /* flac_write_strings */
660 
661 static int
flac_write_header(SF_PRIVATE * psf,int UNUSED (calc_length))662 flac_write_header (SF_PRIVATE *psf, int UNUSED (calc_length))
663 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
664 	int err ;
665 
666 	flac_write_strings (psf, pflac) ;
667 
668 	if ((err = FLAC__stream_encoder_init_stream (pflac->fse, sf_flac_enc_write_callback, sf_flac_enc_seek_callback, sf_flac_enc_tell_callback, NULL, psf)) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
669 	{	psf_log_printf (psf, "Error : FLAC encoder init returned error : %s\n", FLAC__StreamEncoderInitStatusString [err]) ;
670 		return SFE_FLAC_INIT_DECODER ;
671 		} ;
672 
673 	if (psf->error == 0)
674 		psf->dataoffset = psf_ftell (psf) ;
675 	pflac->encbuffer = calloc (ENC_BUFFER_SIZE, sizeof (int32_t)) ;
676 
677 	/* can only call init_stream once */
678 	psf->write_header = NULL ;
679 
680 	return psf->error ;
681 } /* flac_write_header */
682 
683 /*------------------------------------------------------------------------------
684 ** Public function.
685 */
686 
687 int
flac_open(SF_PRIVATE * psf)688 flac_open	(SF_PRIVATE *psf)
689 {	int		subformat ;
690 	int		error = 0 ;
691 
692 	FLAC_PRIVATE* pflac = calloc (1, sizeof (FLAC_PRIVATE)) ;
693 	psf->codec_data = pflac ;
694 
695 	/* Set the default value here. Over-ridden later if necessary. */
696 	pflac->compression = FLAC_DEFAULT_COMPRESSION_LEVEL ;
697 
698 	if (psf->file.mode == SFM_RDWR)
699 		return SFE_BAD_MODE_RW ;
700 
701 	if (psf->file.mode == SFM_READ)
702 	{	if ((error = flac_read_header (psf)))
703 			return error ;
704 		} ;
705 
706 	subformat = SF_CODEC (psf->sf.format) ;
707 
708 	if (psf->file.mode == SFM_WRITE)
709 	{	if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_FLAC)
710 			return	SFE_BAD_OPEN_FORMAT ;
711 
712 		psf->endian = SF_ENDIAN_BIG ;
713 		psf->sf.seekable = 0 ;
714 
715 		psf->strings.flags = SF_STR_ALLOW_START ;
716 
717 		if ((error = flac_enc_init (psf)))
718 			return error ;
719 
720 		/* In an ideal world we would write the header at this point. Unfortunately
721 		** that would prevent string metadata being added so we have to hold off.
722 		*/
723 
724 		psf->write_header = flac_write_header ;
725 		} ;
726 
727 	psf->datalength = psf->filelength ;
728 	psf->dataoffset = 0 ;
729 
730 	psf->container_close = flac_close ;
731 	psf->seek = flac_seek ;
732 	psf->byterate = flac_byterate ;
733 
734 	psf->command = flac_command ;
735 
736 	switch (subformat)
737 	{	case SF_FORMAT_PCM_S8 :	/* 8-bit FLAC.  */
738 		case SF_FORMAT_PCM_16 :	/* 16-bit FLAC. */
739 		case SF_FORMAT_PCM_24 :	/* 24-bit FLAC. */
740 			error = flac_init (psf) ;
741 			break ;
742 
743 		default : return SFE_UNIMPLEMENTED ;
744 		} ;
745 
746 	return error ;
747 } /* flac_open */
748 
749 /*------------------------------------------------------------------------------
750 */
751 
752 static int
flac_close(SF_PRIVATE * psf)753 flac_close	(SF_PRIVATE *psf)
754 {	FLAC_PRIVATE* pflac ;
755 	int k ;
756 
757 	if ((pflac = (FLAC_PRIVATE*) psf->codec_data) == NULL)
758 		return 0 ;
759 
760 	if (pflac->metadata != NULL)
761 		FLAC__metadata_object_delete (pflac->metadata) ;
762 
763 	if (psf->file.mode == SFM_WRITE)
764 	{	FLAC__stream_encoder_finish (pflac->fse) ;
765 		FLAC__stream_encoder_delete (pflac->fse) ;
766 		free (pflac->encbuffer) ;
767 		} ;
768 
769 	if (psf->file.mode == SFM_READ)
770 	{	FLAC__stream_decoder_finish (pflac->fsd) ;
771 		FLAC__stream_decoder_delete (pflac->fsd) ;
772 		} ;
773 
774 	for (k = 0 ; k < ARRAY_LEN (pflac->rbuffer) ; k++)
775 		free (pflac->rbuffer [k]) ;
776 
777 	free (pflac) ;
778 	psf->codec_data = NULL ;
779 
780 	return 0 ;
781 } /* flac_close */
782 
783 static int
flac_enc_init(SF_PRIVATE * psf)784 flac_enc_init (SF_PRIVATE *psf)
785 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
786 	unsigned bps ;
787 
788 	/* To cite the flac FAQ at
789 	** http://flac.sourceforge.net/faq.html#general__samples
790 	**     "FLAC supports linear sample rates from 1Hz - 655350Hz in 1Hz
791 	**     increments."
792 	*/
793 	if (psf->sf.samplerate < 1 || psf->sf.samplerate > 655350)
794 	{	psf_log_printf (psf, "flac sample rate out of range.\n", psf->sf.samplerate) ;
795 		return SFE_FLAC_BAD_SAMPLE_RATE ;
796 		} ;
797 
798 	psf_fseek (psf, 0, SEEK_SET) ;
799 
800 	switch (SF_CODEC (psf->sf.format))
801 	{	case SF_FORMAT_PCM_S8 :
802 			bps = 8 ;
803 			break ;
804 		case SF_FORMAT_PCM_16 :
805 			bps = 16 ;
806 			break ;
807 		case SF_FORMAT_PCM_24 :
808 			bps = 24 ;
809 			break ;
810 
811 		default :
812 			bps = 0 ;
813 			break ;
814 		} ;
815 
816 	if (pflac->fse)
817 		FLAC__stream_encoder_delete (pflac->fse) ;
818 	if ((pflac->fse = FLAC__stream_encoder_new ()) == NULL)
819 		return SFE_FLAC_NEW_DECODER ;
820 
821 	if (! FLAC__stream_encoder_set_channels (pflac->fse, psf->sf.channels))
822 	{	psf_log_printf (psf, "FLAC__stream_encoder_set_channels (%d) return false.\n", psf->sf.channels) ;
823 		return SFE_FLAC_INIT_DECODER ;
824 		} ;
825 
826 	if (! FLAC__stream_encoder_set_sample_rate (pflac->fse, psf->sf.samplerate))
827 	{	psf_log_printf (psf, "FLAC__stream_encoder_set_sample_rate (%d) returned false.\n", psf->sf.samplerate) ;
828 		return SFE_FLAC_BAD_SAMPLE_RATE ;
829 		} ;
830 
831 	if (! FLAC__stream_encoder_set_bits_per_sample (pflac->fse, bps))
832 	{	psf_log_printf (psf, "FLAC__stream_encoder_set_bits_per_sample (%d) return false.\n", bps) ;
833 		return SFE_FLAC_INIT_DECODER ;
834 		} ;
835 
836 	if (! FLAC__stream_encoder_set_compression_level (pflac->fse, pflac->compression))
837 	{	psf_log_printf (psf, "FLAC__stream_encoder_set_compression_level (%d) return false.\n", pflac->compression) ;
838 		return SFE_FLAC_INIT_DECODER ;
839 		} ;
840 
841 	return 0 ;
842 } /* flac_enc_init */
843 
844 static int
flac_read_header(SF_PRIVATE * psf)845 flac_read_header (SF_PRIVATE *psf)
846 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
847 
848 	psf_fseek (psf, 0, SEEK_SET) ;
849 	if (pflac->fsd)
850 		FLAC__stream_decoder_delete (pflac->fsd) ;
851 	if ((pflac->fsd = FLAC__stream_decoder_new ()) == NULL)
852 		return SFE_FLAC_NEW_DECODER ;
853 
854 	FLAC__stream_decoder_set_metadata_respond_all (pflac->fsd) ;
855 
856 	if (FLAC__stream_decoder_init_stream (pflac->fsd, sf_flac_read_callback, sf_flac_seek_callback, sf_flac_tell_callback, sf_flac_length_callback, sf_flac_eof_callback, sf_flac_write_callback, sf_flac_meta_callback, sf_flac_error_callback, psf) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
857 		return SFE_FLAC_INIT_DECODER ;
858 
859 	FLAC__stream_decoder_process_until_end_of_metadata (pflac->fsd) ;
860 
861 	psf_log_printf (psf, "End\n") ;
862 
863 	if (psf->error != 0)
864 		FLAC__stream_decoder_delete (pflac->fsd) ;
865 	else
866 	{	FLAC__uint64 position ;
867 
868 		FLAC__stream_decoder_get_decode_position (pflac->fsd, &position) ;
869 		psf->dataoffset = position ;
870 		} ;
871 
872 	return psf->error ;
873 } /* flac_read_header */
874 
875 static int
flac_command(SF_PRIVATE * psf,int command,void * data,int datasize)876 flac_command (SF_PRIVATE * psf, int command, void * data, int datasize)
877 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
878 	double quality ;
879 
880 	switch (command)
881 	{	case SFC_SET_COMPRESSION_LEVEL :
882 			if (data == NULL || datasize != sizeof (double))
883 				return SF_FALSE ;
884 
885 			if (psf->have_written)
886 				return SF_FALSE ;
887 
888 			/* FLAC compression level is in the range [0, 8] while libsndfile takes
889 			** values in the range [0.0, 1.0]. Massage the libsndfile value here.
890 			*/
891 			quality = (*((double *) data)) * 8.0 ;
892 			/* Clip range. */
893 			pflac->compression = psf_lrint (SF_MAX (0.0, SF_MIN (8.0, quality))) ;
894 
895 			psf_log_printf (psf, "%s : Setting SFC_SET_COMPRESSION_LEVEL to %u.\n", __func__, pflac->compression) ;
896 
897 			if (flac_enc_init (psf))
898 				return SF_FALSE ;
899 
900 			return SF_TRUE ;
901 
902 		default :
903 			return SF_FALSE ;
904 		} ;
905 
906 	return SF_FALSE ;
907 } /* flac_command */
908 
909 int
flac_init(SF_PRIVATE * psf)910 flac_init (SF_PRIVATE *psf)
911 {
912 	if (psf->file.mode == SFM_RDWR)
913 		return SFE_BAD_MODE_RW ;
914 
915 	if (psf->file.mode == SFM_READ)
916 	{	psf->read_short		= flac_read_flac2s ;
917 		psf->read_int		= flac_read_flac2i ;
918 		psf->read_float		= flac_read_flac2f ;
919 		psf->read_double	= flac_read_flac2d ;
920 		} ;
921 
922 	if (psf->file.mode == SFM_WRITE)
923 	{	psf->write_short	= flac_write_s2flac ;
924 		psf->write_int		= flac_write_i2flac ;
925 		psf->write_float	= flac_write_f2flac ;
926 		psf->write_double	= flac_write_d2flac ;
927 		} ;
928 
929 	if (psf->filelength > psf->dataoffset)
930 		psf->datalength = (psf->dataend) ? psf->dataend - psf->dataoffset : psf->filelength - psf->dataoffset ;
931 	else
932 		psf->datalength = 0 ;
933 
934 	return 0 ;
935 } /* flac_init */
936 
937 static unsigned
flac_read_loop(SF_PRIVATE * psf,unsigned len)938 flac_read_loop (SF_PRIVATE *psf, unsigned len)
939 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
940 	FLAC__StreamDecoderState state ;
941 
942 	pflac->pos = 0 ;
943 	pflac->len = len ;
944 	pflac->remain = len ;
945 
946 	state = FLAC__stream_decoder_get_state (pflac->fsd) ;
947 	if (state > FLAC__STREAM_DECODER_END_OF_STREAM)
948 	{	psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
949 		/* Current frame is busted, so NULL the pointer. */
950 		pflac->frame = NULL ;
951 		} ;
952 
953 	/* First copy data that has already been decoded and buffered. */
954 	if (pflac->frame != NULL && pflac->bufferpos < pflac->frame->header.blocksize)
955 		flac_buffer_copy (psf) ;
956 
957 	/* Decode some more. */
958 	while (pflac->pos < pflac->len)
959 	{	if (FLAC__stream_decoder_process_single (pflac->fsd) == 0)
960 		{	psf_log_printf (psf, "FLAC__stream_decoder_process_single returned false\n") ;
961 			/* Current frame is busted, so NULL the pointer. */
962 			pflac->frame = NULL ;
963 			break ;
964 			} ;
965 		state = FLAC__stream_decoder_get_state (pflac->fsd) ;
966 		if (state >= FLAC__STREAM_DECODER_END_OF_STREAM)
967 		{	psf_log_printf (psf, "FLAC__stream_decoder_get_state returned %s\n", FLAC__StreamDecoderStateString [state]) ;
968 			/* Current frame is busted, so NULL the pointer. */
969 			pflac->frame = NULL ;
970 			break ;
971 			} ;
972 		} ;
973 
974 	pflac->ptr = NULL ;
975 
976 	return pflac->pos ;
977 } /* flac_read_loop */
978 
979 static sf_count_t
flac_read_flac2s(SF_PRIVATE * psf,short * ptr,sf_count_t len)980 flac_read_flac2s (SF_PRIVATE *psf, short *ptr, sf_count_t len)
981 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
982 	sf_count_t total = 0, current ;
983 	unsigned readlen ;
984 
985 	pflac->pcmtype = PFLAC_PCM_SHORT ;
986 
987 	while (total < len)
988 	{	pflac->ptr = ptr + total ;
989 		readlen = (len - total > READ_LOOP_MAX_LEN) ? READ_LOOP_MAX_LEN : (unsigned) (len - total) ;
990 		current = flac_read_loop (psf, readlen) ;
991 		if (current == 0)
992 			break ;
993 		total += current ;
994 		} ;
995 
996 	return total ;
997 } /* flac_read_flac2s */
998 
999 static sf_count_t
flac_read_flac2i(SF_PRIVATE * psf,int * ptr,sf_count_t len)1000 flac_read_flac2i (SF_PRIVATE *psf, int *ptr, sf_count_t len)
1001 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1002 	sf_count_t total = 0, current ;
1003 	unsigned readlen ;
1004 
1005 	pflac->pcmtype = PFLAC_PCM_INT ;
1006 
1007 	while (total < len)
1008 	{	pflac->ptr = ptr + total ;
1009 		readlen = (len - total > READ_LOOP_MAX_LEN) ? READ_LOOP_MAX_LEN : (unsigned) (len - total) ;
1010 		current = flac_read_loop (psf, readlen) ;
1011 		if (current == 0)
1012 			break ;
1013 		total += current ;
1014 		} ;
1015 
1016 	return total ;
1017 } /* flac_read_flac2i */
1018 
1019 static sf_count_t
flac_read_flac2f(SF_PRIVATE * psf,float * ptr,sf_count_t len)1020 flac_read_flac2f (SF_PRIVATE *psf, float *ptr, sf_count_t len)
1021 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1022 	sf_count_t total = 0, current ;
1023 	unsigned readlen ;
1024 
1025 	pflac->pcmtype = PFLAC_PCM_FLOAT ;
1026 
1027 	while (total < len)
1028 	{	pflac->ptr = ptr + total ;
1029 		readlen = (len - total > READ_LOOP_MAX_LEN) ? READ_LOOP_MAX_LEN : (unsigned) (len - total) ;
1030 		current = flac_read_loop (psf, readlen) ;
1031 		if (current == 0)
1032 			break ;
1033 		total += current ;
1034 		} ;
1035 
1036 	return total ;
1037 } /* flac_read_flac2f */
1038 
1039 static sf_count_t
flac_read_flac2d(SF_PRIVATE * psf,double * ptr,sf_count_t len)1040 flac_read_flac2d (SF_PRIVATE *psf, double *ptr, sf_count_t len)
1041 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1042 	sf_count_t total = 0, current ;
1043 	unsigned readlen ;
1044 
1045 	pflac->pcmtype = PFLAC_PCM_DOUBLE ;
1046 
1047 	while (total < len)
1048 	{	pflac->ptr = ptr + total ;
1049 		readlen = (len - total > READ_LOOP_MAX_LEN) ? READ_LOOP_MAX_LEN : (unsigned) (len - total) ;
1050 
1051 		current = flac_read_loop (psf, readlen) ;
1052 		if (current == 0)
1053 			break ;
1054 		total += current ;
1055 		} ;
1056 
1057 	return total ;
1058 } /* flac_read_flac2d */
1059 
1060 static sf_count_t
flac_write_s2flac(SF_PRIVATE * psf,const short * ptr,sf_count_t len)1061 flac_write_s2flac (SF_PRIVATE *psf, const short *ptr, sf_count_t len)
1062 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1063 	void (*convert) (const short *, int32_t *, int) ;
1064 	int bufferlen, writecount, thiswrite ;
1065 	sf_count_t	total = 0 ;
1066 	int32_t* buffer = pflac->encbuffer ;
1067 
1068 	switch (SF_CODEC (psf->sf.format))
1069 	{	case SF_FORMAT_PCM_S8 :
1070 			convert = s2flac8_array ;
1071 			break ;
1072 		case SF_FORMAT_PCM_16 :
1073 			convert = s2flac16_array ;
1074 			break ;
1075 		case SF_FORMAT_PCM_24 :
1076 			convert = s2flac24_array ;
1077 			break ;
1078 		default :
1079 			return -1 ;
1080 		} ;
1081 
1082 	bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
1083 	bufferlen *= psf->sf.channels ;
1084 
1085 	while (len > 0)
1086 	{	writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1087 		convert (ptr + total, buffer, writecount) ;
1088 		if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1089 			thiswrite = writecount ;
1090 		else
1091 			break ;
1092 		total += thiswrite ;
1093 		if (thiswrite < writecount)
1094 			break ;
1095 
1096 		len -= thiswrite ;
1097 		} ;
1098 
1099 	return total ;
1100 } /* flac_write_s2flac */
1101 
1102 static sf_count_t
flac_write_i2flac(SF_PRIVATE * psf,const int * ptr,sf_count_t len)1103 flac_write_i2flac (SF_PRIVATE *psf, const int *ptr, sf_count_t len)
1104 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1105 	void (*convert) (const int *, int32_t *, int) ;
1106 	int bufferlen, writecount, thiswrite ;
1107 	sf_count_t	total = 0 ;
1108 	int32_t* buffer = pflac->encbuffer ;
1109 
1110 	switch (SF_CODEC (psf->sf.format))
1111 	{	case SF_FORMAT_PCM_S8 :
1112 			convert = i2flac8_array ;
1113 			break ;
1114 		case SF_FORMAT_PCM_16 :
1115 			convert = i2flac16_array ;
1116 			break ;
1117 		case SF_FORMAT_PCM_24 :
1118 			convert = i2flac24_array ;
1119 			break ;
1120 		default :
1121 			return -1 ;
1122 		} ;
1123 
1124 	bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
1125 	bufferlen *= psf->sf.channels ;
1126 
1127 	while (len > 0)
1128 	{	writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1129 		convert (ptr + total, buffer, writecount) ;
1130 		if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1131 			thiswrite = writecount ;
1132 		else
1133 			break ;
1134 		total += thiswrite ;
1135 		if (thiswrite < writecount)
1136 			break ;
1137 
1138 		len -= thiswrite ;
1139 		} ;
1140 
1141 	return total ;
1142 } /* flac_write_i2flac */
1143 
1144 static sf_count_t
flac_write_f2flac(SF_PRIVATE * psf,const float * ptr,sf_count_t len)1145 flac_write_f2flac (SF_PRIVATE *psf, const float *ptr, sf_count_t len)
1146 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1147 	void (*convert) (const float *, int32_t *, int, int) ;
1148 	int bufferlen, writecount, thiswrite ;
1149 	sf_count_t	total = 0 ;
1150 	int32_t* buffer = pflac->encbuffer ;
1151 
1152 	switch (SF_CODEC (psf->sf.format))
1153 	{	case SF_FORMAT_PCM_S8 :
1154 			convert = (psf->add_clipping) ? f2flac8_clip_array : f2flac8_array ;
1155 			break ;
1156 		case SF_FORMAT_PCM_16 :
1157 			convert = (psf->add_clipping) ? f2flac16_clip_array : f2flac16_array ;
1158 			break ;
1159 		case SF_FORMAT_PCM_24 :
1160 			convert = (psf->add_clipping) ? f2flac24_clip_array : f2flac24_array ;
1161 			break ;
1162 		default :
1163 			return -1 ;
1164 		} ;
1165 
1166 	bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
1167 	bufferlen *= psf->sf.channels ;
1168 
1169 	while (len > 0)
1170 	{	writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1171 		convert (ptr + total, buffer, writecount, psf->norm_float) ;
1172 		if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1173 			thiswrite = writecount ;
1174 		else
1175 			break ;
1176 		total += thiswrite ;
1177 		if (thiswrite < writecount)
1178 			break ;
1179 
1180 		len -= thiswrite ;
1181 		} ;
1182 
1183 	return total ;
1184 } /* flac_write_f2flac */
1185 
1186 static void
f2flac8_clip_array(const float * src,int32_t * dest,int count,int normalize)1187 f2flac8_clip_array (const float *src, int32_t *dest, int count, int normalize)
1188 {	float normfact, scaled_value ;
1189 
1190 	normfact = normalize ? (8.0 * 0x10) : 1.0 ;
1191 
1192 	for (int i = 0 ; i < count ; i++)
1193 	{	scaled_value = src [i] * normfact ;
1194 		if (scaled_value >= (1.0 * 0x7F))
1195 		{	dest [i] = 0x7F ;
1196 			continue ;
1197 			} ;
1198 		if (scaled_value <= (-8.0 * 0x10))
1199 		{	dest [i] = -0x80 ;
1200 			continue ;
1201 			} ;
1202 		dest [i] = psf_lrintf (scaled_value) ;
1203 		} ;
1204 
1205 	return ;
1206 } /* f2flac8_clip_array */
1207 
1208 static void
f2flac16_clip_array(const float * src,int32_t * dest,int count,int normalize)1209 f2flac16_clip_array (const float *src, int32_t *dest, int count, int normalize)
1210 {	float normfact, scaled_value ;
1211 
1212 	normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
1213 
1214 	for (int i = 0 ; i < count ; i++)
1215 	{	scaled_value = src [i] * normfact ;
1216 		if (scaled_value >= (1.0 * 0x7FFF))
1217 		{	dest [i] = 0x7FFF ;
1218 			continue ;
1219 			} ;
1220 		if (scaled_value <= (-8.0 * 0x1000))
1221 		{	dest [i] = -0x8000 ;
1222 			continue ;
1223 			} ;
1224 		dest [i] = psf_lrintf (scaled_value) ;
1225 		} ;
1226 } /* f2flac16_clip_array */
1227 
1228 static void
f2flac24_clip_array(const float * src,int32_t * dest,int count,int normalize)1229 f2flac24_clip_array (const float *src, int32_t *dest, int count, int normalize)
1230 {	float normfact, scaled_value ;
1231 
1232 	normfact = normalize ? (8.0 * 0x100000) : 1.0 ;
1233 
1234 	for (int i = 0 ; i < count ; i++)
1235 	{	scaled_value = src [i] * normfact ;
1236 		if (scaled_value >= (1.0 * 0x7FFFFF))
1237 		{	dest [i] = 0x7FFFFF ;
1238 			continue ;
1239 			} ;
1240 
1241 		if (scaled_value <= (-8.0 * 0x100000))
1242 		{	dest [i] = -0x800000 ;
1243 			continue ;
1244 			}
1245 		dest [i] = psf_lrintf (scaled_value) ;
1246 		} ;
1247 
1248 	return ;
1249 } /* f2flac24_clip_array */
1250 
1251 static void
f2flac8_array(const float * src,int32_t * dest,int count,int normalize)1252 f2flac8_array (const float *src, int32_t *dest, int count, int normalize)
1253 {	float normfact = normalize ? (1.0 * 0x7F) : 1.0 ;
1254 
1255 	for (int i = 0 ; i < count ; i++)
1256 		dest [i] = psf_lrintf (src [i] * normfact) ;
1257 } /* f2flac8_array */
1258 
1259 static void
f2flac16_array(const float * src,int32_t * dest,int count,int normalize)1260 f2flac16_array (const float *src, int32_t *dest, int count, int normalize)
1261 {	float normfact = normalize ? (1.0 * 0x7FFF) : 1.0 ;
1262 
1263 	for (int i = 0 ; i < count ; i++)
1264 		dest [i] = psf_lrintf (src [i] * normfact) ;
1265 } /* f2flac16_array */
1266 
1267 static void
f2flac24_array(const float * src,int32_t * dest,int count,int normalize)1268 f2flac24_array (const float *src, int32_t *dest, int count, int normalize)
1269 {	float normfact = normalize ? (1.0 * 0x7FFFFF) : 1.0 ;
1270 
1271 	for (int i = 0 ; i < count ; i++)
1272 		dest [i] = psf_lrintf (src [i] * normfact) ;
1273 } /* f2flac24_array */
1274 
1275 static sf_count_t
flac_write_d2flac(SF_PRIVATE * psf,const double * ptr,sf_count_t len)1276 flac_write_d2flac (SF_PRIVATE *psf, const double *ptr, sf_count_t len)
1277 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1278 	void (*convert) (const double *, int32_t *, int, int) ;
1279 	int bufferlen, writecount, thiswrite ;
1280 	sf_count_t	total = 0 ;
1281 	int32_t* buffer = pflac->encbuffer ;
1282 
1283 	switch (SF_CODEC (psf->sf.format))
1284 	{	case SF_FORMAT_PCM_S8 :
1285 			convert = (psf->add_clipping) ? d2flac8_clip_array : d2flac8_array ;
1286 			break ;
1287 		case SF_FORMAT_PCM_16 :
1288 			convert = (psf->add_clipping) ? d2flac16_clip_array : d2flac16_array ;
1289 			break ;
1290 		case SF_FORMAT_PCM_24 :
1291 			convert = (psf->add_clipping) ? d2flac24_clip_array : d2flac24_array ;
1292 			break ;
1293 		default :
1294 			return -1 ;
1295 		} ;
1296 
1297 	bufferlen = ENC_BUFFER_SIZE / (sizeof (int32_t) * psf->sf.channels) ;
1298 	bufferlen *= psf->sf.channels ;
1299 
1300 	while (len > 0)
1301 	{	writecount = (len >= bufferlen) ? bufferlen : (int) len ;
1302 		convert (ptr + total, buffer, writecount, psf->norm_double) ;
1303 		if (FLAC__stream_encoder_process_interleaved (pflac->fse, buffer, writecount / psf->sf.channels))
1304 			thiswrite = writecount ;
1305 		else
1306 			break ;
1307 		total += thiswrite ;
1308 		if (thiswrite < writecount)
1309 			break ;
1310 
1311 		len -= thiswrite ;
1312 		} ;
1313 
1314 	return total ;
1315 } /* flac_write_d2flac */
1316 
1317 static void
d2flac8_clip_array(const double * src,int32_t * dest,int count,int normalize)1318 d2flac8_clip_array (const double *src, int32_t *dest, int count, int normalize)
1319 {	double normfact, scaled_value ;
1320 
1321 	normfact = normalize ? (8.0 * 0x10) : 1.0 ;
1322 
1323 	for (int i = 0 ; i < count ; i++)
1324 	{	scaled_value = src [i] * normfact ;
1325 		if (scaled_value >= (1.0 * 0x7F))
1326 		{	dest [i] = 0x7F ;
1327 			continue ;
1328 			} ;
1329 		if (scaled_value <= (-8.0 * 0x10))
1330 		{	dest [i] = -0x80 ;
1331 			continue ;
1332 			} ;
1333 		dest [i] = psf_lrint (scaled_value) ;
1334 		} ;
1335 
1336 	return ;
1337 } /* d2flac8_clip_array */
1338 
1339 static void
d2flac16_clip_array(const double * src,int32_t * dest,int count,int normalize)1340 d2flac16_clip_array (const double *src, int32_t *dest, int count, int normalize)
1341 {	double normfact, scaled_value ;
1342 
1343 	normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
1344 
1345 	for (int i = 0 ; i < count ; i++)
1346 	{	scaled_value = src [i] * normfact ;
1347 		if (scaled_value >= (1.0 * 0x7FFF))
1348 		{	dest [i] = 0x7FFF ;
1349 			continue ;
1350 			} ;
1351 		if (scaled_value <= (-8.0 * 0x1000))
1352 		{	dest [i] = -0x8000 ;
1353 			continue ;
1354 			} ;
1355 		dest [i] = psf_lrint (scaled_value) ;
1356 		} ;
1357 
1358 	return ;
1359 } /* d2flac16_clip_array */
1360 
1361 static void
d2flac24_clip_array(const double * src,int32_t * dest,int count,int normalize)1362 d2flac24_clip_array (const double *src, int32_t *dest, int count, int normalize)
1363 {	double normfact, scaled_value ;
1364 
1365 	normfact = normalize ? (8.0 * 0x100000) : 1.0 ;
1366 
1367 	for (int i = 0 ; i < count ; i++)
1368 	{	scaled_value = src [i] * normfact ;
1369 		if (scaled_value >= (1.0 * 0x7FFFFF))
1370 		{	dest [i] = 0x7FFFFF ;
1371 			continue ;
1372 			} ;
1373 		if (scaled_value <= (-8.0 * 0x100000))
1374 		{	dest [i] = -0x800000 ;
1375 			continue ;
1376 			} ;
1377 		dest [i] = psf_lrint (scaled_value) ;
1378 		} ;
1379 
1380 	return ;
1381 } /* d2flac24_clip_array */
1382 
1383 static void
d2flac8_array(const double * src,int32_t * dest,int count,int normalize)1384 d2flac8_array (const double *src, int32_t *dest, int count, int normalize)
1385 {	double normfact = normalize ? (1.0 * 0x7F) : 1.0 ;
1386 
1387 	for (int i = 0 ; i < count ; i++)
1388 		dest [i] = psf_lrint (src [i] * normfact) ;
1389 } /* d2flac8_array */
1390 
1391 static void
d2flac16_array(const double * src,int32_t * dest,int count,int normalize)1392 d2flac16_array (const double *src, int32_t *dest, int count, int normalize)
1393 {	double normfact = normalize ? (1.0 * 0x7FFF) : 1.0 ;
1394 
1395 	for (int i = 0 ; i < count ; i++)
1396 		dest [i] = psf_lrint (src [i] * normfact) ;
1397 } /* d2flac16_array */
1398 
1399 static void
d2flac24_array(const double * src,int32_t * dest,int count,int normalize)1400 d2flac24_array (const double *src, int32_t *dest, int count, int normalize)
1401 {	double normfact = normalize ? (1.0 * 0x7FFFFF) : 1.0 ;
1402 
1403 	for (int i = 0 ; i < count ; i++)
1404 		dest [i] = psf_lrint (src [i] * normfact) ;
1405 } /* d2flac24_array */
1406 
1407 static sf_count_t
flac_seek(SF_PRIVATE * psf,int UNUSED (mode),sf_count_t offset)1408 flac_seek (SF_PRIVATE *psf, int UNUSED (mode), sf_count_t offset)
1409 {	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;
1410 
1411 	if (pflac == NULL)
1412 		return 0 ;
1413 
1414 	if (psf->dataoffset < 0)
1415 	{	psf->error = SFE_BAD_SEEK ;
1416 		return ((sf_count_t) -1) ;
1417 		} ;
1418 
1419 	pflac->frame = NULL ;
1420 
1421 	if (psf->file.mode == SFM_READ)
1422 	{	if (FLAC__stream_decoder_seek_absolute (pflac->fsd, offset))
1423 			return offset ;
1424 
1425 		if (offset == psf->sf.frames)
1426 		{	/*
1427 			** If we've been asked to seek to the very end of the file, libFLAC
1428 			** will return an error. However, we know the length of the file so
1429 			** instead of returning an error, we can return the offset.
1430 			*/
1431 			return offset ;
1432 			} ;
1433 
1434 		psf->error = SFE_BAD_SEEK ;
1435 		return ((sf_count_t) -1) ;
1436 		} ;
1437 
1438 	/* Seeking in write mode not yet supported. */
1439 	psf->error = SFE_BAD_SEEK ;
1440 
1441 	return ((sf_count_t) -1) ;
1442 } /* flac_seek */
1443 
1444 static int
flac_byterate(SF_PRIVATE * psf)1445 flac_byterate (SF_PRIVATE *psf)
1446 {
1447 	if (psf->file.mode == SFM_READ)
1448 		return (psf->datalength * psf->sf.samplerate) / psf->sf.frames ;
1449 
1450 	return -1 ;
1451 } /* flac_byterate */
1452 
1453 
1454 #else /* HAVE_EXTERNAL_XIPH_LIBS */
1455 
1456 int
flac_open(SF_PRIVATE * psf)1457 flac_open	(SF_PRIVATE *psf)
1458 {
1459 	psf_log_printf (psf, "This version of libsndfile was compiled without FLAC support.\n") ;
1460 	return SFE_UNIMPLEMENTED ;
1461 } /* flac_open */
1462 
1463 #endif
1464