-
Notifications
You must be signed in to change notification settings - Fork 3
/
mp3-stream.cpp
465 lines (366 loc) · 10.4 KB
/
mp3-stream.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
#include <cinttypes>
#include "mp3-stream.hpp"
#define MINIMP3_IMPLEMENTATION
#define MINIMP3_ONLY_MP3
#include "minimp3.h"
#include "audio/audio.hpp"
#include "engine/engine.hpp"
#include "engine/file.hpp"
#ifdef PROFILER
#include "engine/profiler.hpp"
extern blit::ProfilerProbe *profilerRefillProbe;
extern blit::ProfilerProbe *profilerReadProbe;
extern blit::ProfilerProbe *profilerDecProbe;
#endif
// ID3v2 helpers
static int getSynchsafe(char *buf)
{
auto ubuf = reinterpret_cast<uint8_t *>(buf);
return ubuf[3] | (ubuf[2] << 7) | (ubuf[1] << 14) | (ubuf[0] << 21);
}
static uint32_t getInt32(char *buf)
{
auto ubuf = reinterpret_cast<uint8_t *>(buf);
return ubuf[3] | (ubuf[2] << 8) | (ubuf[1] << 16) | (ubuf[0] << 24);
}
static std::string readString(blit::File &file, uint32_t offset, char encoding, int32_t len)
{
std::string ret;
if(encoding == 0)
{
// ISO-8859-1
char c;
file.read(offset++, 1, &c);
for(int i = 1; i < len || (len == -1 && c); i++)
{
// "convert" by throwing away anything non-ascii
if((c & 0x80) == 0)
ret += c;
file.read(offset++, 1, &c);
}
}
else if(encoding == 1)
{
// UCS-2
uint16_t bom;
file.read(offset, 2, reinterpret_cast<char *>(&bom));
offset += 2;
uint16_t c;
file.read(offset, 2, reinterpret_cast<char *>(&c));
offset += 2;
for(int i = 1; i < (len - 2) / 2 || (len == -1 && c); i++)
{
// "convert" by throwing away anything non-ascii
if(bom == 0xFEFF && c < 0x80)
ret += c;
else if((c >> 8) < 0x80)
ret += (c >> 8);
file.read(offset, 2, reinterpret_cast<char *>(&c));
offset += 2;
}
}
else if(encoding == 3)
{
// UTF-8
char c;
file.read(offset++, 1, &c);
for(int i = 1; i < len || (len == -1 && c); i++)
{
// "convert" by throwing away anything non-ascii
if((c & 0x80) == 0)
ret += c;
file.read(offset++, 1, &c);
}
}
else
ret = "enc? " + std::to_string(encoding);
return ret;
}
static std::string readTextTag(blit::File &file, uint32_t offset, int32_t len)
{
char encoding;
file.read(offset, 1, &encoding);
return readString(file, offset + 1, encoding, len);
}
MP3Stream::MP3Stream()
{
mp3dec = new mp3dec_t;
}
MP3Stream::~MP3Stream()
{
delete mp3dec;
}
bool MP3Stream::load(std::string filename, bool doDurationCalc)
{
if(channel != -1)
blit::channels[channel].off();
currentSample = nullptr;
bufferedSamples = 0;
needConvert = false;
supported = true;
if(!file.open(filename))
return false;
// fill initial buffer
fileBufferFilled = 0;
fileOffset = 0;
read(0);
if(!fileBufferFilled)
return false;
if(doDurationCalc)
{
mp3dec_init(static_cast<mp3dec_t *>(mp3dec));
durationMs = calcDuration();
}
else
durationMs = 0;
// TODO: we're opening the file twice here
tags = parseTags(filename);
// start the decoder
mp3dec_init(static_cast<mp3dec_t *>(mp3dec));
return true;
}
MusicTags MP3Stream::parseTags(std::string filename)
{
MusicTags ret;
blit::File file(filename);
if(!file.is_open())
return ret;
char buf[10];
file.read(0, 10, buf);
if(memcmp(buf, "ID3", 3) != 0)
return ret;
// version/flags
int versionMajor = buf[3], versionMinor = buf[4];
int flags = buf[5];
// size
uint32_t size = getSynchsafe(buf + 6);
printf("ID3v2.%i.%i flags %x size %" PRIi32 "\n", versionMajor, versionMinor, flags, size);
uint32_t offset = 10;
// skip extended header
if(flags & 0x40)
{
file.read(offset, 4, buf);
offset += getSynchsafe(buf);
}
while(offset < size)
{
// read header
file.read(offset, 10, buf);
if(buf[0] == 0)
break;
std::string id(buf, 4);
uint32_t frameSize = versionMajor == 4 ? getSynchsafe(buf + 4) : getInt32(buf + 4);
offset += 10;
if(id == "TALB")
ret.album = readTextTag(file, offset, frameSize);
else if(id == "TIT2")
ret.title = readTextTag(file, offset, frameSize);
else if(id == "TPE1")
ret.artist = readTextTag(file, offset, frameSize);
else if(id == "TRCK")
ret.track = readTextTag(file, offset, frameSize);
else
printf("\t%s size %" PRIu32 " flags %x %x @%" PRIx32 "\n", id.c_str(), frameSize, buf[8], buf[9], offset);
offset += frameSize;
}
return ret;
}
void MP3Stream::play(int channel)
{
if(!fileBufferFilled)
return;
this->channel = channel;
if(!currentSample)
{
decode(0);
decode(1);
curAudioBuf = 0;
currentSample = audioBuf[0];
endSample = currentSample + dataSize[0];
blit::channels[channel].wave_buf_pos = 0;
}
blit::channels[channel].waveforms = blit::Waveform::WAVE;
blit::channels[channel].user_data = this;
blit::channels[channel].wave_buffer_callback = &MP3Stream::staticCallback;
//blit::channels[channel].trigger_attack();
blit::channels[channel].adsr = 0xFFFF00;
blit::channels[channel].trigger_sustain();
}
void MP3Stream::pause()
{
blit::channels[channel].off();
}
bool MP3Stream::getPlaying() const
{
return channel != -1 && blit::channels[channel].adsr_phase == blit::ADSRPhase::SUSTAIN;
}
void MP3Stream::update()
{
if(!currentSample)
return;
// refill audio buffers
for(int i = 0; i < 2; i++)
{
if(!dataSize[i])
decode(i);
}
}
int MP3Stream::getCurrentSample() const
{
return bufferedSamples + blit::channels[channel].wave_buf_pos;
}
int MP3Stream::getDurationMs() const
{
return durationMs;
}
const MusicTags &MP3Stream::getTags() const
{
return tags;
}
bool MP3Stream::getFileSupported() const
{
return supported;
}
void MP3Stream::decode(int bufIndex)
{
#ifdef PROFILER
blit::ScopedProfilerProbe scopedProbe(profilerRefillProbe);
#endif
mp3dec_frame_info_t info = {};
int samples = 0;
int freqScale = 1;
do
{
if(fileBufferFilled == 0)
break;
#ifdef PROFILER
profilerDecProbe->start();
#endif
if(needConvert)
{
// attempt to convert to mono 22050Hz (badly)
int16_t tmpBuf[MINIMP3_MAX_SAMPLES_PER_FRAME];
int tmpSamples = mp3dec_decode_frame(static_cast<mp3dec_t *>(mp3dec), fileBuffer, fileBufferFilled, tmpBuf, &info);
if(tmpSamples)
{
freqScale = info.hz / 22050;
int div = info.channels * freqScale;
for(int i = 0; i < tmpSamples * info.channels; i += div, samples++)
{
int32_t tmp = 0;
for(int j = 0; j < div; j++)
tmp += tmpBuf[i + j];
audioBuf[bufIndex][samples] = tmp / div;
}
}
}
else
samples += mp3dec_decode_frame(static_cast<mp3dec_t *>(mp3dec), fileBuffer, fileBufferFilled, audioBuf[bufIndex] + samples, &info);
#ifdef PROFILER
profilerDecProbe->pause();
#endif
// switch conversion on and retry if needed
if(!needConvert && (info.channels != 1 || info.hz != 22050))
{
needConvert = true;
decode(bufIndex);
supported = info.hz % 22050 == 0;
return;
}
#ifdef PROFILER
profilerReadProbe->start();
#endif
read(info.frame_bytes);
#ifdef PROFILER
profilerReadProbe->pause();
#endif
// / 2 because we only ever store mono
} while (samples + (MINIMP3_MAX_SAMPLES_PER_FRAME / (2 * freqScale)) <= audioBufSize);
#ifdef PROFILER
profilerReadProbe->store_elapsed_us();
profilerDecProbe->store_elapsed_us();
#endif
if(!samples)
{
dataSize[bufIndex] = -1;
return;
}
dataSize[bufIndex] = samples;
}
void MP3Stream::staticCallback(blit::AudioChannel &channel)
{
reinterpret_cast<MP3Stream *>(channel.user_data)->callback(channel);
}
void MP3Stream::callback(blit::AudioChannel &channel)
{
if(!currentSample)
{
channel.off();
return;
}
// there was no buffer last time
if(currentSample == endSample)
{
if(dataSize[curAudioBuf])
{
// recover from underrun
endSample = audioBuf[curAudioBuf] + dataSize[curAudioBuf];
}
else
{
memset(channel.wave_buffer, 0, 64 * sizeof(int16_t));
return;
}
}
auto out = channel.wave_buffer;
int i = 0;
for(; i < 64 /*&& currentSample != endSample*/; i++)
*(out++) = *(currentSample++);
// swap buffers
if(currentSample == endSample)
{
dataSize[curAudioBuf] = 0;
curAudioBuf = ++curAudioBuf % 2;
if(dataSize[curAudioBuf] == -1) // EOF
currentSample = endSample = nullptr;
else
{
currentSample = audioBuf[curAudioBuf];
endSample = currentSample + dataSize[curAudioBuf];
// if(currentSample == endSample)
// no more samples available - underrun
}
}
//for(; i < 64 && currentSample != endSample; i++)
// *(out++) = *(currentSample++);
bufferedSamples += 64;
}
int MP3Stream::calcDuration()
{
// decode entire file to get length
unsigned int samples = 0;
mp3dec_frame_info_t info = {};
//while(true)
while(fileBufferFilled)
{
samples += mp3dec_decode_frame(static_cast<mp3dec_t *>(mp3dec), fileBuffer, fileBufferFilled, nullptr, &info);
read(info.frame_bytes);
}
// reset;
fileOffset = 0;
fileBufferFilled = 0;
read(0);
int lenMs = (static_cast<uint64_t>(samples) * 1000) / info.hz;
return lenMs;
}
void MP3Stream::read(int32_t len)
{
if(len < fileBufferSize)
memmove(fileBuffer, fileBuffer + len, fileBufferFilled - len);
fileBufferFilled -= len;
auto read = file.read(fileOffset, fileBufferSize - fileBufferFilled, reinterpret_cast<char *>(fileBuffer) + fileBufferFilled);
if(read <= 0)
return;
fileBufferFilled += read;
fileOffset += read;
}