forked from 15-466/15-466-f22-base4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load_opus.cpp
54 lines (46 loc) · 1.64 KB
/
load_opus.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
#include "load_opus.hpp"
#include <opusfile.h>
#include <cassert>
#include <memory>
#include <cmath>
#include <stdexcept>
#include <iostream>
void load_opus(std::string const &filename, std::vector< float > *data_) {
assert(data_);
auto &data = *data_;
data.clear();
std::cout << "loading '" << filename << "'..."; std::cout.flush();
//will hold opusfile * int a std::unique_ptr so that it will automatically be deleted:
int err = 0;
std::unique_ptr< OggOpusFile, decltype(&op_free) > op(
op_open_file(filename.c_str(), &err), //pointer to hold
op_free //deletion function
);
if (err != 0) {
throw std::runtime_error("opusfile error " + std::to_string(err) + " opening \"" + filename + "\".");
}
//get length in samples:
ogg_int64_t length = op_pcm_total(op.get(), -1);
if (length >= 0) {
data.reserve(length);
} else {
std::cerr << "WARNING: cannot estimate length of '" << filename << "', loading may be slow." << std::endl;
length = 0;
data.reserve(2*48000);
}
std::vector< float > pcm(2*48000*2, 0.0f); //seems like reads are generally 960 samples so this is definitely overkill
for (;;) {
int ret = op_read_float_stereo(op.get(), pcm.data(), int(pcm.size()));
if (ret >= 0) {
//positive return values are the number of samples read per channel; copy into data:
data.reserve(data.size() + ret);
for (uint32_t i = 0; i < uint32_t(ret); ++i) {
data.emplace_back((pcm[2*i] + pcm[2*i+1]) * 0.5f); //downmix to mono by averaging
}
if (ret == 0) break;
} else {
throw std::runtime_error("opusfile read error " + std::to_string(ret) + " reading \"" + filename + "\".");
}
}
std::cout << " done." << std::endl;
}