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
|
#ifdef _WIN32
#include <winsock2.h>
#endif
#include "manager.hpp"
#include <array>
#define MINIAUDIO_IMPLEMENTATION
#include <miniaudio.h>
#include <opus.h>
#include <cstring>
#define BUFFER_SAMPLES 4800
const uint8_t *StripRTPExtensionHeader(const uint8_t *buf, int num_bytes, size_t &outlen) {
if (buf[0] == 0xbe && buf[1] == 0xde && num_bytes > 4) {
uint64_t offset = 4 + 4 * ((buf[2] << 8) | buf[3]);
outlen = num_bytes - offset;
return buf + offset;
}
outlen = num_bytes;
return buf;
}
void data_callback(ma_device *pDevice, void *pOutput, const void *pInput, ma_uint32 frameCount) {
AudioManager *mgr = reinterpret_cast<AudioManager *>(pDevice->pUserData);
if (mgr == nullptr) return;
std::lock_guard<std::mutex> _(mgr->m_dumb_mutex);
const auto buffered_frames = std::min(static_cast<ma_uint32>(mgr->m_dumb.size() / 2), frameCount);
auto *pOutputCast = static_cast<ma_int16 *>(pOutput);
std::copy(mgr->m_dumb.begin(), mgr->m_dumb.begin() + buffered_frames * 2, pOutputCast);
mgr->m_dumb.erase(mgr->m_dumb.begin(), mgr->m_dumb.begin() + buffered_frames * 2);
}
AudioManager::AudioManager() {
m_ok = true;
m_device_config = ma_device_config_init(ma_device_type_playback);
m_device_config.playback.format = ma_format_s16;
m_device_config.playback.channels = 2;
m_device_config.sampleRate = 48000;
m_device_config.dataCallback = data_callback;
m_device_config.pUserData = this;
if (ma_device_init(nullptr, &m_device_config, &m_device) != MA_SUCCESS) {
puts("open playabck fail");
m_ok = false;
return;
}
if (ma_device_start(&m_device) != MA_SUCCESS) {
puts("failed to start playback");
ma_device_uninit(&m_device);
m_ok = false;
return;
}
int err;
m_opus_decoder = opus_decoder_create(48000, 2, &err);
m_active = true;
}
AudioManager::~AudioManager() {
m_active = false;
ma_device_uninit(&m_device);
}
void AudioManager::FeedMeOpus(const std::vector<uint8_t> &data) {
size_t payload_size = 0;
const auto *opus_encoded = StripRTPExtensionHeader(data.data(), static_cast<int>(data.size()), payload_size);
static std::array<opus_int16, 120 * 48 * 2> pcm;
int decoded = opus_decode(m_opus_decoder, opus_encoded, static_cast<opus_int32>(payload_size), pcm.data(), 120 * 48, 0);
if (decoded <= 0) {
printf("failed decode: %d\n", decoded);
} else {
m_buffer.insert(m_buffer.end(), pcm.begin(), pcm.begin() + decoded * 2);
if (m_buffer.size() >= BUFFER_SAMPLES * 2) {
m_dumb_mutex.lock();
m_dumb.insert(m_dumb.end(), m_buffer.begin(), m_buffer.begin() + BUFFER_SAMPLES * 2);
m_dumb_mutex.unlock();
m_buffer.erase(m_buffer.begin(), m_buffer.begin() + BUFFER_SAMPLES * 2);
}
}
}
bool AudioManager::OK() const {
return m_ok;
}
|