forked from pure-data/pure-data
/
ceammc_loader_minimp3.cpp
445 lines (366 loc) · 13.9 KB
/
ceammc_loader_minimp3.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
/*****************************************************************************
* Copyright 2017 Serge Poltavsky. All rights reserved.
*
* This file may be distributed under the terms of GNU Public License version
* 3 (GPL v3) as defined by the Free Software Foundation (FSF). A copy of the
* license should have been included with this file, or the project in which
* this file belongs to. You may also find the details of GPL v3 at:
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* If you have any questions regarding the use of this file, feel free to
* contact the author of this file, or the owner of the project in which
* this file belongs to.
*****************************************************************************/
#include "ceammc_loader_minimp3.h"
#include "fmt/core.h"
#include "soxr.h"
#include <cmath>
#include <iostream>
#define MINIMP3_IMPLEMENTATION
#define MINIMP3_FLOAT_OUTPUT 1
//#define MINIMP3_SEEK_IDX_LINEAR_SEARCH 1
//#define MINIMP3_ALLOW_MONO_STEREO_TRANSITION
#include "minimp3.h"
#include "minimp3_ex.h"
#ifdef WITH_LIBSAMPLERATE
#include "samplerate.h"
using SampleRatePtr = std::unique_ptr<SRC_STATE, decltype(&src_delete)>;
#endif
#define MINI_PREFIX "[minimp3] "
namespace {
using SoxPtr = std::unique_ptr<soxr, decltype(&soxr_delete)>;
soxr_t ceammc_soxr_create(double ratio, unsigned ch, soxr_error_t* err)
{
return soxr_create(
1, ratio, ch, /* Input rate, output rate, # of channels. */
err, /* To report any error during creation. */
nullptr, nullptr, nullptr);
}
constexpr bool do_debug = false;
}
namespace ceammc {
namespace sound {
MiniMp3::MiniMp3()
: decoder_(new mp3dec_ex_t)
{
}
bool MiniMp3::probe(const char* fname) const
{
return mp3dec_detect(fname) == 0;
}
bool MiniMp3::open(const char* fname, OpenMode mode, const SoundFileOpenParams& params)
{
switch (mode) {
case SoundFile::WRITE:
log(fmt::format(MINI_PREFIX "can't open for writing: '{}'", fname));
return false;
case SoundFile::READ:
if (mp3dec_ex_open(decoder_.get(), fname, MP3D_SEEK_TO_SAMPLE)) {
log(fmt::format(MINI_PREFIX "can't open file: '{}'", fname));
decoder_.reset();
return false;
}
break;
case SoundFile::NONE:
default:
return false;
}
setOpenMode(mode);
fname_ = fname;
return true;
}
MiniMp3::~MiniMp3() = default; // for std::unique
size_t MiniMp3::frameCount() const
{
if (decoder_)
return decoder_->samples / decoder_->info.channels;
else
return 0;
}
size_t MiniMp3::sampleRate() const
{
if (decoder_)
return decoder_->info.hz;
else
return 0;
}
size_t MiniMp3::channels() const
{
if (decoder_)
return decoder_->info.channels;
else
return 0;
}
bool MiniMp3::isOpened() const
{
return decoder_.get();
}
bool MiniMp3::close()
{
if (decoder_)
mp3dec_ex_close(decoder_.get());
return true;
}
std::int64_t MiniMp3::read(t_word* dest, size_t sz, size_t ch, std::int64_t offset)
{
if (!(isOpened() && openMode() == READ)) {
error(fmt::format(MINI_PREFIX "not opened for reading"));
return -1;
}
const auto NUM_CH = channels();
if (ch >= NUM_CH) {
error(fmt::format(MINI_PREFIX "invalid channel number: {}", ch));
return -1;
}
if (resampleRatio() != 1)
return readResampled(dest, sz, ch, offset);
// seek to offset
const auto pos = std::min<size_t>(offset, frameCount()) * NUM_CH;
if (mp3dec_ex_seek(decoder_.get(), pos)) {
error(fmt::format(MINI_PREFIX "can't seek to sample #{}", offset));
return -1;
}
// decode to buffer
std::vector<mp3d_sample_t> buffer(sz * NUM_CH);
size_t readed = mp3dec_ex_read(decoder_.get(), buffer.data(), buffer.size());
if (readed != buffer.size()) { /* normal eof or error condition */
if (decoder_->last_error) {
error(MINI_PREFIX "read error");
return -1;
}
}
// copy to destination and apply gain
const auto g = gain();
for (size_t i = ch, j = 0; i < readed && i < buffer.size(); i += NUM_CH, j++)
dest[j].w_float = buffer[i] * g;
return readed / NUM_CH;
}
std::int64_t MiniMp3::readFrames(float* dest, size_t frames, std::int64_t offset)
{
if (!dest)
return -1;
if (!(isOpened() && openMode() == READ)) {
error(fmt::format(MINI_PREFIX "not opened for reading"));
return -1;
}
// seek to offset
const auto pos = std::min<size_t>(offset, frameCount()) * channels();
if (mp3dec_ex_seek(decoder_.get(), pos) != 0) {
error(fmt::format(MINI_PREFIX "can't seek to sample #{}", offset));
return -1;
}
static_assert(std::is_same<mp3d_sample_t, float>::value, "expected float for mp3 sample format");
auto n = mp3dec_ex_read(decoder_.get(), dest, frames * channels());
return n / channels();
}
#ifdef WITH_LIBSAMPLERATE
std::int64_t MiniMp3::readResampled(t_word* dest, size_t size, size_t ch, std::int64_t offset)
{
static_assert(std::is_same<mp3d_sample_t, float>::value, "");
if (resampleRatio() < 0.001) {
error(fmt::format(MINI_PREFIX "invalid resample ratio: {}", resampleRatio()));
return -1;
}
const auto NUM_CH = channels();
if (ch >= NUM_CH) {
error(fmt::format(MINI_PREFIX "[minimp3] invalid channel number: {}", ch));
return -1;
}
// seek to position
const auto pos = std::min<size_t>(offset * NUM_CH * resampleRatio(), frameCount());
if (pos > 0 && mp3dec_ex_seek(decoder_.get(), pos)) {
error(fmt::format(MINI_PREFIX "can't seek to pos #{}", offset));
return -1;
}
if (do_debug)
debug(fmt::format("offset {}", pos));
int sr_error = 0;
SampleRatePtr libsr(src_new(SRC_SINC_BEST_QUALITY, NUM_CH, &sr_error), &src_delete);
if (!libsr) {
error(fmt::format("[libsamplerate] init error: {}", src_strerror(sr_error)));
return -1;
}
sr_error = src_set_ratio(libsr.get(), resampleRatio());
if (sr_error) {
error(fmt::format("[libsamplerate] can't set ratio: {}", src_strerror(sr_error)));
return -1;
}
// decode to buffer
const size_t mp3_out_bufsize = MINIMP3_MAX_SAMPLES_PER_FRAME;
std::vector<mp3d_sample_t> in_buffer(mp3_out_bufsize);
const size_t should_read = size * NUM_CH;
if (do_debug)
debug(fmt::format("should output {} samples", should_read));
const size_t OUT_BUF_SIZE = std::round(in_buffer.size() * resampleRatio());
std::vector<float> out_buf(OUT_BUF_SIZE);
size_t total_decoded_mp3_samples = 0;
size_t total_output_samples = 0;
t_word* x = dest;
while (total_output_samples < should_read) {
bool eof = false;
// read to buffer
const auto nsamp = mp3dec_ex_read(decoder_.get(), in_buffer.data(), in_buffer.size());
total_decoded_mp3_samples += nsamp;
if (nsamp != in_buffer.size()) { /* normal eof or error condition */
if (decoder_->last_error) {
error("[minimp3] read error");
return -1;
}
// eof
eof = true;
}
/*
* Copy data from the mp3 decoder buffer into the resampler and resample
* to produce as much output as is possible to the given output buffer:
*/
SRC_DATA data = { 0 };
data.data_in = in_buffer.data();
data.input_frames = in_buffer.size();
data.data_out = out_buf.data();
data.output_frames = out_buf.size();
data.src_ratio = resampleRatio();
data.end_of_input = 0;
sr_error = src_process(libsr.get(), &data);
if (sr_error) {
error(fmt::format("[libsamplerate] error: ", src_strerror(sr_error)));
return -1;
}
// write channel data to destination
for (size_t j = 0; total_output_samples < size; j++) {
x->w_float = out_buf[j * NUM_CH + ch] * gain();
x++;
total_output_samples++;
}
if (eof)
break;
}
// process remaining resample data
while (true) {
SRC_DATA data = { 0 };
data.data_in = in_buffer.data();
data.input_frames = in_buffer.size();
data.data_out = out_buf.data();
data.output_frames = out_buf.size();
data.src_ratio = resampleRatio();
data.end_of_input = 1;
sr_error = src_process(libsr.get(), &data);
if (sr_error) {
error(fmt::format("[libsamplerate] error: {}", src_strerror(sr_error)));
return -1;
}
if (!data.output_frames_gen)
break;
// write channel data to destination
for (size_t j = 0; total_output_samples < size; j++) {
x->w_float = out_buf[j * NUM_CH + ch] * gain();
x++;
total_output_samples++;
}
}
if (do_debug) {
debug(fmt::format("total decoded mp3 samples: {}", total_decoded_mp3_samples));
debug(fmt::format("total output samples: {}", total_output_samples));
}
return total_output_samples;
}
#else
std::int64_t MiniMp3::readResampled(t_word* dest, size_t size, size_t ch, std::int64_t offset)
{
if (resampleRatio() < 0.001) {
error(fmt::format(MINI_PREFIX "invalid resample ratio: {}", resampleRatio()));
return -1;
}
const auto NUM_CH = channels();
if (ch >= NUM_CH) {
error(fmt::format(MINI_PREFIX "invalid channel number: {}", ch));
return -1;
}
// resampler init
soxr_error_t err;
SoxPtr soxr(ceammc_soxr_create(resampleRatio(), NUM_CH, &err), &soxr_delete);
if (err || !soxr) {
error(fmt::format(MINI_PREFIX "resampler init failed: {}", err));
return -1;
}
// seek to position
const auto pos = std::min<size_t>(offset * NUM_CH * resampleRatio(), frameCount());
if (pos > 0 && mp3dec_ex_seek(decoder_.get(), pos)) {
error(fmt::format(MINI_PREFIX "can't seek to pos #{}", offset));
return -1;
}
if (do_debug)
debug(fmt::format("offset {}", pos));
// decode to buffer
const size_t mp3_out_bufsize = MINIMP3_MAX_SAMPLES_PER_FRAME;
std::vector<mp3d_sample_t> in_buffer(mp3_out_bufsize);
const size_t should_read = size * NUM_CH;
if (do_debug)
debug(fmt::format("should output {} samples", should_read));
const size_t OUT_BUF_SIZE = std::round(in_buffer.size() * resampleRatio());
std::vector<float> out_buf(OUT_BUF_SIZE);
size_t total_decoded_mp3_samples = 0;
size_t total_output_samples = 0;
t_word* x = dest;
while (total_output_samples < should_read) {
bool eof = false;
// read to buffer
const auto nsamp = mp3dec_ex_read(decoder_.get(), in_buffer.data(), in_buffer.size());
total_decoded_mp3_samples += nsamp;
if (nsamp != in_buffer.size()) { /* normal eof or error condition */
if (decoder_->last_error) {
error(MINI_PREFIX "read error");
return -1;
}
// eof
eof = true;
}
/*
* Copy data from the mp3 decoder buffer into the resampler and resample
* to produce as much output as is possible to the given output buffer:
*/
size_t odone;
err = soxr_process(soxr.get(), in_buffer.data(), in_buffer.size(), nullptr, out_buf.data(), NUM_CH, &odone);
if (err) {
error(fmt::format(MINI_PREFIX "[soxr] error: {}", err));
break;
}
// write channel data to destination
for (size_t j = 0; j < odone && total_output_samples < size; j++) {
x->w_float = out_buf[j * NUM_CH + ch] * gain();
x++;
total_output_samples++;
}
if (eof)
break;
}
// process remaining resample data
while (true) {
size_t odone = 0;
// indicate end of input with nullptr
err = soxr_process(soxr.get(), nullptr, 0, nullptr, out_buf.data(), NUM_CH, &odone);
if (err) {
error(fmt::format(MINI_PREFIX "[soxr] error: {}", err));
break;
}
if (odone == 0)
break;
// write channel data to destination
for (size_t j = 0; j < odone && total_output_samples < size; j++) {
x->w_float = out_buf[j * NUM_CH + ch] * gain();
x++;
total_output_samples++;
}
}
if (do_debug) {
debug(fmt::format("total decoded mp3 samples: {}", total_decoded_mp3_samples));
debug(fmt::format("total output samples: {}", total_output_samples));
}
return total_output_samples;
}
#endif
FormatList MiniMp3::supportedReadFormats()
{
return { { "MP3", "MPEG Layer 3" } };
}
}
}