ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
opus.c
Go to the documentation of this file.
1
6
10#include <ascii-chat/common.h>
12#include <ascii-chat/otel.h>
13#include <opus.h>
14#include <stdlib.h>
15#include <string.h>
16
17/* ============================================================================
18 * Encoder Creation
19 * ============================================================================
20 */
21
23 int bitrate) {
24 if (!encoder || bitrate < 6000 || bitrate > 510000)
25 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid Opus encoder or bitrate: %d",
26 bitrate);
27 int result = opus_encoder_ctl(encoder, OPUS_SET_BITRATE(bitrate));
28 if (result == OPUS_OK)
29 result = opus_encoder_ctl(encoder, OPUS_SET_VBR(1));
30 // Ordered streams retain silence packets so playout timing remains
31 // continuous.
32 if (result == OPUS_OK)
33 result = opus_encoder_ctl(encoder, OPUS_SET_DTX(0));
34 if (result != OPUS_OK)
35 return SET_ERRNO(ERROR_AUDIO, "Opus configuration failed: %s",
36 opus_strerror(result));
37 return ASCIICHAT_OK;
38}
39
41 int sample_rate, int bitrate) {
42 return opus_codec_create_encoder_channels(application, sample_rate, bitrate,
44}
45
47 int sample_rate, int bitrate,
48 int channels) {
49 ASCII_OTEL_SCOPE(OPUS_ENCODER_CREATE);
50 ASCII_OTEL_ATTR_INT("audio.sample_rate", sample_rate);
51 ASCII_OTEL_ATTR_INT("audio.bitrate", bitrate);
52 if (sample_rate <= 0 || bitrate <= 0 || (channels != 1 && channels != 2)) {
54 "Invalid codec parameters: sample_rate=%d, bitrate=%d",
55 sample_rate, bitrate);
56 return NULL;
57 }
58
60 if (!codec) {
61 SET_ERRNO(ERROR_MEMORY, "Failed to allocate opus codec context");
62 return NULL;
63 }
64
65 // Create encoder
66 int error = OPUS_OK;
67 codec->encoder =
68 opus_encoder_create(sample_rate, channels, (int)application, &error);
69 if (error != OPUS_OK || !codec->encoder) {
70 SET_ERRNO(ERROR_AUDIO, "Failed to create Opus encoder: %s",
71 opus_strerror(error));
72 SAFE_FREE(codec);
73 return NULL;
74 }
75
76 if (audio_opus_configure_encoder(codec->encoder, bitrate) != ASCIICHAT_OK) {
77 opus_encoder_destroy(codec->encoder);
78 SAFE_FREE(codec);
79 return NULL;
80 }
81
82 codec->decoder = NULL;
83 codec->sample_rate = sample_rate;
84 codec->channels = channels;
85 codec->bitrate = bitrate;
86 codec->tmp_buffer = NULL;
87
89 "Opus encoder created: sample_rate=%d, bitrate=%d bps, continuous VBR",
90 sample_rate, bitrate);
91
92 // Register Opus encoder for debugging
93 NAMED_REGISTER_CONTEXT(codec, "opus_encoder", "opus_codec", NULL);
94
95 return codec;
96}
97
98/* ============================================================================
99 * Decoder Creation
100 * ============================================================================
101 */
102
106
108 int channels) {
109 ASCII_OTEL_SCOPE(OPUS_DECODER_CREATE);
110 ASCII_OTEL_ATTR_INT("audio.sample_rate", sample_rate);
111 if (sample_rate <= 0 || (channels != 1 && channels != 2)) {
112 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid sample rate: %d", sample_rate);
113 return NULL;
114 }
115
117 if (!codec) {
118 SET_ERRNO(ERROR_MEMORY, "Failed to allocate opus codec context");
119 return NULL;
120 }
121
122 // Create decoder
123 int error = OPUS_OK;
124 codec->decoder = opus_decoder_create(sample_rate, channels, &error);
125 if (error != OPUS_OK || !codec->decoder) {
126 SET_ERRNO(ERROR_AUDIO, "Failed to create Opus decoder: %s",
127 opus_strerror(error));
128 SAFE_FREE(codec);
129 return NULL;
130 }
131
132 codec->encoder = NULL;
133 codec->sample_rate = sample_rate;
134 codec->channels = channels;
135 codec->bitrate = 0; // N/A for decoder
136 codec->tmp_buffer = NULL;
137
138 log_debug("Opus decoder created: sample_rate=%d", sample_rate);
139
140 // Register Opus decoder for debugging
141 NAMED_REGISTER_CONTEXT(codec, "opus_decoder", "opus_codec", NULL);
142
143 return codec;
144}
145
146/* ============================================================================
147 * Encoding
148 * ============================================================================
149 */
150
151size_t opus_codec_encode(opus_codec_t *codec, const float *samples,
152 int num_samples, uint8_t *out_data, size_t out_size) {
153 ASCII_OTEL_SCOPE(OPUS_CODEC_ENCODE);
154 ASCII_OTEL_ATTR_STRING("audio.codec", "opus");
155 ASCII_OTEL_ATTR_INT("audio.frame.samples", num_samples);
156 ASCII_OTEL_ATTR_INT("audio.output.capacity", (int64_t)out_size);
157 if (!codec || !codec->encoder || !samples || num_samples <= 0 || !out_data ||
158 out_size == 0 || num_samples % codec->channels != 0) {
160 "Invalid encode parameters: codec=%p, encoder=%p, samples=%p, "
161 "num_samples=%d, out_data=%p, "
162 "out_size=%zu",
163 (void *)codec, (void *)(codec ? codec->encoder : NULL),
164 (const void *)samples, num_samples, (void *)out_data, out_size);
165 return 0;
166 }
167
168 ASCII_OTEL_ATTR_INT("audio.sample_rate", codec->sample_rate);
169 ASCII_OTEL_ATTR_INT("audio.bitrate", codec->bitrate);
170 ASCII_OTEL_ATTR_INT("audio.channels", codec->channels);
171 // Encode frame
172 opus_int32 encoded_bytes =
173 opus_encode_float(codec->encoder, samples, num_samples / codec->channels,
174 out_data, (opus_int32)out_size);
175
176 if (encoded_bytes < 0) {
177 SET_ERRNO(ERROR_AUDIO, "Opus encoding failed: %s",
178 opus_strerror((int)encoded_bytes));
179 return 0;
180 }
181
182 if (encoded_bytes == 0) {
183 // DTX frame (silence) - encoder produced zero bytes
184 log_debug_every(LOG_RATE_VERY_FAST, "Opus DTX frame (silence detected)");
185 }
186
187 ascii_otel_metric(ASCII_OTEL_METRIC_OPUS_BYTES, encoded_bytes);
188 ascii_otel_metric(ASCII_OTEL_METRIC_OPUS_ENCODE_SAMPLES, num_samples);
189 ASCII_OTEL_ATTR_INT("audio.packet.size", encoded_bytes);
190 return (size_t)encoded_bytes;
191}
192
193/* ============================================================================
194 * Decoding
195 * ============================================================================
196 */
197
198int opus_codec_decode(opus_codec_t *codec, const uint8_t *data, size_t data_len,
199 float *out_samples, int out_num_samples) {
200 ASCII_OTEL_SCOPE(OPUS_CODEC_DECODE);
201 ASCII_OTEL_ATTR_STRING("audio.codec", "opus");
202 ASCII_OTEL_ATTR_INT("audio.packet.size", (int64_t)data_len);
203 ASCII_OTEL_ATTR_INT("audio.packet_loss_concealment", !data || !data_len);
204 if (!codec || !codec->decoder || !out_samples || out_num_samples <= 0 ||
205 out_num_samples % codec->channels != 0) {
207 "Invalid decode parameters: codec=%p, decoder=%p, "
208 "out_samples=%p, out_num_samples=%d",
209 (void *)codec, (void *)(codec ? codec->decoder : NULL),
210 (void *)out_samples, out_num_samples);
211 return -1;
212 }
213
214 ASCII_OTEL_ATTR_INT("audio.sample_rate", codec->sample_rate);
215 ASCII_OTEL_ATTR_INT("audio.channels", codec->channels);
216 ASCII_OTEL_ATTR_INT("audio.output.capacity_samples", out_num_samples);
217 // If data is NULL, use PLC (Packet Loss Concealment)
218 if (!data || data_len == 0) {
219 log_debug_every(LOG_RATE_VERY_FAST, "Opus PLC (Packet Loss Concealment)");
220 int samples = opus_decode_float(codec->decoder, NULL, 0, out_samples,
221 out_num_samples / codec->channels, 0);
222 if (samples < 0) {
223 SET_ERRNO(ERROR_AUDIO, "Opus PLC failed: %s", opus_strerror(samples));
224 return -1;
225 }
226 ascii_otel_metric(ASCII_OTEL_METRIC_OPUS_DECODE_SAMPLES, samples);
227 ascii_otel_metric(ASCII_OTEL_METRIC_OPUS_PLC_FRAMES, 1);
228 ASCII_OTEL_ATTR_INT("audio.frame.samples", samples);
229 return samples * codec->channels;
230 }
231
232 // Decode frame
233 int samples =
234 opus_decode_float(codec->decoder, data, (opus_int32)data_len, out_samples,
235 out_num_samples / codec->channels, 0);
236
237 if (samples < 0) {
238 SET_ERRNO(ERROR_AUDIO, "Opus decoding failed: %s", opus_strerror(samples));
239 return -1;
240 }
241
242 ascii_otel_metric(ASCII_OTEL_METRIC_OPUS_DECODE_BYTES, (double)data_len);
243 ASCII_OTEL_ATTR_INT("audio.frame.samples", samples);
244 ascii_otel_metric(ASCII_OTEL_METRIC_OPUS_DECODE_SAMPLES, samples);
245 return samples * codec->channels;
246}
247
248/* ============================================================================
249 * Configuration
250 * ============================================================================
251 */
252
254 ASCII_OTEL_SCOPE(OPUS_CODEC_SET_BITRATE);
255 if (!codec || !codec->encoder || bitrate <= 0) {
256 return SET_ERRNO(
258 "Invalid bitrate parameters: codec=%p, encoder=%p, bitrate=%d",
259 (void *)codec, (void *)(codec ? codec->encoder : NULL), bitrate);
260 }
261
262 int error = opus_encoder_ctl(codec->encoder, OPUS_SET_BITRATE(bitrate));
263 if (error != OPUS_OK) {
264 return SET_ERRNO(ERROR_AUDIO, "Failed to set Opus bitrate: %s",
265 opus_strerror(error));
266 }
267
268 codec->bitrate = bitrate;
269 log_debug("Opus bitrate changed to %d bps", bitrate);
270
271 return ASCIICHAT_OK;
272}
273
275 if (!codec || !codec->encoder) {
276 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid codec for bitrate query");
277 return -1;
278 }
279
280 opus_int32 bitrate = 0;
281 int error = opus_encoder_ctl(codec->encoder, OPUS_GET_BITRATE(&bitrate));
282 if (error != OPUS_OK) {
283 SET_ERRNO(ERROR_AUDIO, "Failed to get Opus bitrate: %s",
284 opus_strerror(error));
285 return -1;
286 }
287
288 return (int)bitrate;
289}
290
292 ASCII_OTEL_SCOPE(OPUS_DTX);
293 ASCII_OTEL_ATTR_INT("audio.dtx.enabled", enable != 0);
294 if (!codec || !codec->encoder) {
296 "Invalid codec for DTX configuration");
297 }
298
299 int error = opus_encoder_ctl(codec->encoder, OPUS_SET_DTX(enable ? 1 : 0));
300 if (error != OPUS_OK) {
301 return SET_ERRNO(ERROR_AUDIO, "Failed to set Opus DTX: %s",
302 opus_strerror(error));
303 }
304
305 log_debug("Opus DTX %s", enable ? "enabled" : "disabled");
306
307 return ASCIICHAT_OK;
308}
309
310/* ============================================================================
311 * Lifecycle
312 * ============================================================================
313 */
314
316 if (!codec) {
317 return;
318 }
319
320 NAMED_UNREGISTER(codec);
321
322 if (codec->encoder) {
323 opus_encoder_destroy(codec->encoder);
324 codec->encoder = NULL;
325 }
326
327 if (codec->decoder) {
328 opus_decoder_destroy(codec->decoder);
329 codec->decoder = NULL;
330 }
331
332 if (codec->tmp_buffer) {
333 SAFE_FREE(codec->tmp_buffer);
334 codec->tmp_buffer = NULL;
335 }
336
337 SAFE_FREE(codec);
338}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define AUDIO_CHANNELS
Named object registry for debugging — log identifiable resource names.
opus_codec_t * opus_codec_create_decoder(int sample_rate)
Create an Opus decoder.
Definition opus.c:103
asciichat_error_t opus_codec_set_bitrate(opus_codec_t *codec, int bitrate)
Set encoder bitrate.
Definition opus.c:253
asciichat_error_t audio_opus_configure_encoder(OpusEncoder *encoder, int bitrate)
Definition opus.c:22
opus_application_t
State for one Opus encoding or decoding direction.
Definition opus.h:91
int opus_codec_decode(opus_codec_t *codec, const uint8_t *data, size_t data_len, float *out_samples, int out_num_samples)
Decode Opus audio frame.
Definition opus.c:198
opus_codec_t * opus_codec_create_encoder(opus_application_t application, int sample_rate, int bitrate)
Create an Opus encoder.
Definition opus.c:40
int opus_codec_get_bitrate(opus_codec_t *codec)
Get current encoder bitrate.
Definition opus.c:274
asciichat_error_t opus_codec_set_dtx(opus_codec_t *codec, int enable)
Enable/disable DTX (Discontinuous Transmission).
Definition opus.c:291
void opus_codec_destroy(opus_codec_t *codec)
Destroy an Opus codec instance.
Definition opus.c:315
size_t opus_codec_encode(opus_codec_t *codec, const float *samples, int num_samples, uint8_t *out_data, size_t out_size)
Encode audio frame with Opus.
Definition opus.c:151
opus_codec_t * opus_codec_create_decoder_channels(int sample_rate, int channels)
Definition opus.c:107
struct OpusEncoder OpusEncoder
opus_codec_t * opus_codec_create_encoder_channels(opus_application_t application, int sample_rate, int bitrate, int channels)
Definition opus.c:46
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned char uint8_t
#define NAMED_REGISTER_CONTEXT(context, context_type, name, parent_ptr)
Register a generic context with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_AUDIO
Definition error_codes.h:66
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define LOG_RATE_VERY_FAST
Log rate limit: 0.1 seconds (100,000 microseconds) - for very high frequency operations.
Definition log_rates.h:28
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
Opus audio codec wrapper for real-time encoding/decoding.
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
🔤 String Manipulation and Shell Escaping Utilities
State for one Opus encoding or decoding direction.
Definition opus.h:113
uint8_t * tmp_buffer
Temporary buffer for internal use.
Definition opus.h:119
int bitrate
Bitrate in bits per second (encoder only).
Definition opus.h:118
int channels
PCM channels (1 or 2); sample counts include all channels.
Definition opus.h:117
int sample_rate
Sample rate in Hz (e.g., 44100).
Definition opus.h:116
OpusEncoder * encoder
Encoder state (NULL if decoder).
Definition opus.h:114
OpusDecoder * decoder
Decoder state (NULL if encoder).
Definition opus.h:115