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