1 /* license:BSD-3-Clause
2  * copyright-holders:Aaron Giles
3 ***************************************************************************
4 
5     flac.c
6 
7     FLAC compression wrappers
8 
9 ***************************************************************************/
10 
11 #include <assert.h>
12 #include <string.h>
13 
14 #include <libchdr/flac.h>
15 
16 /***************************************************************************
17  *  FLAC DECODER
18  ***************************************************************************
19  */
20 
21 static FLAC__StreamDecoderReadStatus flac_decoder_read_callback_static(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
22 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(void* client_data, FLAC__byte buffer[], size_t *bytes);
23 static void flac_decoder_metadata_callback_static(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
24 static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback_static(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
25 static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback_static(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
26 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(void* client_data, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
27 static void flac_decoder_error_callback_static(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
28 
29 /* getters (valid after reset) */
sample_rate(flac_decoder * decoder)30 static uint32_t sample_rate(flac_decoder *decoder)  { return decoder->sample_rate; }
channels(flac_decoder * decoder)31 static uint8_t channels(flac_decoder *decoder)  { return decoder->channels; }
bits_per_sample(flac_decoder * decoder)32 static uint8_t bits_per_sample(flac_decoder *decoder) { return decoder->bits_per_sample; }
total_samples(flac_decoder * decoder)33 static uint32_t total_samples(flac_decoder *decoder)  { return FLAC__stream_decoder_get_total_samples(decoder->decoder); }
state(flac_decoder * decoder)34 static FLAC__StreamDecoderState state(flac_decoder *decoder) { return FLAC__stream_decoder_get_state(decoder->decoder); }
state_string(flac_decoder * decoder)35 static const char *state_string(flac_decoder *decoder) { return FLAC__stream_decoder_get_resolved_state_string(decoder->decoder); }
36 
37 /*-------------------------------------------------
38  *  flac_decoder - constructor
39  *-------------------------------------------------
40  */
41 
flac_decoder_init(flac_decoder * decoder)42 void flac_decoder_init(flac_decoder *decoder)
43 {
44 	decoder->decoder = FLAC__stream_decoder_new();
45 	decoder->sample_rate = 0;
46 	decoder->channels = 0;
47 	decoder->bits_per_sample = 0;
48 	decoder->compressed_offset = 0;
49 	decoder->compressed_start = NULL;
50 	decoder->compressed_length = 0;
51 	decoder->compressed2_start = NULL;
52 	decoder->compressed2_length = 0;
53 	decoder->uncompressed_offset = 0;
54 	decoder->uncompressed_length = 0;
55 	decoder->uncompressed_swap = 0;
56 }
57 
58 /*-------------------------------------------------
59  *  flac_decoder - destructor
60  *-------------------------------------------------
61  */
62 
flac_decoder_free(flac_decoder * decoder)63 void flac_decoder_free(flac_decoder* decoder)
64 {
65 	if ((decoder != NULL) && (decoder->decoder != NULL))
66 		FLAC__stream_decoder_delete(decoder->decoder);
67 }
68 
69 /*-------------------------------------------------
70  *  reset - reset state with the original
71  *  parameters
72  *-------------------------------------------------
73  */
74 
flac_decoder_internal_reset(flac_decoder * decoder)75 static int flac_decoder_internal_reset(flac_decoder* decoder)
76 {
77 	decoder->compressed_offset = 0;
78 	if (FLAC__stream_decoder_init_stream(decoder->decoder,
79 				&flac_decoder_read_callback_static,
80 				NULL,
81 				&flac_decoder_tell_callback_static,
82 				NULL,
83 				NULL,
84 				&flac_decoder_write_callback_static,
85 				&flac_decoder_metadata_callback_static,
86 				&flac_decoder_error_callback_static, decoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
87 		return 0;
88 	return FLAC__stream_decoder_process_until_end_of_metadata(decoder->decoder);
89 }
90 
91 /*-------------------------------------------------
92  *  reset - reset state with new memory parameters
93  *  and a custom-generated header
94  *-------------------------------------------------
95  */
96 
flac_decoder_reset(flac_decoder * decoder,uint32_t sample_rate,uint8_t num_channels,uint32_t block_size,const void * buffer,uint32_t length)97 int flac_decoder_reset(flac_decoder* decoder, uint32_t sample_rate, uint8_t num_channels, uint32_t block_size, const void *buffer, uint32_t length)
98 {
99 	/* modify the template header with our parameters */
100 	static const uint8_t s_header_template[0x2a] =
101 	{
102 		0x66, 0x4C, 0x61, 0x43,                         /* +00: 'fLaC' stream header */
103 		0x80,                                           /* +04: metadata block type 0 (STREAMINFO), */
104 								/*      flagged as last block */
105 		0x00, 0x00, 0x22,                               /* +05: metadata block length = 0x22 */
106 		0x00, 0x00,                                     /* +08: minimum block size */
107 		0x00, 0x00,                                     /* +0A: maximum block size */
108 		0x00, 0x00, 0x00,                               /* +0C: minimum frame size (0 == unknown) */
109 		0x00, 0x00, 0x00,                               /* +0F: maximum frame size (0 == unknown) */
110 		0x0A, 0xC4, 0x42, 0xF0, 0x00, 0x00, 0x00, 0x00, /* +12: sample rate (0x0ac44 == 44100), */
111 								/*      numchannels (2), sample bits (16), */
112 								/*      samples in stream (0 == unknown) */
113 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* +1A: MD5 signature (0 == none) */
114 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  /* +2A: start of stream data */
115 	};
116 	memcpy(decoder->custom_header, s_header_template, sizeof(s_header_template));
117 	decoder->custom_header[0x08] = decoder->custom_header[0x0a] = block_size >> 8;
118 	decoder->custom_header[0x09] = decoder->custom_header[0x0b] = block_size & 0xff;
119 	decoder->custom_header[0x12] = sample_rate >> 12;
120 	decoder->custom_header[0x13] = sample_rate >> 4;
121 	decoder->custom_header[0x14] = (sample_rate << 4) | ((num_channels - 1) << 1);
122 
123 	/* configure the header ahead of the provided buffer */
124 	decoder->compressed_start = (const FLAC__byte *)(decoder->custom_header);
125 	decoder->compressed_length = sizeof(decoder->custom_header);
126 	decoder->compressed2_start = (const FLAC__byte *)(buffer);
127 	decoder->compressed2_length = length;
128 	return flac_decoder_internal_reset(decoder);
129 }
130 
131 /*-------------------------------------------------
132  *  decode_interleaved - decode to an interleaved
133  *  sound stream
134  *-------------------------------------------------
135  */
136 
flac_decoder_decode_interleaved(flac_decoder * decoder,int16_t * samples,uint32_t num_samples,int swap_endian)137 int flac_decoder_decode_interleaved(flac_decoder* decoder, int16_t *samples, uint32_t num_samples, int swap_endian)
138 {
139 	/* configure the uncompressed buffer */
140 	memset(decoder->uncompressed_start, 0, sizeof(decoder->uncompressed_start));
141 	decoder->uncompressed_start[0] = samples;
142 	decoder->uncompressed_offset = 0;
143 	decoder->uncompressed_length = num_samples;
144 	decoder->uncompressed_swap = swap_endian;
145 
146 	/* loop until we get everything we want */
147 	while (decoder->uncompressed_offset < decoder->uncompressed_length)
148 		if (!FLAC__stream_decoder_process_single(decoder->decoder))
149 			return 0;
150 	return 1;
151 }
152 
153 #if 0
154 /*-------------------------------------------------
155  *  decode - decode to an multiple independent
156  *  data streams
157  *-------------------------------------------------
158  */
159 
160 bool flac_decoder::decode(int16_t **samples, uint32_t num_samples, bool swap_endian)
161 {
162 	/* make sure we don't have too many channels */
163 	int chans = channels();
164 	if (chans > ARRAY_LENGTH(m_uncompressed_start))
165 		return false;
166 
167 	/* configure the uncompressed buffer */
168 	memset(m_uncompressed_start, 0, sizeof(m_uncompressed_start));
169 	for (int curchan = 0; curchan < chans; curchan++)
170 		m_uncompressed_start[curchan] = samples[curchan];
171 	m_uncompressed_offset = 0;
172 	m_uncompressed_length = num_samples;
173 	m_uncompressed_swap = swap_endian;
174 
175 	/* loop until we get everything we want */
176 	while (m_uncompressed_offset < m_uncompressed_length)
177 		if (!FLAC__stream_decoder_process_single(m_decoder))
178 			return false;
179 	return true;
180 }
181 #endif
182 
183 /*-------------------------------------------------
184  *  finish - finish up the decode
185  *-------------------------------------------------
186  */
187 
flac_decoder_finish(flac_decoder * decoder)188 uint32_t flac_decoder_finish(flac_decoder* decoder)
189 {
190 	/* get the final decoding position and move forward */
191 	FLAC__uint64 position = 0;
192 	FLAC__stream_decoder_get_decode_position(decoder->decoder, &position);
193 	FLAC__stream_decoder_finish(decoder->decoder);
194 
195 	/* adjust position if we provided the header */
196 	if (position == 0)
197 		return 0;
198 	if (decoder->compressed_start == (const FLAC__byte *)(decoder->custom_header))
199 		position -= decoder->compressed_length;
200 	return position;
201 }
202 
203 /*-------------------------------------------------
204  *  read_callback - handle reads from the input
205  *  stream
206  *-------------------------------------------------
207  */
208 
209 #define MIN(x, y) ((x) < (y) ? (x) : (y))
210 
flac_decoder_read_callback_static(const FLAC__StreamDecoder * decoder,FLAC__byte buffer[],size_t * bytes,void * client_data)211 FLAC__StreamDecoderReadStatus flac_decoder_read_callback_static(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
212 {
213 	return flac_decoder_read_callback(client_data, buffer, bytes);
214 }
215 
flac_decoder_read_callback(void * client_data,FLAC__byte buffer[],size_t * bytes)216 FLAC__StreamDecoderReadStatus flac_decoder_read_callback(void* client_data, FLAC__byte buffer[], size_t *bytes)
217 {
218 	flac_decoder* decoder = (flac_decoder*)client_data;
219 
220 	uint32_t expected = *bytes;
221 
222 	/* copy from primary buffer first */
223 	uint32_t outputpos = 0;
224 	if (outputpos < *bytes && decoder->compressed_offset < decoder->compressed_length)
225 	{
226 		uint32_t bytes_to_copy = MIN(*bytes - outputpos, decoder->compressed_length - decoder->compressed_offset);
227 		memcpy(&buffer[outputpos], decoder->compressed_start + decoder->compressed_offset, bytes_to_copy);
228 		outputpos += bytes_to_copy;
229 		decoder->compressed_offset += bytes_to_copy;
230 	}
231 
232 	/* once we're out of that, copy from the secondary buffer */
233 	if (outputpos < *bytes && decoder->compressed_offset < decoder->compressed_length + decoder->compressed2_length)
234 	{
235 		uint32_t bytes_to_copy = MIN(*bytes - outputpos, decoder->compressed2_length - (decoder->compressed_offset - decoder->compressed_length));
236 		memcpy(&buffer[outputpos], decoder->compressed2_start + decoder->compressed_offset - decoder->compressed_length, bytes_to_copy);
237 		outputpos += bytes_to_copy;
238 		decoder->compressed_offset += bytes_to_copy;
239 	}
240 	*bytes = outputpos;
241 
242 	/* return based on whether we ran out of data */
243 	return (*bytes < expected) ? FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM : FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
244 }
245 
246 /*-------------------------------------------------
247  *  metadata_callback - handle STREAMINFO metadata
248  *-------------------------------------------------
249  */
250 
flac_decoder_metadata_callback_static(const FLAC__StreamDecoder * decoder,const FLAC__StreamMetadata * metadata,void * client_data)251 void flac_decoder_metadata_callback_static(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
252 {
253 	flac_decoder *fldecoder;
254 	/* ignore all but STREAMINFO metadata */
255 	if (metadata->type != FLAC__METADATA_TYPE_STREAMINFO)
256 		return;
257 
258 	/* parse out the data we care about */
259 	fldecoder = (flac_decoder *)(client_data);
260 	fldecoder->sample_rate = metadata->data.stream_info.sample_rate;
261 	fldecoder->bits_per_sample = metadata->data.stream_info.bits_per_sample;
262 	fldecoder->channels = metadata->data.stream_info.channels;
263 }
264 
265 /*-------------------------------------------------
266  *  tell_callback - handle requests to find out
267  *  where in the input stream we are
268  *-------------------------------------------------
269  */
270 
flac_decoder_tell_callback_static(const FLAC__StreamDecoder * decoder,FLAC__uint64 * absolute_byte_offset,void * client_data)271 FLAC__StreamDecoderTellStatus flac_decoder_tell_callback_static(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
272 {
273 	*absolute_byte_offset = ((flac_decoder *)client_data)->compressed_offset;
274 	return FLAC__STREAM_DECODER_TELL_STATUS_OK;
275 }
276 
277 /*-------------------------------------------------
278  *  write_callback - handle writes to the output
279  *  stream
280  *-------------------------------------------------
281  */
282 
flac_decoder_write_callback_static(const FLAC__StreamDecoder * decoder,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)283 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback_static(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
284 {
285 	return flac_decoder_write_callback(client_data, frame, buffer);
286 }
287 
flac_decoder_write_callback(void * client_data,const FLAC__Frame * frame,const FLAC__int32 * const buffer[])288 FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(void *client_data, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
289 {
290 	int sampnum, chan;
291 	int shift, blocksize;
292 	flac_decoder * decoder = (flac_decoder *)client_data;
293 
294 	assert(frame->header.channels == channels(decoder));
295 
296 	/* interleaved case */
297 	shift = decoder->uncompressed_swap ? 8 : 0;
298 	blocksize = frame->header.blocksize;
299 	if (decoder->uncompressed_start[1] == NULL)
300 	{
301 		int16_t *dest = decoder->uncompressed_start[0] + decoder->uncompressed_offset * frame->header.channels;
302 		for (sampnum = 0; sampnum < blocksize && decoder->uncompressed_offset < decoder->uncompressed_length; sampnum++, decoder->uncompressed_offset++)
303 			for (chan = 0; chan < frame->header.channels; chan++)
304 				*dest++ = (int16_t)((((uint16_t)buffer[chan][sampnum]) << shift) | (((uint16_t)buffer[chan][sampnum]) >> shift));
305 	}
306 
307 	/* non-interleaved case */
308 	else
309 	{
310 		for (sampnum = 0; sampnum < blocksize && decoder->uncompressed_offset < decoder->uncompressed_length; sampnum++, decoder->uncompressed_offset++)
311 			for (chan = 0; chan < frame->header.channels; chan++)
312 				if (decoder->uncompressed_start[chan] != NULL)
313 					decoder->uncompressed_start[chan][decoder->uncompressed_offset] = (int16_t) ( (((uint16_t)(buffer[chan][sampnum])) << shift) | ( ((uint16_t)(buffer[chan][sampnum])) >> shift) );
314 	}
315 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
316 }
317 
318 /**
319  * @fn  void flac_decoder::error_callback_static(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
320  *
321  * @brief   -------------------------------------------------
322  *            error_callback - handle errors (ignore them)
323  *          -------------------------------------------------.
324  *
325  * @param   decoder             The decoder.
326  * @param   status              The status.
327  * @param [in,out]  client_data If non-null, information describing the client.
328  */
329 
flac_decoder_error_callback_static(const FLAC__StreamDecoder * decoder,FLAC__StreamDecoderErrorStatus status,void * client_data)330 void flac_decoder_error_callback_static(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
331 {
332 }
333