Raw ↗
+ +
2da5fe7 OpenAVX v0.2.0 - High-performance open-standard IP audio and video transport suite
saifmukhtar · 2026-11-24
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * src/avx_audio_codec.c - Opus runtime loader and IMA ADPCM codec
7 */
8  
9 #define _POSIX_C_SOURCE 200809L
10 #define _GNU_SOURCE
11 #include "avx_platform.h"
12 #include "avx_audio_codec.h"
13 #include "avx_internal.h"
14 #include "avx_wire.h"
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <math.h>
19  
20 #if defined(_WIN32)
21 #include <windows.h>
22 #else
23 #include <dlfcn.h>
24 #endif
25  
26 /* ========================================================================= */
27 /* 1. OPUS CONSTANTS & DYNAMIC LOADER PROTOTYPES */
28 /* ========================================================================= */
29  
30 #define OPUS_APPLICATION_VOIP 2048
31 #define OPUS_APPLICATION_AUDIO 2049
32 #define OPUS_APPLICATION_RESTRICTED_LOWDELAY 2051
33 #define OPUS_SIGNAL_MUSIC 3002
34 #define OPUS_SET_BITRATE_REQUEST 4002
35 #define OPUS_SET_COMPLEXITY_REQUEST 4010
36 #define OPUS_SET_SIGNAL_REQUEST 4024
37 #define OPUS_AUTO -1000
38 #define OPUS_OK 0
39  
40 typedef void* (*fn_opus_ms_encoder_create)(int Fs, int channels, int streams, int coupled_streams,
41 const unsigned char *mapping, int application, int *error);
42 typedef void (*fn_opus_ms_encoder_destroy)(void *st);
43 typedef int (*fn_opus_ms_encode_float)(void *st, const float *pcm, int frame_size,
44 unsigned char *data, int max_data_bytes);
45 typedef int (*fn_opus_ms_encoder_ctl)(void *st, int request, ...);
46  
47 typedef void* (*fn_opus_ms_decoder_create)(int Fs, int channels, int streams, int coupled_streams,
48 const unsigned char *mapping, int *error);
49 typedef void (*fn_opus_ms_decoder_destroy)(void *st);
50 typedef int (*fn_opus_ms_decode_float)(void *st, const unsigned char *data, int len,
51 float *pcm, int frame_size, int decode_fec);
52  
53 static struct {
54 void* handle;
55 bool available;
56 bool probed;
57 avx_mutex_t lock;
58  
59 fn_opus_ms_encoder_create ms_encoder_create;
60 fn_opus_ms_encoder_destroy ms_encoder_destroy;
61 fn_opus_ms_encode_float ms_encode_float;
62 fn_opus_ms_encoder_ctl ms_encoder_ctl;
63  
64 fn_opus_ms_decoder_create ms_decoder_create;
65 fn_opus_ms_decoder_destroy ms_decoder_destroy;
66 fn_opus_ms_decode_float ms_decode_float;
67 } g_opus = {
68 .handle = NULL,
69 .available = false,
70 .probed = false,
71 .lock = AVX_MUTEX_INITIALIZER
72 };
73  
74 /* Dynamically probes and binds libopus shared library symbols at runtime with thread-safe locking. */
75 static void probe_opus_library(void) {
76 avx_mutex_lock(&g_opus.lock);
77 if (g_opus.probed) {
78 avx_mutex_unlock(&g_opus.lock);
79 return;
80 }
81 g_opus.probed = true;
82  
83 const char *lib_names[] = {
84 #if defined(_WIN32)
85 "opus.dll", "libopus-0.dll", "libopus.dll"
86 #elif defined(__APPLE__)
87 "libopus.0.dylib", "libopus.dylib",
88 "/opt/homebrew/lib/libopus.0.dylib", "/usr/local/lib/libopus.0.dylib"
89 #else
90 "libopus.so.0", "libopus.so",
91 "/usr/lib64/libopus.so.0", "/usr/lib/x86_64-linux-gnu/libopus.so.0",
92 "/usr/lib/aarch64-linux-gnu/libopus.so.0"
93 #endif
94 };
95  
96 void *h = NULL;
97 for (size_t i = 0; i < sizeof(lib_names) / sizeof(lib_names[0]); ++i) {
98 #if defined(_WIN32)
99 h = (void*)LoadLibraryA(lib_names[i]);
100 #else
101 h = dlopen(lib_names[i], RTLD_NOW | RTLD_LOCAL);
102 #endif
103 if (h) break;
104 }
105  
106 if (!h) {
107 avx_mutex_unlock(&g_opus.lock);
108 return;
109 }
110  
111 #if defined(_WIN32)
112 #define LOAD_SYM(name) (GetProcAddress((HMODULE)h, #name))
113 #else
114 #define LOAD_SYM(name) (dlsym(h, #name))
115 #endif
116  
117 g_opus.ms_encoder_create = (fn_opus_ms_encoder_create)LOAD_SYM(opus_multistream_encoder_create);
118 g_opus.ms_encoder_destroy = (fn_opus_ms_encoder_destroy)LOAD_SYM(opus_multistream_encoder_destroy);
119 g_opus.ms_encode_float = (fn_opus_ms_encode_float)LOAD_SYM(opus_multistream_encode_float);
120 g_opus.ms_encoder_ctl = (fn_opus_ms_encoder_ctl)LOAD_SYM(opus_multistream_encoder_ctl);
121  
122 g_opus.ms_decoder_create = (fn_opus_ms_decoder_create)LOAD_SYM(opus_multistream_decoder_create);
123 g_opus.ms_decoder_destroy = (fn_opus_ms_decoder_destroy)LOAD_SYM(opus_multistream_decoder_destroy);
124 g_opus.ms_decode_float = (fn_opus_ms_decode_float)LOAD_SYM(opus_multistream_decode_float);
125  
126 #undef LOAD_SYM
127  
128 if (g_opus.ms_encoder_create && g_opus.ms_encoder_destroy &&
129 g_opus.ms_encode_float && g_opus.ms_encoder_ctl &&
130 g_opus.ms_decoder_create && g_opus.ms_decoder_destroy &&
131 g_opus.ms_decode_float) {
132 g_opus.handle = h;
133 g_opus.available = true;
134 } else {
135 #if defined(_WIN32)
136 FreeLibrary((HMODULE)h);
137 #else
138 dlclose(h);
139 #endif
140 }
141  
142 avx_mutex_unlock(&g_opus.lock);
143 }
144  
145 bool avx_audio_codec_has_opus(void) {
146 if (!g_opus.probed) {
147 probe_opus_library();
148 }
149 return g_opus.available;
150 }
151  
152 /* ========================================================================= */
153 /* 2. CHANNEL MAPPING (SMPTE / ITU-R <-> VORBIS FAMILY 1) */
154 /* ========================================================================= */
155  
156 typedef struct {
157 int streams;
158 int coupled_streams;
159 unsigned char mapping[16];
160 } opus_channel_config_t;
161  
162 /* Maps broadcast SMPTE / ITU-R channel ordering to Vorbis family 1 multistream Opus layout. */
163 static bool get_opus_channel_config(int channels, opus_channel_config_t *cfg) {
164 if (!cfg || channels < 1 || channels > 8) return false;
165 memset(cfg, 0, sizeof(*cfg));
166  
167 switch (channels) {
168 case 1: /* Mono */
169 cfg->streams = 1;
170 cfg->coupled_streams = 0;
171 cfg->mapping[0] = 0;
172 break;
173 case 2: /* Stereo */
174 cfg->streams = 1;
175 cfg->coupled_streams = 1;
176 cfg->mapping[0] = 0;
177 cfg->mapping[1] = 1;
178 break;
179 case 4: /* Quadraphonic */
180 cfg->streams = 2;
181 cfg->coupled_streams = 2;
182 cfg->mapping[0] = 0;
183 cfg->mapping[1] = 1;
184 cfg->mapping[2] = 2;
185 cfg->mapping[3] = 3;
186 break;
187 case 6: /* 5.1 Surround */
188 cfg->streams = 4;
189 cfg->coupled_streams = 2;
190 /* Vorbis stream assignment:
191 * Stream 0 (coupled): L, R -> slots 0, 1
192 * Stream 1 (uncoupled): C -> slot 2
193 * Stream 2 (coupled): BL, BR -> slots 3, 4
194 * Stream 3 (uncoupled): LFE -> slot 5
195 */
196 cfg->mapping[0] = 0; /* FL */
197 cfg->mapping[1] = 2; /* C */
198 cfg->mapping[2] = 1; /* FR */
199 cfg->mapping[3] = 3; /* BL */
200 cfg->mapping[4] = 4; /* BR */
201 cfg->mapping[5] = 5; /* LFE */
202 break;
203 case 8: /* 7.1 Surround */
204 cfg->streams = 5;
205 cfg->coupled_streams = 3;
206 cfg->mapping[0] = 0; /* FL */
207 cfg->mapping[1] = 2; /* C */
208 cfg->mapping[2] = 1; /* FR */
209 cfg->mapping[3] = 3; /* BL */
210 cfg->mapping[4] = 4; /* BR */
211 cfg->mapping[5] = 5; /* SL */
212 cfg->mapping[6] = 6; /* SR */
213 cfg->mapping[7] = 7; /* LFE */
214 break;
215 default: {
216 int count = (channels > 8) ? 8 : (channels < 1 ? 1 : channels);
217 cfg->streams = count;
218 cfg->coupled_streams = 0;
219 for (int i = 0; i < count; ++i) {
220 cfg->mapping[i] = (unsigned char)i;
221 }
222 break;
223 }
224 }
225 return true;
226 }
227  
228 /* Interleaves planar SMPTE floats into interleaved Vorbis array */
229 static void smpte_planar_to_vorbis_interleaved(
230 const float* const* in_planes,
231 float* out_interleaved,
232 int channels,
233 int frames
234 ) {
235 if (channels == 1) {
236 memcpy(out_interleaved, in_planes[0], (size_t)frames * sizeof(float));
237 } else if (channels == 2) {
238 for (int i = 0; i < frames; ++i) {
239 out_interleaved[i * 2 + 0] = in_planes[0][i];
240 out_interleaved[i * 2 + 1] = in_planes[1][i];
241 }
242 } else if (channels == 4) {
243 for (int i = 0; i < frames; ++i) {
244 out_interleaved[i * 4 + 0] = in_planes[0][i];
245 out_interleaved[i * 4 + 1] = in_planes[1][i];
246 out_interleaved[i * 4 + 2] = in_planes[2][i];
247 out_interleaved[i * 4 + 3] = in_planes[3][i];
248 }
249 } else if (channels == 6) {
250 /* SMPTE: [FL, FR, C, LFE, BL, BR] -> Vorbis: [FL, C, FR, BL, BR, LFE] */
251 for (int i = 0; i < frames; ++i) {
252 out_interleaved[i * 6 + 0] = in_planes[0][i]; /* FL */
253 out_interleaved[i * 6 + 1] = in_planes[2][i]; /* C */
254 out_interleaved[i * 6 + 2] = in_planes[1][i]; /* FR */
255 out_interleaved[i * 6 + 3] = in_planes[4][i]; /* BL */
256 out_interleaved[i * 6 + 4] = in_planes[5][i]; /* BR */
257 out_interleaved[i * 6 + 5] = in_planes[3][i]; /* LFE */
258 }
259 } else if (channels == 8) {
260 /* SMPTE: [FL, FR, C, LFE, BL, BR, SL, SR] -> Vorbis: [FL, C, FR, BL, BR, SL, SR, LFE] */
261 for (int i = 0; i < frames; ++i) {
262 out_interleaved[i * 8 + 0] = in_planes[0][i]; /* FL */
263 out_interleaved[i * 8 + 1] = in_planes[2][i]; /* C */
264 out_interleaved[i * 8 + 2] = in_planes[1][i]; /* FR */
265 out_interleaved[i * 8 + 3] = in_planes[4][i]; /* BL */
266 out_interleaved[i * 8 + 4] = in_planes[5][i]; /* BR */
267 out_interleaved[i * 8 + 5] = in_planes[6][i]; /* SL */
268 out_interleaved[i * 8 + 6] = in_planes[7][i]; /* SR */
269 out_interleaved[i * 8 + 7] = in_planes[3][i]; /* LFE */
270 }
271 } else {
272 for (int i = 0; i < frames; ++i) {
273 for (int c = 0; c < channels; ++c) {
274 out_interleaved[i * channels + c] = in_planes[c][i];
275 }
276 }
277 }
278 }
279  
280 /* De-interleaves Vorbis array into planar SMPTE floats */
281 static void vorbis_interleaved_to_smpte_planar(
282 const float* in_interleaved,
283 float* const* out_planes,
284 int channels,
285 int frames
286 ) {
287 if (channels == 1) {
288 memcpy(out_planes[0], in_interleaved, (size_t)frames * sizeof(float));
289 } else if (channels == 2) {
290 for (int i = 0; i < frames; ++i) {
291 out_planes[0][i] = in_interleaved[i * 2 + 0];
292 out_planes[1][i] = in_interleaved[i * 2 + 1];
293 }
294 } else if (channels == 4) {
295 for (int i = 0; i < frames; ++i) {
296 out_planes[0][i] = in_interleaved[i * 4 + 0];
297 out_planes[1][i] = in_interleaved[i * 4 + 1];
298 out_planes[2][i] = in_interleaved[i * 4 + 2];
299 out_planes[3][i] = in_interleaved[i * 4 + 3];
300 }
301 } else if (channels == 6) {
302 /* Vorbis: [FL, C, FR, BL, BR, LFE] -> SMPTE: [FL, FR, C, LFE, BL, BR] */
303 for (int i = 0; i < frames; ++i) {
304 out_planes[0][i] = in_interleaved[i * 6 + 0]; /* FL */
305 out_planes[1][i] = in_interleaved[i * 6 + 2]; /* FR */
306 out_planes[2][i] = in_interleaved[i * 6 + 1]; /* C */
307 out_planes[3][i] = in_interleaved[i * 6 + 5]; /* LFE */
308 out_planes[4][i] = in_interleaved[i * 6 + 3]; /* BL */
309 out_planes[5][i] = in_interleaved[i * 6 + 4]; /* BR */
310 }
311 } else if (channels == 8) {
312 /* Vorbis: [FL, C, FR, BL, BR, SL, SR, LFE] -> SMPTE: [FL, FR, C, LFE, BL, BR, SL, SR] */
313 for (int i = 0; i < frames; ++i) {
314 out_planes[0][i] = in_interleaved[i * 8 + 0]; /* FL */
315 out_planes[1][i] = in_interleaved[i * 8 + 2]; /* FR */
316 out_planes[2][i] = in_interleaved[i * 8 + 1]; /* C */
317 out_planes[3][i] = in_interleaved[i * 8 + 7]; /* LFE */
318 out_planes[4][i] = in_interleaved[i * 8 + 3]; /* BL */
319 out_planes[5][i] = in_interleaved[i * 8 + 4]; /* BR */
320 out_planes[6][i] = in_interleaved[i * 8 + 5]; /* SL */
321 out_planes[7][i] = in_interleaved[i * 8 + 6]; /* SR */
322 }
323 } else {
324 for (int i = 0; i < frames; ++i) {
325 for (int c = 0; c < channels; ++c) {
326 out_planes[c][i] = in_interleaved[i * channels + c];
327 }
328 }
329 }
330 }
331  
332 /* ========================================================================= */
333 /* 3. PURE C99 IMA ADPCM ENCODER / DECODER */
334 /* ========================================================================= */
335  
336 static const int ima_step_table[89] = {
337 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
338 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
339 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
340 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
341 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
342 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
343 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
344 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
345 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
346 };
347  
348 static const int ima_index_table[16] = {
349 -1, -1, -1, -1, 2, 4, 6, 8,
350 -1, -1, -1, -1, 2, 4, 6, 8
351 };
352  
353 static inline int16_t float_to_s16(float f) {
354 if (isnan(f)) return 0;
355 if (f <= -1.0f) return -32767;
356 if (f >= 1.0f) return 32767;
357 return (int16_t)roundf(f * 32767.0f);
358 }
359  
360 static inline float s16_to_float(int16_t s) {
361 return (float)s / 32767.0f;
362 }
363  
364 static inline uint8_t encode_ima_nibble(int16_t sample, int *predicted, int *index) {
365 int diff = sample - *predicted;
366 int sign = 0;
367 if (diff < 0) {
368 sign = 8;
369 diff = -diff;
370 }
371 int step = ima_step_table[*index];
372 int delta = 0;
373 int vpdiff = step >> 3;
374  
375 if (diff >= step) {
376 delta |= 4;
377 diff -= step;
378 vpdiff += step;
379 }
380 step >>= 1;
381 if (diff >= step) {
382 delta |= 2;
383 diff -= step;
384 vpdiff += step;
385 }
386 step >>= 1;
387 if (diff >= step) {
388 delta |= 1;
389 vpdiff += step;
390 }
391  
392 if (sign) *predicted -= vpdiff;
393 else *predicted += vpdiff;
394  
395 if (*predicted > 32767) *predicted = 32767;
396 if (*predicted < -32768) *predicted = -32768;
397  
398 *index += ima_index_table[delta];
399 if (*index < 0) *index = 0;
400 if (*index > 88) *index = 88;
401  
402 return (uint8_t)(delta | sign);
403 }
404  
405 static inline int16_t decode_ima_nibble(uint8_t nibble, int *predicted, int *index) {
406 int step = ima_step_table[*index];
407 int delta = nibble & 7;
408 int vpdiff = step >> 3;
409  
410 if (delta & 4) vpdiff += step;
411 if (delta & 2) vpdiff += (step >> 1);
412 if (delta & 1) vpdiff += (step >> 2);
413  
414 if (nibble & 8) *predicted -= vpdiff;
415 else *predicted += vpdiff;
416  
417 if (*predicted > 32767) *predicted = 32767;
418 if (*predicted < -32768) *predicted = -32768;
419  
420 *index += ima_index_table[delta];
421 if (*index < 0) *index = 0;
422 if (*index > 88) *index = 88;
423  
424 return (int16_t)*predicted;
425 }
426  
427 /* Pure C99 4-bit IMA ADPCM encoder using 89-step adaptive delta quantization table. */
428 size_t avx_adpcm_encode_planar_float(
429 const float* const* in_planes,
430 int channels,
431 int samples,
432 uint8_t* out_buf,
433 size_t max_out_bytes
434 ) {
435 if (!in_planes || channels < 1 || channels > OAVX_MAX_AUDIO_CHANNELS || samples <= 0 || !out_buf) return 0;
436  
437 /* Header:
438 * 2 bytes magic (0x4441 = "AD")
439 * 2 bytes channels
440 * 4 bytes samples
441 * Per channel: 2 bytes initial valprev + 1 byte initial index + 1 byte padding (4 bytes per ch)
442 */
443 size_t hdr_size = 8 + (size_t)channels * 4;
444 size_t nibbles_per_ch = (samples > 1) ? (size_t)(samples - 1) : 0;
445 size_t bytes_per_ch = (nibbles_per_ch + 1) / 2;
446 size_t needed = hdr_size + (size_t)channels * bytes_per_ch;
447  
448 if (needed > max_out_bytes) return 0;
449  
450 out_buf[0] = 0x41; /* 'A' */
451 out_buf[1] = 0x44; /* 'D' */
452 out_buf[2] = (uint8_t)(channels & 0xFF);
453 out_buf[3] = (uint8_t)((channels >> 8) & 0xFF);
454 out_buf[4] = (uint8_t)(samples & 0xFF);
455 out_buf[5] = (uint8_t)((samples >> 8) & 0xFF);
456 out_buf[6] = (uint8_t)((samples >> 16) & 0xFF);
457 out_buf[7] = (uint8_t)((samples >> 24) & 0xFF);
458  
459 size_t payload_offset = hdr_size;
460  
461 for (int c = 0; c < channels; ++c) {
462 int predicted = float_to_s16(in_planes[c][0]);
463 int index = 0;
464 if (samples > 1) {
465 int init_diff = abs(float_to_s16(in_planes[c][1]) - predicted);
466 while (index < 88 && ima_step_table[index + 1] <= init_diff) {
467 index++;
468 }
469 }
470  
471 /* Write initial state */
472 size_t st_off = 8 + (size_t)c * 4;
473 out_buf[st_off + 0] = (uint8_t)(predicted & 0xFF);
474 out_buf[st_off + 1] = (uint8_t)((predicted >> 8) & 0xFF);
475 out_buf[st_off + 2] = (uint8_t)index;
476 out_buf[st_off + 3] = 0;
477  
478 /* Encode remaining samples as packed 4-bit nibbles */
479 size_t ch_out = payload_offset + (size_t)c * bytes_per_ch;
480 for (int s = 1; s < samples; s += 2) {
481 uint8_t n0 = encode_ima_nibble(float_to_s16(in_planes[c][s]), &predicted, &index);
482 uint8_t n1 = 0;
483 if (s + 1 < samples) {
484 n1 = encode_ima_nibble(float_to_s16(in_planes[c][s + 1]), &predicted, &index);
485 }
486 out_buf[ch_out++] = (uint8_t)(n0 | (n1 << 4));
487 }
488 }
489  
490 return needed;
491 }
492  
493 int avx_adpcm_decode_to_planar_float(
494 const uint8_t* in_buf,
495 size_t in_bytes,
496 int channels,
497 float* const* out_planes,
498 int max_samples
499 ) {
500 if (!in_buf || in_bytes < 8 || channels < 1 || channels > OAVX_MAX_AUDIO_CHANNELS || !out_planes || max_samples <= 0) return -1;
501  
502 if (in_buf[0] != 0x41 || in_buf[1] != 0x44) return -1;
503 uint32_t pkt_ch = (uint32_t)in_buf[2] | ((uint32_t)in_buf[3] << 8);
504 uint32_t samples_u = (uint32_t)in_buf[4] | ((uint32_t)in_buf[5] << 8) |
505 ((uint32_t)in_buf[6] << 16) | ((uint32_t)in_buf[7] << 24);
506  
507 if (pkt_ch != (uint32_t)channels || samples_u == 0 || samples_u > (uint32_t)max_samples) return -1;
508 int samples = (int)samples_u;
509  
510 size_t hdr_size = 8 + (size_t)channels * 4;
511 size_t nibbles_per_ch = (samples > 1) ? (size_t)(samples - 1) : 0;
512 size_t bytes_per_ch = (nibbles_per_ch + 1) / 2;
513 size_t expected_size = hdr_size + (size_t)channels * bytes_per_ch;
514  
515 if (in_bytes < expected_size) return -1;
516  
517 size_t payload_offset = hdr_size;
518  
519 for (int c = 0; c < channels; ++c) {
520 size_t st_off = 8 + (size_t)c * 4;
521 int predicted = (int16_t)(in_buf[st_off + 0] | (in_buf[st_off + 1] << 8));
522 int index = in_buf[st_off + 2];
523 if (index > 88) index = 88;
524  
525 out_planes[c][0] = s16_to_float((int16_t)predicted);
526  
527 size_t ch_in = payload_offset + (size_t)c * bytes_per_ch;
528 for (int s = 1; s < samples; s += 2) {
529 uint8_t byte = in_buf[ch_in++];
530 uint8_t n0 = byte & 0x0F;
531 uint8_t n1 = (byte >> 4) & 0x0F;
532  
533 out_planes[c][s] = s16_to_float(decode_ima_nibble(n0, &predicted, &index));
534 if (s + 1 < samples) {
535 out_planes[c][s + 1] = s16_to_float(decode_ima_nibble(n1, &predicted, &index));
536 }
537 }
538 }
539  
540 return samples;
541 }
542  
543 /* ========================================================================= */
544 /* 4. HIGH-LEVEL AUDIO ENCODER & DECODER IMPLEMENTATION */
545 /* ========================================================================= */
546  
547 #define OPUS_FRAME_SIZE_48K 960 /* 20 ms @ 48 kHz */
548 #define MAX_AUDIO_CHANNELS OAVX_MAX_AUDIO_CHANNELS
549 #define ACCUM_CAPACITY 19200 /* 400 ms cushion */
550  
551 struct avx_audio_encoder_t {
552 int sample_rate;
553 int channels;
554 avx_audio_codec_type_e codec_type;
555 uint32_t fourcc;
556 int bitrate_kbps;
557  
558 /* Opus Multistream State */
559 void *opus_ms_enc;
560 float *interleaved_pcm;
561  
562 /* Sample Accumulator for irregular frame sizes */
563 float *accum_planes[MAX_AUDIO_CHANNELS];
564 int accum_samples;
565 int64_t accum_start_pts;
566 };
567  
568 avx_audio_encoder_t* avx_audio_encoder_create(
569 int sample_rate,
570 int channels,
571 avx_audio_codec_type_e preferred_codec,
572 int bitrate_kbps
573 ) {
574 if (sample_rate <= 0 || channels < 1 || channels > MAX_AUDIO_CHANNELS) return NULL;
575  
576 avx_audio_encoder_t *enc = (avx_audio_encoder_t*)calloc(1, sizeof(*enc));
577 if (!enc) return NULL;
578  
579 enc->sample_rate = sample_rate;
580 enc->channels = channels;
581 enc->bitrate_kbps = bitrate_kbps;
582  
583 for (int c = 0; c < channels; ++c) {
584 enc->accum_planes[c] = (float*)malloc((size_t)ACCUM_CAPACITY * sizeof(float));
585 if (!enc->accum_planes[c]) {
586 avx_audio_encoder_destroy(enc);
587 return NULL;
588 }
589 }
590  
591 /* Decide codec */
592 bool want_opus = (preferred_codec == AVX_AUDIO_CODEC_OPUS);
593 bool opus_ok = false;
594  
595 if (want_opus && avx_audio_codec_has_opus()) {
596 opus_channel_config_t cfg;
597 if (get_opus_channel_config(channels, &cfg)) {
598 int err = OPUS_OK;
599 enc->opus_ms_enc = g_opus.ms_encoder_create(
600 sample_rate, channels, cfg.streams, cfg.coupled_streams,
601 cfg.mapping, OPUS_APPLICATION_AUDIO, &err
602 );
603 if (enc->opus_ms_enc && err == OPUS_OK) {
604 opus_ok = true;
605 int target_br = bitrate_kbps > 0 ? (bitrate_kbps * 1000) : (64000 * channels);
606 g_opus.ms_encoder_ctl(enc->opus_ms_enc, OPUS_SET_BITRATE_REQUEST, target_br);
607 g_opus.ms_encoder_ctl(enc->opus_ms_enc, OPUS_SET_COMPLEXITY_REQUEST, 10);
608 g_opus.ms_encoder_ctl(enc->opus_ms_enc, OPUS_SET_SIGNAL_REQUEST, OPUS_SIGNAL_MUSIC);
609  
610 enc->interleaved_pcm = (float*)malloc((size_t)OPUS_FRAME_SIZE_48K * (size_t)channels * sizeof(float));
611 if (!enc->interleaved_pcm) {
612 avx_audio_encoder_destroy(enc);
613 return NULL;
614 }
615 }
616 }
617 }
618  
619 if (opus_ok) {
620 enc->codec_type = AVX_AUDIO_CODEC_OPUS;
621 enc->fourcc = OAVX_FOURCC_AUDIO_TYPE_OPUS;
622 } else {
623 enc->codec_type = AVX_AUDIO_CODEC_ADPCM;
624 enc->fourcc = OAVX_FOURCC_AUDIO_TYPE_ADPC;
625 }
626  
627 return enc;
628 }
629  
630 void avx_audio_encoder_destroy(avx_audio_encoder_t* enc) {
631 if (!enc) return;
632 if (enc->opus_ms_enc && g_opus.ms_encoder_destroy) {
633 g_opus.ms_encoder_destroy(enc->opus_ms_enc);
634 }
635 free(enc->interleaved_pcm);
636 for (int c = 0; c < MAX_AUDIO_CHANNELS; ++c) {
637 free(enc->accum_planes[c]);
638 }
639 free(enc);
640 }
641  
642 avx_audio_codec_type_e avx_audio_encoder_get_codec(const avx_audio_encoder_t* enc) {
643 return enc ? enc->codec_type : AVX_AUDIO_CODEC_NONE;
644 }
645  
646 uint32_t avx_audio_encoder_get_fourcc(const avx_audio_encoder_t* enc) {
647 return enc ? enc->fourcc : 0;
648 }
649  
650 /* Buffers planar PCM samples into accumulation queue with timestamp alignment for 20 ms frames. */
651 bool avx_audio_encoder_feed(
652 avx_audio_encoder_t* enc,
653 const float* const* planes,
654 int frames,
655 int64_t pts_ns
656 ) {
657 if (!enc || !planes || frames <= 0) return false;
658  
659 if (enc->accum_samples + frames > ACCUM_CAPACITY) {
660 /* Drop oldest or clamp to prevent overflow */
661 enc->accum_samples = 0;
662 }
663  
664 if (enc->accum_samples == 0) {
665 enc->accum_start_pts = pts_ns;
666 }
667  
668 for (int c = 0; c < enc->channels; ++c) {
669 memcpy(enc->accum_planes[c] + enc->accum_samples, planes[c], (size_t)frames * sizeof(float));
670 }
671 enc->accum_samples += frames;
672 return true;
673 }
674  
675 /* Encodes accumulated 20 ms PCM frames (960 samples @ 48kHz) via multistream Opus or IMA ADPCM. */
676 bool avx_audio_encoder_pull(
677 avx_audio_encoder_t* enc,
678 uint8_t* out_pkt,
679 size_t max_pkt_size,
680 size_t* out_pkt_size,
681 int* out_samples,
682 int64_t* out_pts_ns,
683 uint32_t* out_codec_fourcc
684 ) {
685 if (!enc || !out_pkt || !out_pkt_size || !out_samples || !out_pts_ns || !out_codec_fourcc) {
686 return false;
687 }
688  
689 if (enc->codec_type == AVX_AUDIO_CODEC_ADPCM) {
690 if (enc->accum_samples <= 0) return false;
691  
692 size_t encoded = avx_adpcm_encode_planar_float(
693 (const float* const*)enc->accum_planes,
694 enc->channels,
695 enc->accum_samples,
696 out_pkt,
697 max_pkt_size
698 );
699 if (encoded == 0) return false;
700  
701 *out_pkt_size = encoded;
702 *out_samples = enc->accum_samples;
703 *out_pts_ns = enc->accum_start_pts;
704 *out_codec_fourcc = enc->fourcc;
705  
706 enc->accum_samples = 0;
707 return true;
708 }
709  
710 if (enc->codec_type == AVX_AUDIO_CODEC_OPUS) {
711 if (enc->accum_samples < OPUS_FRAME_SIZE_48K) return false;
712  
713 /* Interleave 960 samples with SMPTE -> Vorbis ordering */
714 smpte_planar_to_vorbis_interleaved(
715 (const float* const*)enc->accum_planes,
716 enc->interleaved_pcm,
717 enc->channels,
718 OPUS_FRAME_SIZE_48K
719 );
720  
721 int bytes = g_opus.ms_encode_float(
722 enc->opus_ms_enc,
723 enc->interleaved_pcm,
724 OPUS_FRAME_SIZE_48K,
725 out_pkt,
726 (int)max_pkt_size
727 );
728 if (bytes <= 0) return false;
729  
730 *out_pkt_size = (size_t)bytes;
731 *out_samples = OPUS_FRAME_SIZE_48K;
732 *out_pts_ns = enc->accum_start_pts;
733 *out_codec_fourcc = enc->fourcc;
734  
735 /* Shift remaining samples down */
736 enc->accum_samples -= OPUS_FRAME_SIZE_48K;
737 if (enc->accum_samples > 0) {
738 for (int c = 0; c < enc->channels; ++c) {
739 memmove(enc->accum_planes[c],
740 enc->accum_planes[c] + OPUS_FRAME_SIZE_48K,
741 (size_t)enc->accum_samples * sizeof(float));
742 }
743 int64_t step_ns = (int64_t)((double)OPUS_FRAME_SIZE_48K * 1000000000.0 / enc->sample_rate);
744 enc->accum_start_pts += step_ns;
745 }
746  
747 return true;
748 }
749  
750 return false;
751 }
752  
753 bool avx_audio_encoder_flush(
754 avx_audio_encoder_t* enc,
755 uint8_t* out_pkt,
756 size_t max_pkt_size,
757 size_t* out_pkt_size,
758 int* out_samples,
759 int64_t* out_pts_ns,
760 uint32_t* out_codec_fourcc
761 ) {
762 if (!enc || enc->accum_samples <= 0) return false;
763  
764 if (enc->codec_type == AVX_AUDIO_CODEC_ADPCM) {
765 return avx_audio_encoder_pull(enc, out_pkt, max_pkt_size, out_pkt_size, out_samples, out_pts_ns, out_codec_fourcc);
766 }
767  
768 if (enc->codec_type == AVX_AUDIO_CODEC_OPUS) {
769 /* Zero pad to 960 */
770 int pad = OPUS_FRAME_SIZE_48K - enc->accum_samples;
771 if (pad > 0) {
772 for (int c = 0; c < enc->channels; ++c) {
773 memset(enc->accum_planes[c] + enc->accum_samples, 0, (size_t)pad * sizeof(float));
774 }
775 enc->accum_samples = OPUS_FRAME_SIZE_48K;
776 }
777 return avx_audio_encoder_pull(enc, out_pkt, max_pkt_size, out_pkt_size, out_samples, out_pts_ns, out_codec_fourcc);
778 }
779  
780 return false;
781 }
782  
783 /* ========================================================================= */
784 /* 5. AUDIO DECODER IMPLEMENTATION */
785 /* ========================================================================= */
786  
787 struct avx_audio_decoder_t {
788 int sample_rate;
789 int channels;
790 uint32_t fourcc;
791  
792 /* Opus Multistream State */
793 void *opus_ms_dec;
794 float *interleaved_pcm;
795 };
796  
797 avx_audio_decoder_t* avx_audio_decoder_create(
798 int sample_rate,
799 int channels,
800 uint32_t codec_fourcc
801 ) {
802 if (sample_rate <= 0 || channels < 1 || channels > MAX_AUDIO_CHANNELS) return NULL;
803  
804 avx_audio_decoder_t *dec = (avx_audio_decoder_t*)calloc(1, sizeof(*dec));
805 if (!dec) return NULL;
806  
807 dec->sample_rate = sample_rate;
808 dec->channels = channels;
809 dec->fourcc = codec_fourcc;
810  
811 if (codec_fourcc == OAVX_FOURCC_AUDIO_TYPE_OPUS && avx_audio_codec_has_opus()) {
812 opus_channel_config_t cfg;
813 if (get_opus_channel_config(channels, &cfg)) {
814 int err = OPUS_OK;
815 dec->opus_ms_dec = g_opus.ms_decoder_create(
816 sample_rate, channels, cfg.streams, cfg.coupled_streams,
817 cfg.mapping, &err
818 );
819 if (dec->opus_ms_dec && err == OPUS_OK) {
820 /* Max frame size: 5760 samples (120ms) */
821 dec->interleaved_pcm = (float*)malloc(5760 * (size_t)channels * sizeof(float));
822 if (!dec->interleaved_pcm) {
823 avx_audio_decoder_destroy(dec);
824 return NULL;
825 }
826 }
827 }
828 }
829  
830 return dec;
831 }
832  
833 void avx_audio_decoder_destroy(avx_audio_decoder_t* dec) {
834 if (!dec) return;
835 if (dec->opus_ms_dec && g_opus.ms_decoder_destroy) {
836 g_opus.ms_decoder_destroy(dec->opus_ms_dec);
837 }
838 free(dec->interleaved_pcm);
839 free(dec);
840 }
841  
842 int avx_audio_decoder_decode(
843 avx_audio_decoder_t* dec,
844 uint32_t codec_fourcc,
845 const uint8_t* pkt_data,
846 size_t pkt_size,
847 float* const* out_planes,
848 int max_samples
849 ) {
850 if (!dec || !pkt_data || pkt_size == 0 || !out_planes || max_samples <= 0) return -1;
851  
852 if (codec_fourcc == OAVX_FOURCC_AUDIO_TYPE_ADPC) {
853 return avx_adpcm_decode_to_planar_float(pkt_data, pkt_size, dec->channels, out_planes, max_samples);
854 }
855  
856 if (codec_fourcc == OAVX_FOURCC_AUDIO_TYPE_OPUS) {
857 if (!dec->opus_ms_dec || !g_opus.ms_decode_float || !dec->interleaved_pcm) return -1;
858  
859 int decoded_frames = g_opus.ms_decode_float(
860 dec->opus_ms_dec,
861 pkt_data,
862 (int)pkt_size,
863 dec->interleaved_pcm,
864 max_samples,
865 0
866 );
867 if (decoded_frames <= 0) return -1;
868  
869 vorbis_interleaved_to_smpte_planar(
870 dec->interleaved_pcm,
871 out_planes,
872 dec->channels,
873 decoded_frames
874 );
875 return decoded_frames;
876 }
877  
878 return -1;
879 }