summaryrefslogtreecommitdiffstatshomepage
path: root/src/lib/util/flac.cpp
blob: 54a589ee2a235f7fdfbcfa76dbfe281f661fb204 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************

    flac.c

    FLAC compression wrappers

***************************************************************************/

#include <assert.h>

#include "flac.h"
#include <new>


//**************************************************************************
//  FLAC ENCODER
//**************************************************************************

//-------------------------------------------------
//  flac_encoder - constructors
//-------------------------------------------------

flac_encoder::flac_encoder()
{
	init_common();
}


flac_encoder::flac_encoder(void *buffer, uint32_t buflength)
{
	init_common();
	reset(buffer, buflength);
}


flac_encoder::flac_encoder(util::core_file &file)
{
	init_common();
	reset(file);
}


//-------------------------------------------------
//  ~flac_encoder - destructor
//-------------------------------------------------

flac_encoder::~flac_encoder()
{
	// delete the encoder
	FLAC__stream_encoder_delete(m_encoder);
}


//-------------------------------------------------
//  reset - reset state with the original
//  parameters
//-------------------------------------------------

bool flac_encoder::reset()
{
	// configure the output
	m_compressed_offset = 0;
	m_ignore_bytes = m_strip_metadata ? 4 : 0;
	m_found_audio = !m_strip_metadata;

	// configure the encoder in a standard way
	// note we do this on each reset; if we don't, results are NOT consistent!
	FLAC__stream_encoder_set_verify(m_encoder, false);
//  FLAC__stream_encoder_set_do_md5(m_encoder, false);
	FLAC__stream_encoder_set_compression_level(m_encoder, 8);
	FLAC__stream_encoder_set_channels(m_encoder, m_channels);
	FLAC__stream_encoder_set_bits_per_sample(m_encoder, 16);
	FLAC__stream_encoder_set_sample_rate(m_encoder, m_sample_rate);
	FLAC__stream_encoder_set_total_samples_estimate(m_encoder, 0);
	FLAC__stream_encoder_set_streamable_subset(m_encoder, false);
	FLAC__stream_encoder_set_blocksize(m_encoder, m_block_size);

	// re-start processing
	return (FLAC__stream_encoder_init_stream(m_encoder, write_callback_static, nullptr, nullptr, nullptr, this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK);
}


//-------------------------------------------------
//  reset - reset state with new memory parameters
//-------------------------------------------------

bool flac_encoder::reset(void *buffer, uint32_t buflength)
{
	// configure the output
	m_compressed_start = reinterpret_cast<FLAC__byte *>(buffer);
	m_compressed_length = buflength;
	m_file = nullptr;
	return reset();
}


//-------------------------------------------------
//  reset - reset state with new file parameters
//-------------------------------------------------

bool flac_encoder::reset(util::core_file &file)
{
	// configure the output
	m_compressed_start = nullptr;
	m_compressed_length = 0;
	m_file = &file;
	return reset();
}


//-------------------------------------------------
//  encode_interleaved - encode a buffer with
//  interleaved samples
//-------------------------------------------------

bool flac_encoder::encode_interleaved(const int16_t *samples, uint32_t samples_per_channel, bool swap_endian)
{
	int shift = swap_endian ? 8 : 0;

	// loop over source samples
	int num_channels = FLAC__stream_encoder_get_channels(m_encoder);
	uint32_t srcindex = 0;
	while (samples_per_channel != 0)
	{
		// process in batches of 2k samples
		FLAC__int32 converted_buffer[2048];
		FLAC__int32 *dest = converted_buffer;
		uint32_t cur_samples = (std::min<size_t>)(ARRAY_LENGTH(converted_buffer) / num_channels, samples_per_channel);

		// convert a buffers' worth
		for (uint32_t sampnum = 0; sampnum < cur_samples; sampnum++)
			for (int channel = 0; channel < num_channels; channel++, srcindex++)
				*dest++ = int16_t((uint16_t(samples[srcindex]) << shift) | (uint16_t(samples[srcindex]) >> shift));

		// process this batch
		if (!FLAC__stream_encoder_process_interleaved(m_encoder, converted_buffer, cur_samples))
			return false;
		samples_per_channel -= cur_samples;
	}
	return true;
}


//-------------------------------------------------
//  encode - encode a buffer with individual
//  sample streams
//-------------------------------------------------

bool flac_encoder::encode(int16_t *const *samples, uint32_t samples_per_channel, bool swap_endian)
{
	int shift = swap_endian ? 8 : 0;

	// loop over source samples
	int num_channels = FLAC__stream_encoder_get_channels(m_encoder);
	uint32_t srcindex = 0;
	while (samples_per_channel != 0)
	{
		// process in batches of 2k samples
		FLAC__int32 converted_buffer[2048];
		FLAC__int32 *dest = converted_buffer;
		uint32_t cur_samples = (std::min<size_t>)(ARRAY_LENGTH(converted_buffer) / num_channels, samples_per_channel);

		// convert a buffers' worth
		for (uint32_t sampnum = 0; sampnum < cur_samples; sampnum++, srcindex++)
			for (int channel = 0; channel < num_channels; channel++)
				*dest++ = int16_t((uint16_t(samples[channel][srcindex]) << shift) | (uint16_t(samples[channel][srcindex]) >> shift));

		// process this batch
		if (!FLAC__stream_encoder_process_interleaved(m_encoder, converted_buffer, cur_samples))
			return false;
		samples_per_channel -= cur_samples;
	}
	return true;
}


//-------------------------------------------------
//  finish - complete encoding and flush the
//  stream
//-------------------------------------------------

uint32_t flac_encoder::finish()
{
	// process the data and return the amount written
	FLAC__stream_encoder_finish(m_encoder);
	return (m_file != nullptr) ? m_file->tell() : m_compressed_offset;
}


//-------------------------------------------------
//  init_common - common initialization
//-------------------------------------------------

void flac_encoder::init_common()
{
	// allocate the encoder
	m_encoder = FLAC__stream_encoder_new();
	if (m_encoder == nullptr)
		throw std::bad_alloc();

	// initialize default state
	m_file = nullptr;
	m_compressed_offset = 0;
	m_compressed_start = nullptr;
	m_compressed_length = 0;
	m_sample_rate = 44100;
	m_channels = 2;
	m_block_size = 0;
	m_strip_metadata = false;
	m_ignore_bytes = 0;
	m_found_audio = false;
}


//-------------------------------------------------
//  write_callback - handle writes to the
//  output stream
//-------------------------------------------------

FLAC__StreamEncoderWriteStatus flac_encoder::write_callback_static(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
{
	return reinterpret_cast<flac_encoder *>(client_data)->write_callback(buffer, bytes, samples, current_frame);
}

FLAC__StreamEncoderWriteStatus flac_encoder::write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame)
{
	// loop over output data
	size_t offset = 0;
	while (offset < bytes)
	{
		// if we're ignoring, continue to do so
		if (m_ignore_bytes != 0)
		{
			size_t ignore = std::min(bytes - offset, size_t(m_ignore_bytes));
			offset += ignore;
			m_ignore_bytes -= ignore;
		}

		// if we haven't hit the end of metadata, process a new piece
		else if (!m_found_audio)
		{
			assert(bytes - offset >= 4);
			m_found_audio = ((buffer[offset] & 0x80) != 0);
			m_ignore_bytes = (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | buffer[offset + 3];
			offset += 4;
		}

		// otherwise process as audio data and copy to the output
		else
		{
			int count = bytes - offset;
			if (m_file != nullptr)
				m_file->write(buffer, count);
			else
			{
				if (m_compressed_offset + count <= m_compressed_length)
					memcpy(m_compressed_start + m_compressed_offset, buffer, count);
				m_compressed_offset += count;
			}
			offset += count;
		}
	}
	return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
}



//**************************************************************************
//  FLAC DECODER
//**************************************************************************

//-------------------------------------------------
//  flac_decoder - constructor
//-------------------------------------------------

flac_decoder::flac_decoder()
	: m_decoder(FLAC__stream_decoder_new()),
		m_file(nullptr),
		m_sample_rate(0),
		m_channels(0),
		m_bits_per_sample(0),
		m_compressed_offset(0),
		m_compressed_start(nullptr),
		m_compressed_length(0),
		m_compressed2_start(nullptr),
		m_compressed2_length(0),
		m_uncompressed_offset(0),
		m_uncompressed_length(0),
		m_uncompressed_swap(false)
{
}


//-------------------------------------------------
//  flac_decoder - constructor
//-------------------------------------------------

flac_decoder::flac_decoder(const void *buffer, uint32_t length, const void *buffer2, uint32_t length2)
	: m_decoder(FLAC__stream_decoder_new()),
		m_file(nullptr),
		m_compressed_offset(0),
		m_compressed_start(reinterpret_cast<const FLAC__byte *>(buffer)),
		m_compressed_length(length),
		m_compressed2_start(reinterpret_cast<const FLAC__byte *>(buffer2)),
		m_compressed2_length(length2)
{
	reset();
}


//-------------------------------------------------
//  flac_decoder - constructor
//-------------------------------------------------

flac_decoder::flac_decoder(util::core_file &file)
	: m_decoder(FLAC__stream_decoder_new()),
		m_file(&file),
		m_compressed_offset(0),
		m_compressed_start(nullptr),
		m_compressed_length(0),
		m_compressed2_start(nullptr),
		m_compressed2_length(0)
{
	reset();
}


//-------------------------------------------------
//  flac_decoder - destructor
//-------------------------------------------------

flac_decoder::~flac_decoder()
{
	FLAC__stream_decoder_delete(m_decoder);
}


//-------------------------------------------------
//  reset - reset state with the original
//  parameters
//-------------------------------------------------

bool flac_decoder::reset()
{
	m_compressed_offset = 0;
	if (FLAC__stream_decoder_init_stream(m_decoder,
				&flac_decoder::read_callback_static,
				nullptr,
				&flac_decoder::tell_callback_static,
				nullptr,
				nullptr,
				&flac_decoder::write_callback_static,
				&flac_decoder::metadata_callback_static,
				&flac_decoder::error_callback_static, this) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
		return false;
	return FLAC__stream_decoder_process_until_end_of_metadata(m_decoder);
}


//-------------------------------------------------
//  reset - reset state with new memory parameters
//-------------------------------------------------

bool flac_decoder::reset(const void *buffer, uint32_t length, const void *buffer2, uint32_t length2)
{
	m_file = nullptr;
	m_compressed_start = reinterpret_cast<const FLAC__byte *>(buffer);
	m_compressed_length = length;
	m_compressed2_start = reinterpret_cast<const FLAC__byte *>(buffer2);
	m_compressed2_length = length2;
	return reset();
}


//-------------------------------------------------
//  reset - reset state with new memory parameters
//  and a custom-generated header
//-------------------------------------------------

bool flac_decoder::reset(uint32_t sample_rate, uint8_t num_channels, uint32_t block_size, const void *buffer, uint32_t length)
{
	// modify the template header with our parameters
	static const uint8_t s_header_template[0x2a] =
	{
		0x66, 0x4C, 0x61, 0x43,                         // +00: 'fLaC' stream header
		0x80,                                           // +04: metadata block type 0 (STREAMINFO),
														//      flagged as last block
		0x00, 0x00, 0x22,                               // +05: metadata block length = 0x22
		0x00, 0x00,                                     // +08: minimum block size
		0x00, 0x00,                                     // +0A: maximum block size
		0x00, 0x00, 0x00,                               // +0C: minimum frame size (0 == unknown)
		0x00, 0x00, 0x00,                               // +0F: maximum frame size (0 == unknown)
		0x0A, 0xC4, 0x42, 0xF0, 0x00, 0x00, 0x00, 0x00, // +12: sample rate (0x0ac44 == 44100),
														//      numchannels (2), sample bits (16),
														//      samples in stream (0 == unknown)
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // +1A: MD5 signature (0 == none)
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  //
														// +2A: start of stream data
	};
	memcpy(m_custom_header, s_header_template, sizeof(s_header_template));
	m_custom_header[0x08] = m_custom_header[0x0a] = block_size >> 8;
	m_custom_header[0x09] = m_custom_header[0x0b] = block_size & 0xff;
	m_custom_header[0x12] = sample_rate >> 12;
	m_custom_header[0x13] = sample_rate >> 4;
	m_custom_header[0x14] = (sample_rate << 4) | ((num_channels - 1) << 1);

	// configure the header ahead of the provided buffer
	m_file = nullptr;
	m_compressed_start = reinterpret_cast<const FLAC__byte *>(m_custom_header);
	m_compressed_length = sizeof(m_custom_header);
	m_compressed2_start = reinterpret_cast<const FLAC__byte *>(buffer);
	m_compressed2_length = length;
	return reset();
}


//-------------------------------------------------
//  reset - reset state with new file parameter
//-------------------------------------------------

bool flac_decoder::reset(util::core_file &file)
{
	m_file = &file;
	m_compressed_start = nullptr;
	m_compressed_length = 0;
	m_compressed2_start = nullptr;
	m_compressed2_length = 0;
	return reset();
}


//-------------------------------------------------
//  decode_interleaved - decode to an interleaved
//  sound stream
//-------------------------------------------------

bool flac_decoder::decode_interleaved(int16_t *samples, uint32_t num_samples, bool swap_endian)
{
	// configure the uncompressed buffer
	memset(m_uncompressed_start, 0, sizeof(m_uncompressed_start));
	m_uncompressed_start[0] = samples;
	m_uncompressed_offset = 0;
	m_uncompressed_length = num_samples;
	m_uncompressed_swap = swap_endian;

	// loop until we get everything we want
	while (m_uncompressed_offset < m_uncompressed_length)
		if (!FLAC__stream_decoder_process_single(m_decoder))
			return false;
	return true;
}


//-------------------------------------------------
//  decode - decode to an multiple independent
//  data streams
//-------------------------------------------------

bool flac_decoder::decode(int16_t **samples, uint32_t num_samples, bool swap_endian)
{
	// make sure we don't have too many channels
	int chans = channels();
	if (chans > ARRAY_LENGTH(m_uncompressed_start))
		return false;

	// configure the uncompressed buffer
	memset(m_uncompressed_start, 0, sizeof(m_uncompressed_start));
	for (int curchan = 0; curchan < chans; curchan++)
		m_uncompressed_start[curchan] = samples[curchan];
	m_uncompressed_offset = 0;
	m_uncompressed_length = num_samples;
	m_uncompressed_swap = swap_endian;

	// loop until we get everything we want
	while (m_uncompressed_offset < m_uncompressed_length)
		if (!FLAC__stream_decoder_process_single(m_decoder))
			return false;
	return true;
}


//-------------------------------------------------
//  finish - finish up the decode
//-------------------------------------------------

uint32_t flac_decoder::finish()
{
	// get the final decoding position and move forward
	FLAC__uint64 position = 0;
	FLAC__stream_decoder_get_decode_position(m_decoder, &position);
	FLAC__stream_decoder_finish(m_decoder);

	// adjust position if we provided the header
	if (position == 0)
		return 0;
	if (m_compressed_start == reinterpret_cast<const FLAC__byte *>(m_custom_header))
		position -= m_compressed_length;
	return position;
}


//-------------------------------------------------
//  read_callback - handle reads from the input
//  stream
//-------------------------------------------------

FLAC__StreamDecoderReadStatus flac_decoder::read_callback_static(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
{
	return reinterpret_cast<flac_decoder *>(client_data)->read_callback(buffer, bytes);
}

FLAC__StreamDecoderReadStatus flac_decoder::read_callback(FLAC__byte buffer[], size_t *bytes)
{
	uint32_t expected = *bytes;

	// if a file, just read
	if (m_file != nullptr)
		*bytes = m_file->read(buffer, expected);

	// otherwise, copy from memory
	else
	{
		// copy from primary buffer first
		uint32_t outputpos = 0;
		if (outputpos < *bytes && m_compressed_offset < m_compressed_length)
		{
			uint32_t bytes_to_copy = (std::min<size_t>)(*bytes - outputpos, m_compressed_length - m_compressed_offset);
			memcpy(&buffer[outputpos], m_compressed_start + m_compressed_offset, bytes_to_copy);
			outputpos += bytes_to_copy;
			m_compressed_offset += bytes_to_copy;
		}

		// once we're out of that, copy from the secondary buffer
		if (outputpos < *bytes && m_compressed_offset < m_compressed_length + m_compressed2_length)
		{
			uint32_t bytes_to_copy = (std::min<size_t>)(*bytes - outputpos, m_compressed2_length - (m_compressed_offset - m_compressed_length));
			memcpy(&buffer[outputpos], m_compressed2_start + m_compressed_offset - m_compressed_length, bytes_to_copy);
			outputpos += bytes_to_copy;
			m_compressed_offset += bytes_to_copy;
		}
		*bytes = outputpos;
	}

	// return based on whether we ran out of data
	return (*bytes < expected) ? FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM : FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
}


//-------------------------------------------------
//  metadata_callback - handle STREAMINFO metadata
//-------------------------------------------------

void flac_decoder::metadata_callback_static(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
{
	// ignore all but STREAMINFO metadata
	if (metadata->type != FLAC__METADATA_TYPE_STREAMINFO)
		return;

	// parse out the data we care about
	flac_decoder *fldecoder = reinterpret_cast<flac_decoder *>(client_data);
	fldecoder->m_sample_rate = metadata->data.stream_info.sample_rate;
	fldecoder->m_bits_per_sample = metadata->data.stream_info.bits_per_sample;
	fldecoder->m_channels = metadata->data.stream_info.channels;
}


//-------------------------------------------------
//  tell_callback - handle requests to find out
//  where in the input stream we are
//-------------------------------------------------

FLAC__StreamDecoderTellStatus flac_decoder::tell_callback_static(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
{
	*absolute_byte_offset = reinterpret_cast<flac_decoder *>(client_data)->m_compressed_offset;
	return FLAC__STREAM_DECODER_TELL_STATUS_OK;
}


//-------------------------------------------------
//  write_callback - handle writes to the output
//  stream
//-------------------------------------------------

FLAC__StreamDecoderWriteStatus flac_decoder::write_callback_static(const FLAC__StreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
{
	return reinterpret_cast<flac_decoder *>(client_data)->write_callback(frame, buffer);
}

FLAC__StreamDecoderWriteStatus flac_decoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
	assert(frame->header.channels == channels());

	// interleaved case
	int shift = m_uncompressed_swap ? 8 : 0;
	int blocksize = frame->header.blocksize;
	if (m_uncompressed_start[1] == nullptr)
	{
		int16_t *dest = m_uncompressed_start[0] + m_uncompressed_offset * frame->header.channels;
		for (int sampnum = 0; sampnum < blocksize && m_uncompressed_offset < m_uncompressed_length; sampnum++, m_uncompressed_offset++)
			for (int chan = 0; chan < frame->header.channels; chan++)
				*dest++ = int16_t((uint16_t(buffer[chan][sampnum]) << shift) | (uint16_t(buffer[chan][sampnum]) >> shift));
	}

	// non-interleaved case
	else
	{
		for (int sampnum = 0; sampnum < blocksize && m_uncompressed_offset < m_uncompressed_length; sampnum++, m_uncompressed_offset++)
			for (int chan = 0; chan < frame->header.channels; chan++)
				if (m_uncompressed_start[chan] != nullptr)
					m_uncompressed_start[chan][m_uncompressed_offset] = int16_t((uint16_t(buffer[chan][sampnum]) << shift) | (uint16_t(buffer[chan][sampnum]) >> shift));
	}
	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}

/**
 * @fn  void flac_decoder::error_callback_static(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
 *
 * @brief   -------------------------------------------------
 *            error_callback - handle errors (ignore them)
 *          -------------------------------------------------.
 *
 * @param   decoder             The decoder.
 * @param   status              The status.
 * @param [in,out]  client_data If non-null, information describing the client.
 */

void flac_decoder::error_callback_static(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
{
}