-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathopus_decoder.cc
More file actions
50 lines (41 loc) · 1.44 KB
/
opus_decoder.cc
File metadata and controls
50 lines (41 loc) · 1.44 KB
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
#include "opus_decoder.h"
#include <esp_log.h>
#define TAG "OpusDecoderWrapper"
OpusDecoderWrapper::OpusDecoderWrapper(int sample_rate, int channels, int duration_ms)
: sample_rate_(sample_rate), duration_ms_(duration_ms) {
int error;
audio_dec_ = opus_decoder_create(sample_rate, channels, &error);
if (audio_dec_ == nullptr) {
ESP_LOGE(TAG, "Failed to create audio decoder, error code: %d", error);
return;
}
frame_size_ = sample_rate / 1000 * channels * duration_ms;
}
OpusDecoderWrapper::~OpusDecoderWrapper() {
std::lock_guard<std::mutex> lock(mutex_);
if (audio_dec_ != nullptr) {
opus_decoder_destroy(audio_dec_);
}
}
bool OpusDecoderWrapper::Decode(std::vector<uint8_t>&& opus, std::vector<int16_t>& pcm) {
std::lock_guard<std::mutex> lock(mutex_);
if (audio_dec_ == nullptr) {
ESP_LOGE(TAG, "Audio decoder is not configured");
return false;
}
pcm.resize(frame_size_);
auto ret = opus_decode(audio_dec_, opus.data(), opus.size(), pcm.data(), pcm.size(), 0);
if (ret < 0) {
ESP_LOGE(TAG, "Failed to decode audio, error code: %d", ret);
return false;
}
// Resize the pcm vector to the actual decoded samples
pcm.resize(ret);
return true;
}
void OpusDecoderWrapper::ResetState() {
std::lock_guard<std::mutex> lock(mutex_);
if (audio_dec_ != nullptr) {
opus_decoder_ctl(audio_dec_, OPUS_RESET_STATE);
}
}