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