arduino-audio-tools
Loading...
Searching...
No Matches
CodecOpus.h
Go to the documentation of this file.
1#pragma once
2
4#include "Print.h"
5#include "opus.h"
6
7#ifndef OPUS_ENC_MAX_BUFFER_SIZE
8#define OPUS_ENC_MAX_BUFFER_SIZE 2048
9#endif
10
11#ifndef OPUS_DEC_MAX_BUFFER_SIZE
12#define OPUS_DEC_MAX_BUFFER_SIZE 4 * 1024
13#endif
14
15namespace audio_tools {
16
34
78 int bitrate = -1;
80 int force_channel = -1;
82 int vbr = -1;
86 int complexity = -1;
91 int max_bandwidth = -1;
93 int signal = -1;
95 int inband_fec = -1;
99 int lsb_depth = -1;
103 int use_dtx = -1;
105 int frame_sizes_ms_x2 = -1; /* x2 to avoid 2.5 ms */
106};
107
122 public:
127
137
140
141 AudioInfo audioInfo() override { return cfg; }
142
144 OpusSettings &config() { return cfg; }
146
147 bool begin(OpusSettings settings) {
148 TRACED();
150 cfg = settings;
152 return begin();
153 }
154
155 bool begin() override {
156 TRACED();
158 LOGE("Sample rate not supported: %d", cfg.sample_rate);
159 return false;
160 }
162 assert(outbuf.data() != nullptr);
163
164 // allocate decoder
165 size_t size = opus_decoder_get_size(cfg.channels);
166 decbuf.resize(size);
167 assert(decbuf.data() != nullptr);
168 dec = (OpusDecoder *)decbuf.data();
170
171 if (err != OPUS_OK) {
172 LOGE("opus_decoder_create: %s for sample_rate: %d, channels:%d",
174 return false;
175 }
176 active = true;
177 return true;
178 }
179
180 void end() override {
181 TRACED();
182 dec = nullptr;
183 if (release_on_end) {
184 outbuf.resize(0);
185 decbuf.resize(0);
186 }
187 active = false;
188 }
189
190 void setAudioInfo(AudioInfo from) override {
192 info = from;
194 cfg.channels = from.channels;
196 }
197
199 size_t write(const uint8_t *data, size_t len) override {
200 if (!active || p_print == nullptr) return 0;
201 // decode data
202 LOGD("OpusAudioDecoder::write: %d", (int)len);
204 int frame_count = cfg.max_buffer_size / cfg.channels / sizeof(opus_int16);
205 int out_samples =
206 opus_decode(dec, (uint8_t *)data, len, (opus_int16 *)outbuf.data(),
208 if (out_samples < 0) {
209 LOGW("opus-decode: %s", opus_strerror(out_samples));
210 } else if (out_samples > 0) {
211 // write data to final destination
212 int out_bytes = out_samples * cfg.channels * sizeof(int16_t);
213 LOGD("opus-decode: %d", out_bytes);
214 int open = out_bytes;
215 int processed = 0;
216 while (open > 0) {
217 int to_write = std::min(open, cfg.max_buffer_write_size);
218 int written = p_print->write(outbuf.data() + processed, to_write);
219 open -= written;
220 processed += written;
221 }
222 }
223 return len;
224 }
225
226 operator bool() override { return active; }
227
231
232 protected:
233 Print *p_print = nullptr;
234 OpusDecoder *dec = nullptr;
236 bool active = false;
239 const uint32_t valid_rates[5] = {8000, 12000, 16000, 24000, 48000};
240 bool release_on_end = false;
241
242 bool isValidRate(int rate) {
243 for (auto &valid : valid_rates) {
244 if (valid == rate) return true;
245 }
246 return false;
247 }
248};
249
261 public:
262 // Empty Constructor - the output stream must be provided with begin()
263 OpusAudioEncoder() = default;
264
265 // Constructor providing the output stream
267
270
272 const char *mime() override { return "audio/opus"; }
273
275 void setAudioInfo(AudioInfo from) override {
278 cfg.channels = from.channels;
280 }
281
283 bool begin() override {
284 int err;
285 int size = getFrameSizeSamples(cfg.sample_rate) * 2;
286 frame.resize(size);
287 assert(frame.data() != nullptr);
289 &err);
290 if (err != OPUS_OK) {
291 LOGE("opus_encoder_create: %s for sample_rate: %d, channels:%d",
293 return false;
294 }
295 is_open = settings();
296 return true;
297 }
298
301
303
305 cfg = settings;
306 return begin();
307 }
308
310 void end() override {
311 // flush buffered data
312 encodeFrame();
313 // release memory
315 is_open = false;
316 }
317
319 size_t write(const uint8_t *data, size_t len) override {
320 if (!is_open || p_print == nullptr) return 0;
321 LOGD("OpusAudioEncoder::write: %d", (int)len);
322
323 // fill frame
324 for (int j = 0; j < len; j++) {
325 encodeByte(data[j]);
326 }
327 return len;
328 }
329
330 operator bool() override { return is_open; }
331
332 bool isOpen() { return is_open; }
333
334 protected:
335 Print *p_print = nullptr;
336 OpusEncoder *enc = nullptr;
338 bool is_open = false;
340 int frame_pos = 0;
341
342 void encodeByte(uint8_t data) {
343 // add byte to frame
344 frame[frame_pos++] = data;
345
346 // if frame is complete -> encode
347 if (frame_pos >= frame.size()) {
348 encodeFrame();
349 frame_pos = 0;
350 }
351 }
352
353 void encodeFrame() {
354 if (frame.size() > 0) {
355 // allocate temp buffer on stack
356 int packet_len =
358 uint8_t packet[packet_len];
359
360 int frames = frame.size() / cfg.channels / sizeof(int16_t);
361 LOGD("opus_encode - frame_size: %d", frames);
362 int len = opus_encode(enc, (opus_int16 *)frame.data(), frames, packet,
363 packet_len);
364 if (len < 0) {
365 LOGE("opus_encode: %s", opus_strerror(len));
366 } else if (len > 0) {
367 LOGD("opus-encode: %d", len);
368 int eff = p_print->write(packet, len);
369 if (eff != len) {
370 LOGE("encodeFrame data lost: %d->%d", len, eff);
371 }
372 }
373 }
374 }
375
377 int getFrameSizeSamples(int sampling_rate) {
378 switch (cfg.frame_sizes_ms_x2) {
380 return sampling_rate / 400;
382 return sampling_rate / 200;
384 return sampling_rate / 100;
386 return sampling_rate / 50;
388 return sampling_rate / 25;
390 return 3 * sampling_rate / 50;
392 return 4 * sampling_rate / 50;
394 return 5 * sampling_rate / 50;
396 return 6 * sampling_rate / 50;
397 }
398 return sampling_rate / 100;
399 }
400
401 bool settings() {
402 bool ok = true;
403 if (cfg.bitrate >= 0 &&
405 LOGE("invalid bitrate: %d", cfg.bitrate);
406 ok = false;
407 }
408 if (cfg.force_channel >= 0 &&
410 OPUS_OK) {
411 LOGE("invalid force_channel: %d", cfg.force_channel);
412 ok = false;
413 };
414 if (cfg.vbr >= 0 &&
416 LOGE("invalid vbr: %d", cfg.vbr);
417 ok = false;
418 }
419 if (cfg.vbr_constraint >= 0 &&
421 OPUS_OK) {
422 LOGE("invalid vbr_constraint: %d", cfg.vbr_constraint);
423 ok = false;
424 }
425 if (cfg.complexity >= 0 &&
427 LOGE("invalid complexity: %d", cfg.complexity);
428 ok = false;
429 }
430 if (cfg.max_bandwidth >= 0 &&
432 OPUS_OK) {
433 LOGE("invalid max_bandwidth: %d", cfg.max_bandwidth);
434 ok = false;
435 }
436 if (cfg.signal >= 0 &&
438 LOGE("invalid signal: %d", cfg.signal);
439 ok = false;
440 }
441 if (cfg.inband_fec >= 0 &&
443 LOGE("invalid inband_fec: %d", cfg.inband_fec);
444 ok = false;
445 }
446 if (cfg.packet_loss_perc >= 0 &&
449 LOGE("invalid pkt_loss: %d", cfg.packet_loss_perc);
450 ok = false;
451 }
452 if (cfg.lsb_depth >= 0 &&
454 LOGE("invalid lsb_depth: %d", cfg.lsb_depth);
455 ok = false;
456 }
457 if (cfg.prediction_disabled >= 0 &&
460 LOGE("invalid pred_disabled: %d", cfg.prediction_disabled);
461 ok = false;
462 }
463 if (cfg.use_dtx >= 0 &&
465 LOGE("invalid use_dtx: %d", cfg.use_dtx);
466 ok = false;
467 }
468 if (cfg.frame_sizes_ms_x2 > 0 &&
471 LOGE("invalid frame_sizes_ms_x2: %d", cfg.frame_sizes_ms_x2);
472 ok = false;
473 }
474 return ok;
475 }
476};
477
478} // namespace audio_tools
#define LOGW(...)
Definition AudioLoggerIDF.h:29
#define TRACED()
Definition AudioLoggerIDF.h:31
#define LOGD(...)
Definition AudioLoggerIDF.h:27
#define LOGE(...)
Definition AudioLoggerIDF.h:30
#define OPUS_DEC_MAX_BUFFER_SIZE
Definition CodecOpus.h:12
#define OPUS_ENC_MAX_BUFFER_SIZE
Definition CodecOpus.h:8
#define assert(T)
Definition avr.h:10
Decoding of encoded audio into PCM data.
Definition AudioCodecsBase.h:18
AudioInfo info
Definition AudioCodecsBase.h:76
void setAudioInfo(AudioInfo from) override
for most decoders this is not needed
Definition AudioCodecsBase.h:28
Encoding of PCM data.
Definition AudioCodecsBase.h:97
void setAudioInfo(AudioInfo from) override
Defines the sample rate, number of channels and bits per sample.
Definition AudioCodecsBase.h:106
void notifyAudioChange(AudioInfo info)
Definition AudioTypes.h:178
Decoder for the Opus audio format. Each Opus frame must be provided with one write() call....
Definition CodecOpus.h:121
OpusAudioDecoder(Print &out_stream)
Construct a new OpusDecoder object.
Definition CodecOpus.h:133
bool active
Definition CodecOpus.h:236
void setOutput(Print &out_stream) override
Defines the output Stream.
Definition CodecOpus.h:139
Vector< uint8_t > outbuf
Definition CodecOpus.h:237
bool begin(OpusSettings settings)
Definition CodecOpus.h:147
OpusAudioDecoder(bool releaseOnEnd=false)
Construct a new OpusDecoder object.
Definition CodecOpus.h:126
OpusDecoder * dec
Definition CodecOpus.h:234
void setAudioInfo(AudioInfo from) override
for most decoders this is not needed
Definition CodecOpus.h:190
void end() override
Definition CodecOpus.h:180
Vector< uint8_t > decbuf
Definition CodecOpus.h:238
size_t write(const uint8_t *data, size_t len) override
write one full opus frame
Definition CodecOpus.h:199
OpusSettings cfg
Definition CodecOpus.h:235
const uint32_t valid_rates[5]
Definition CodecOpus.h:239
bool release_on_end
Definition CodecOpus.h:240
bool isValidRate(int rate)
Definition CodecOpus.h:242
void setReleaseOnEnd(bool flag)
Definition CodecOpus.h:230
OpusSettings & config()
Provides access to the configuration.
Definition CodecOpus.h:144
bool begin() override
Definition CodecOpus.h:155
Print * p_print
Definition CodecOpus.h:233
OpusSettings & defaultConfig()
Definition CodecOpus.h:145
AudioInfo audioInfo() override
provides the actual input AudioInfo
Definition CodecOpus.h:141
Encode for Opus audio.
Definition CodecOpus.h:260
bool is_open
Definition CodecOpus.h:338
void setOutput(Print &out_stream) override
Defines the output Stream.
Definition CodecOpus.h:269
bool isOpen()
Definition CodecOpus.h:332
bool begin(OpusEncoderSettings settings)
Definition CodecOpus.h:304
void setAudioInfo(AudioInfo from) override
We actually do nothing with this.
Definition CodecOpus.h:275
void end() override
stops the processing
Definition CodecOpus.h:310
OpusAudioEncoder(Print &out)
Definition CodecOpus.h:266
OpusEncoderSettings cfg
Definition CodecOpus.h:337
void encodeFrame()
Definition CodecOpus.h:353
size_t write(const uint8_t *data, size_t len) override
Writes PCM data to be encoded as Opus.
Definition CodecOpus.h:319
OpusEncoderSettings & config()
Provides access to the configuration.
Definition CodecOpus.h:300
OpusEncoder * enc
Definition CodecOpus.h:336
bool settings()
Definition CodecOpus.h:401
const char * mime() override
Provides "audio/pcm".
Definition CodecOpus.h:272
int frame_pos
Definition CodecOpus.h:340
bool begin() override
starts the processing using the actual OpusAudioInfo
Definition CodecOpus.h:283
Print * p_print
Definition CodecOpus.h:335
Vector< uint8_t > frame
Definition CodecOpus.h:339
void encodeByte(uint8_t data)
Definition CodecOpus.h:342
int getFrameSizeSamples(int sampling_rate)
Returns the frame size in samples.
Definition CodecOpus.h:377
OpusEncoderSettings & defaultConfig()
Definition CodecOpus.h:302
Definition NoArduino.h:62
virtual size_t write(const uint8_t *data, size_t len)
Definition NoArduino.h:126
Vector implementation which provides the most important methods as defined by std::vector....
Definition Vector.h:21
bool resize(int newSize, T value)
Definition Vector.h:266
T * data()
Definition Vector.h:316
int size()
Definition Vector.h:178
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition AudioCodecsBase.h:10
size_t writeData(Print *p_out, T *data, int samples, int maxSamples=512)
Definition AudioTypes.h:512
Basic Audio information which drives e.g. I2S.
Definition AudioTypes.h:55
sample_rate_t sample_rate
Sample Rate: e.g 44100.
Definition AudioTypes.h:57
uint16_t channels
Number of channels: 2=stereo, 1=mono.
Definition AudioTypes.h:59
uint8_t bits_per_sample
Number of bits per sample (int16_t = 16 bits)
Definition AudioTypes.h:61
Setting for Opus Encoder where the following values are valid: -1 indicates that the default value sh...
Definition CodecOpus.h:68
int vbr
0, 1
Definition CodecOpus.h:82
int vbr_constraint
0, 1
Definition CodecOpus.h:84
int frame_sizes_ms_x2
OPUS_FRAMESIZE_2_5_MS,OPUS_FRAMESIZE_5_MS,OPUS_FRAMESIZE_10_MS,OPUS_FRAMESIZE_20_MS,...
Definition CodecOpus.h:105
int inband_fec
0, 1
Definition CodecOpus.h:95
OpusEncoderSettings()
Definition CodecOpus.h:69
int use_dtx
0, 1
Definition CodecOpus.h:103
int packet_loss_perc
0, 1, 2, 5
Definition CodecOpus.h:97
int complexity
0 to 10
Definition CodecOpus.h:86
int force_channel
OPUS_AUTO, OPUS_AUTO, 1, 2.
Definition CodecOpus.h:80
int signal
OPUS_AUTO, OPUS_SIGNAL_VOICE, OPUS_SIGNAL_MUSIC.
Definition CodecOpus.h:93
int bitrate
Definition CodecOpus.h:78
int prediction_disabled
0, 1
Definition CodecOpus.h:101
int max_bandwidth
Definition CodecOpus.h:91
int lsb_depth
8, 24
Definition CodecOpus.h:99
int application
Definition CodecOpus.h:75
Setting for Opus Decoder.
Definition CodecOpus.h:22
OpusSettings()
Definition CodecOpus.h:23
int max_buffer_size
Definition CodecOpus.h:31
int max_buffer_write_size
Definition CodecOpus.h:32