forked from FrankBoesing/Arduino-Teensy-Codec-lib
-
Notifications
You must be signed in to change notification settings - Fork 2
/
play_sd_flac.cpp
601 lines (515 loc) · 15.9 KB
/
play_sd_flac.cpp
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
/*
Arduino Audiocodecs
Copyright (c) 2014 Frank Bösing
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
Diese Bibliothek ist freie Software: Sie können es unter den Bedingungen
der GNU General Public License, wie von der Free Software Foundation,
Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren
veröffentlichten Version, weiterverbreiten und/oder modifizieren.
Diese Bibliothek wird in der Hoffnung, dass es nützlich sein wird, aber
OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
Siehe die GNU General Public License für weitere Details.
Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*/
#include "play_sd_flac.h"
FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data);
FLAC__StreamDecoderSeekStatus seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
FLAC__StreamDecoderTellStatus tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
FLAC__StreamDecoderLengthStatus length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
FLAC__bool eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
FLAC__StreamDecoder *AudioPlaySdFlac::hFLACDecoder ;
unsigned AudioCodec::decode_cycles;
unsigned AudioCodec::decode_cycles_max;
unsigned AudioCodec::decode_cycles_read;
unsigned AudioCodec::decode_cycles_max_read;
short AudioCodec::lastError;
void decodeFlac(void);
void AudioPlaySdFlac::stop(void)
{
NVIC_DISABLE_IRQ(IRQ_AUDIOCODEC);
playing = codec_stopped;
delete audiobuffer;
audiobuffer = NULL;
if (hFLACDecoder != NULL)
{
FLAC__stream_decoder_finish(hFLACDecoder);
FLAC__stream_decoder_delete(hFLACDecoder);
hFLACDecoder=NULL;
};
}
uint32_t AudioPlaySdFlac::lengthMillis(void)
{
if (hFLACDecoder != NULL)
return FLAC__stream_decoder_get_total_samples(hFLACDecoder) * 1000 / samplerate;
else
return 0;
}
/*
int AudioPlaySdFlac::play(const char *filename){
stop();
if (!fopen(filename))
return ERR_CODEC_FILE_NOT_FOUND;
return initPlay();
}
int AudioPlaySdFlac::play(const size_t p, const size_t size){
stop();
if (!fopen(p,size))
return ERR_CODEC_FILE_NOT_FOUND;
return initPlay();
}
*/
int AudioPlaySdFlac::play(void)
{
initVars();
lastError = ERR_CODEC_NONE;
hFLACDecoder = FLAC__stream_decoder_new();
if (!hFLACDecoder)
{
lastError = ERR_CODEC_OUT_OF_MEMORY;
goto PlayErr;
}
audiobuffer = new AudioBuffer();
FLAC__StreamDecoderInitStatus ret;
ret = FLAC__stream_decoder_init_stream(hFLACDecoder,
read_callback,
seek_callback,
tell_callback,
length_callback,
eof_callback,
write_callback,
NULL,
error_callback,
this);
// ret = FLAC__stream_decoder_init_stream(hFLACDecoder,read_callback,NULL,NULL,NULL,NULL,write_callback,NULL,error_callback,this);
if (ret != FLAC__STREAM_DECODER_INIT_STATUS_OK)
{
if (ret == FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR) lastError = ERR_CODEC_OUT_OF_MEMORY;
else lastError = ERR_CODEC_FORMAT;
//Serial.printf("Init: %s",FLAC__StreamDecoderInitStatusString[ret]);
goto PlayErr;
}
if (!FLAC__stream_decoder_process_until_end_of_metadata(hFLACDecoder))
{
lastError = ERR_CODEC_FORMAT;
goto PlayErr;
}
if (!FLAC__stream_decoder_process_single(hFLACDecoder))
{
lastError = ERR_CODEC_FORMAT;
goto PlayErr;
}
parseMetadata();
samplerate = FLAC__stream_decoder_get_sample_rate(hFLACDecoder);
#ifdef FLAC_USE_SWI
_VectorsRam[IRQ_AUDIOCODEC + 16] = &decodeFlac;
initSwi();
#endif
playing = codec_playing;
return lastError;
PlayErr:
stop();
return lastError;
}
bool AudioPlaySdFlac::seek(uint32_t timesec)
{
pause(true);
uint64_t sample = timesec * samplerate;
sample &= ~(AUDIO_BLOCK_SAMPLES-1); // the write callback can't handle frame sizes that are not multiples of AUDIO_BLOCK_SAMPLES
bool seekResult = FLAC__stream_decoder_seek_absolute(hFLACDecoder, sample);
if (seekResult) {
goto done;
}
// seek failed, flush decoder and try again
FLAC__StreamDecoderState state;
state = FLAC__stream_decoder_get_state(hFLACDecoder);
Serial.print("FLAC seek failed, decoder state: ");
Serial.println(state);
seekResult = FLAC__stream_decoder_flush(hFLACDecoder);
if (seekResult) {
Serial.println("FLAC flush succeeded");
goto done;
}
// flush failed
state = FLAC__stream_decoder_get_state(hFLACDecoder);
Serial.print("FLAC flush failed, decoder state: ");
Serial.println(state);
done:
// clear and refill audiobuffer
while(audiobuffer->used()){
audiobuffer->get();
}
checkAndFillBuffer();
pause(false);
return seekResult;
}
__attribute__ ((optimize("O2")))
FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
{
uint32_t cycles = ARM_DWT_CYCCNT;
FLAC__StreamDecoderReadStatus ret = FLAC__STREAM_DECODER_READ_STATUS_ABORT;
if(*bytes > 0)
{
int num = ((AudioPlaySdFlac*)client_data)->fread(buffer, *bytes);
if (num > 0)
{
ret = FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
*bytes = num;
} else
if(num == 0)
{
ret = FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
*bytes = 0;
}
else *bytes = 0;
}
((AudioPlaySdFlac*)client_data)->decode_cycles_read += (ARM_DWT_CYCCNT - cycles);
return ret;
}
/**
* Seek callback. Called when decoder needs to seek the stream.
*
* @param decoder Decoder instance
* @param absolute_byte_offset Offset from beginning of stream to seek to
* @param client_data Client data set at initialisation
*
* @return Seek status
*/
FLAC__StreamDecoderSeekStatus seek_callback(const FLAC__StreamDecoder* decoder, FLAC__uint64 absolute_byte_offset, void* client_data)
{
if (!((AudioPlaySdFlac*)client_data)->fseek(absolute_byte_offset)) {
// seek failed
return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
}
else {
return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
}
}
/**
* Tell callback. Called when decoder wants to know current position of stream.
*
* @param decoder Decoder instance
* @param absolute_byte_offset Offset from beginning of stream to seek to
* @param client_data Client data set at initialisation
*
* @return Tell status
*/
FLAC__StreamDecoderTellStatus tell_callback(const FLAC__StreamDecoder* decoder, FLAC__uint64* absolute_byte_offset, void* client_data)
{
// update offset
*absolute_byte_offset = (FLAC__uint64)((AudioPlaySdFlac*)client_data)->fposition();
return FLAC__STREAM_DECODER_TELL_STATUS_OK;
}
/**
* Length callback. Called when decoder wants total length of stream.
*
* @param decoder Decoder instance
* @param stream_length Total length of stream in bytes
* @param client_data Client data set at initialisation
*
* @return Length status
*/
FLAC__StreamDecoderLengthStatus length_callback(const FLAC__StreamDecoder* decoder, FLAC__uint64* stream_length, void* client_data)
{
*stream_length = (FLAC__uint64)((AudioPlaySdFlac*)client_data)->fsize();
return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
}
/**
* EOF callback. Called when decoder wants to know if end of stream is reached.
*
* @param decoder Decoder instance
* @param client_data Client data set at initialisation
*
* @return True if end of stream
*/
FLAC__bool eof_callback(const FLAC__StreamDecoder* decoder, void* client_data)
{
return ((AudioPlaySdFlac*)client_data)->f_eof();
}
/**
* Error callback. Called when error occured during decoding.
*
* @param decoder Decoder instance
* @param status Error
* @param client_data Client data set at initialisation
*/
void error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
{
//Serial.println(FLAC__StreamDecoderErrorStatusString[status]);
//((AudioPlaySdFlac*)client_data)->stop();
//Serial.print("ERROR ");
}
/**
* Write callback. Called when decoder has decoded a single audio frame.
*
* @param decoder Decoder instance
* @param frame Decoded frame
* @param buffer Array of pointers to decoded channels of data
* @param client_data Client data set at initialisation
*
* @return Read status
*/
__attribute__ ((optimize("O3")))
FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
{
AudioPlaySdFlac *obj = (AudioPlaySdFlac*) client_data;
int blocksize = frame->header.blocksize & ~(AUDIO_BLOCK_SAMPLES-1) ;
int chan = frame->header.channels;
int bps = frame->header.bits_per_sample;
size_t numbuffers = (blocksize * chan) / AUDIO_BLOCK_SAMPLES;
if (obj->audiobuffer->getBufsize() == 0)
{ //It is our very first frame.
obj->_channels = chan;
obj->audiobuffer->allocMem(FLAC_BUFFERS(numbuffers));
obj->minbuffers = numbuffers;
}
if (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER && obj->audiobuffer->used() == 0) {
// we get here after seeking or starting playback. update samples_played.
obj->samples_played = frame->header.number.sample_number;
}
if (chan==0 || chan> 2 ||
blocksize < AUDIO_BLOCK_SAMPLES ||
obj->audiobuffer->available() < numbuffers
)
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
//Copy all the data to the fifo. Decoded buffer is 32 bit, fifo is 16 bit
//int16_t *abufPtr = obj->audiobuffer->alloc(numbuffers);
//Serial.printf("Free:%d Req:%d\r\n", obj->audiobuffer->available(), numbuffers);
const FLAC__int32 *sbuf;
const FLAC__int32 *k;
if (bps==16) //16 BITS / SAMPLE
{
int j = 0;
do
{
int i = 0;
do
{
sbuf = &buffer[i][j];
k = sbuf + AUDIO_BLOCK_SAMPLES;
int16_t *abufPtr = obj->audiobuffer->alloc();
do
{
*abufPtr++ = (*sbuf++);
} while (sbuf < k);
} while (++i < chan);
j+= AUDIO_BLOCK_SAMPLES;
} while (j < blocksize);
}
else if (bps < 16) //2..15 BITS /SAMPLE
{
int shift = 16-bps;
int j = 0;
do
{
int i = 0;
do
{
sbuf = &buffer[i][j];
k = sbuf + AUDIO_BLOCK_SAMPLES;
int16_t *abufPtr = obj->audiobuffer->alloc();
do
{
*abufPtr++ = (*sbuf++)<<shift;
} while (sbuf < k);
} while (++i < chan);
j+= AUDIO_BLOCK_SAMPLES;
} while (j < blocksize);
}
else //17..32 BITS /SAMPLE
{
int shift = bps-16;
int j = 0;
do
{
int i = 0;
do
{
sbuf = &buffer[i][j];
k = sbuf + AUDIO_BLOCK_SAMPLES;
int16_t *abufPtr = obj->audiobuffer->alloc();
do
{
*abufPtr++ = (*sbuf++)>>shift;
} while (sbuf < k);
} while (++i < chan);
j+= AUDIO_BLOCK_SAMPLES;
} while (j < blocksize);
}
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
//runs in ISR
__attribute__ ((optimize("O3")))
void AudioPlaySdFlac::update(void)
{
audio_block_t *audioblockL;
audio_block_t *audioblockR;
//paused or stopped ?
if (playing != codec_playing) return;
if (_channels > 0 && audiobuffer->used() >= _channels)
{
audioblockL = allocate();
if (!audioblockL) return;
if (_channels == 2)
{
audioblockR = allocate();
if (!audioblockR) {
release(audioblockL);
return;
}
int16_t *abufptrL = audiobuffer->get();
int16_t *abufptrR = audiobuffer->get();
for (int j=0; j < AUDIO_BLOCK_SAMPLES; j++)
{
audioblockL->data[j] = *abufptrL++;
audioblockR->data[j] = *abufptrR++;
}
transmit(audioblockL, 0);
transmit(audioblockR, 1);
release(audioblockL);
release(audioblockR);
} else
{
int16_t *abufptrL = audiobuffer->get();
for (int j=0; j < AUDIO_BLOCK_SAMPLES; j++)
{
audioblockL->data[j] = *abufptrL++;
}
transmit(audioblockL, 0);
transmit(audioblockL, 1);
release(audioblockL);
}
samples_played += AUDIO_BLOCK_SAMPLES;
} else
{ //Stop playing
#ifdef FLAC_USE_SWI
if (!NVIC_IS_ACTIVE(IRQ_AUDIOCODEC))
#endif
{
FLAC__StreamDecoderState state;
state = FLAC__stream_decoder_get_state(hFLACDecoder);
if (state == FLAC__STREAM_DECODER_END_OF_STREAM ||
state == FLAC__STREAM_DECODER_ABORTED ||
state == FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR)
{
stop();
return;
}
}
}
if (decodingSuspended) return;
checkAndFillBuffer();
}
void AudioPlaySdFlac::checkAndFillBuffer(void)
{
if (audiobuffer->getBufsize() > 0 && audiobuffer->available() < minbuffers) return;
#ifndef FLAC_USE_SWI
decode_cycles_sd = 0;
FLAC__stream_decoder_process_single(hFLACDecoder);
if (decode_cycles_sd > decode_cycles_max_sd ) decode_cycles_max_sd = decode_cycles_sd;
#else
//to give the user-sketch some cpu-time, only chain
//if the swi is not active currently.
if (!NVIC_IS_ACTIVE(IRQ_AUDIOCODEC))
NVIC_TRIGGER_INTERRUPT(IRQ_AUDIOCODEC);
#endif
}
// FLAC metadata API reads the whole metadata block into memory. The metadata can be up to 16MB
// So we reimplement metadata parsing in a low-memory-friendly way
void AudioPlaySdFlac::parseMetadata(void){
uint32_t savedPos = fposition();
uint32_t metaBlockPos = 4;
bool lastMetadataBlock = false;
uint8_t buf[4];
fseek(0);
fread(buf, 4);
if(strncmp("ID3", (char*)buf, 3) == 0){
// This will seek back to 0 and parse the ID3
uint32_t id3size = parseID3();
// skip ID3 and parse the FLAC header now
fseek(id3size);
fread(buf, 4);
metaBlockPos = id3size + 4;
}
if(strncmp("fLaC", (char*)buf, 4)){
goto end;
}
while(!lastMetadataBlock){
if(!fseek(metaBlockPos)){
goto end;
}
fread(buf, 4);
lastMetadataBlock = buf[0] >> 7;
uint32_t blockLen = (buf[1] << 16) | (buf[2] << 8) | buf[3];
metaBlockPos += blockLen + 4;
uint8_t blockType = buf[0] & 0x7f;
Serial.print("block type ");
Serial.println(blockType);
if(blockType != 4){
continue;
}
uint32_t vendorLen;
fread((uint8_t*)&vendorLen, 4);
if(!fseek(fposition() + vendorLen)){
goto end;
}
uint32_t numTags;
fread((uint8_t*)&numTags, 4);
for(uint32_t i = 0; i < numTags; i++){
if(fposition() >= metaBlockPos){
break;
}
uint32_t tagLen;
fread((uint8_t*)&tagLen, 4);
if(tagLen > 49){
if(!fseek(fposition() + tagLen)){
goto end;
}
continue;
}
char tagBuf[tagLen + 1];
fread((uint8_t*)tagBuf, tagLen);
tagBuf[tagLen] = 0;
if(isReplayGainKey(tagBuf)){
float value = atof(tagBuf + 22);
setReplayGainValue(tagBuf, value);
}
}
}
end:
fseek(savedPos);
}
void AudioPlaySdFlac::suspendDecoding(void)
{
decodingSuspended = true;
}
void AudioPlaySdFlac::resumeDecoding(void)
{
decodingSuspended = false;
checkAndFillBuffer();
}
void decodeFlac(void)
{
//if (!audiobuffer.available()) return;
AudioPlaySdFlac::decode_cycles_read = 0;
uint32_t cycles = ARM_DWT_CYCCNT;
if (AudioPlaySdFlac::hFLACDecoder == NULL) return;
FLAC__stream_decoder_process_single(AudioPlaySdFlac::hFLACDecoder);
cycles = (ARM_DWT_CYCCNT - cycles);
if (cycles - AudioPlaySdFlac::decode_cycles > AudioPlaySdFlac::decode_cycles_max )
AudioPlaySdFlac::decode_cycles_max = cycles - AudioPlaySdFlac::decode_cycles;
if (AudioPlaySdFlac::decode_cycles_read > AudioPlaySdFlac::decode_cycles_max_read )
AudioPlaySdFlac::decode_cycles_max_read = AudioPlaySdFlac::decode_cycles_read;
}