Move non-UI audio into std with Android PCM and async sinks

This commit is contained in:
waozi committed 2026-11-16 21:46:29 -03:00
1 parent 617dd0ede2
commit dd0aff6424
77 files changed
+4324 -648

No files matched your search

+2 -2
View File
@@ -31,7 +31,7 @@ jobs:
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
- name: Install ripgrep, MinGW, Wine, Vorbis, ARMv7 and Wasm tools, and the private display for the test scripts
timeout-minutes: 5
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip gcc-mingw-w64-x86-64 wine wine64 xvfb xauth ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip gcc-mingw-w64-x86-64 wine wine64 xvfb xauth libsdl2-dev emscripten ffmpeg libvorbis-dev python3-markdown gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user clang-18 lld-18
- name: Keep compile results between runs
uses: ./.github/actions/compile-cache
with:
@@ -87,7 +87,7 @@ jobs:
run: cd "$RUNNER_TEMP" && go mod download github.com/klauspost/[email protected]
- name: Install ripgrep and Vorbis for the test scripts
timeout-minutes: 5
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip ffmpeg libvorbis-dev python3-markdown
run: sh scripts/ci_packages.sh ccache ripgrep zip unzip xvfb xauth libsdl2-dev emscripten ffmpeg libvorbis-dev python3-markdown
- name: Keep compile results between runs
uses: ./.github/actions/compile-cache
with:
+2 -1
View File
@@ -2,7 +2,8 @@
## [Unreleased]
- ZX lowering folds signed integer interval checks such as `value > 1000 || value < 0` into one unsigned comparison when both sides read the same stable local, record member or fixed-array element. Calls and other expressions whose second evaluation can matter retain short-circuit evaluation.
- Audio mixing, PCM streams, Ogg/Vorbis inspection and streaming/seek, WAV/MP3 decoding and SDL/WebAudio output are core standard modules independent of Kryon. Android streams through AAudio on API 26+ and OpenSL ES on API 21–25, with the same mixer and sink contract as desktop.
- Loop invariant hoisting leaves standalone constants and symbolic addresses near their uses while retaining useful invariant expressions. This reduces spills in vector growth loops; the matched Alpha Vectors kernel improves from 85.8 to 42.5 µs with unchanged results.
- `bench/standard/` holds the benchmarks people use to compare languages, in Ziran, C and Go with every input read at run time: recursive Fibonacci, n-body, spectral-norm, mandelbrot, fannkuch-redux, binary-trees, fasta, nqueens, integer matrix multiplication, quicksort and FNV-1a string hashing. `bench/wasm_tier.py --standard` runs them as C (`cc -O2`), Go, native ZX and Wasm on Alpha's physical host and checks every result against C, at diagnostic sizes or the Benchmarks Game sizes (`--standard-full`); `bench/bench.zi -- standard-compile` times whole-suite builds for each target. The small-kernel table gains independent Go references. The website shows the results, and `bench/results/standard/gaps.md` ranks where native ZX trails C: on spectral-norm, fasta, binary-trees and matmul the same program runs much closer to C as Wasm, so the native backend is the gap there.
+13
View File
@@ -862,6 +862,12 @@ check: all $(BIN_DIR)/check-runner $(BIN_DIR)/bundle-link-test $(BIN_DIR)/host-c
zx-wasm-test: all
env -u DISPLAY -u WAYLAND_DISPLAY tests/zx_wasm.sh $(BIN_DIR)/ziran
# Optional decoder for std/audio_mp3; no SDL or other UI dependency.
.PHONY: audio-mp3
audio-mp3:
cmake -S std/native -B $(BUILD_DIR)/audio/native -DCMAKE_C_COMPILER=$(CC)
cmake --build $(BUILD_DIR)/audio/native --target ziran_mp3
# Native ZX on an Android device: ANDROID_ARCH is aarch64 or armv7.
# android-build cross-builds libziran.a and zi2zx with the NDK for
# ANDROID_API; the compilers that run during that build are this host's.
@@ -880,6 +886,13 @@ ANDROID_TOOLCHAIN = $(ANDROID_NDK)/toolchains/llvm/prebuilt/linux-x86_64/bin
ANDROID_TRIPLE_aarch64 = aarch64-linux-android
ANDROID_TRIPLE_armv7 = armv7a-linux-androideabi
ANDROID_OUT = $(abspath $(ANDROID_BUILD_DIR))
# Real-device streaming PCM test, separate from native ZX parity.
.PHONY: audio-android-test
audio-android-test: $(BIN_DIR)/ziran
@test -n "$(ANDROID_SERIAL)" || { echo 'set ANDROID_SERIAL' >&2; exit 1; }
env -u DISPLAY -u WAYLAND_DISPLAY $(BIN_DIR)/ziran run --target=c --root tests tests/audio_android_cases.zi -- \
$(abspath $(BIN_DIR)/ziran) $(BUILD_DIR)/audio/android-test '$(ANDROID_NDK)' '$(ANDROID_SERIAL)'
.PHONY: android-build android-parity
android-build: $(BIN_DIR)/zi2c
@test -n "$(ANDROID_NDK)" || { echo 'set ANDROID_NDK or ANDROID_NDK_HOME' >&2; exit 1; }
@@ -686,8 +686,6 @@ static int32_t compiler_zir_lower_UnsignedOf(int32_t bits) ZIRAN_MAYBE_UNUSED;
static int32_t compiler_zir_lower_ConstantArray(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t identity) ZIRAN_MAYBE_UNUSED;
static int32_t compiler_zir_lower_Compound(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t identity, int32_t depth) ZIRAN_MAYBE_UNUSED;
static LirOp compiler_zir_lower_Binary(uint8_t* op) ZIRAN_MAYBE_UNUSED;
static bool compiler_zir_lower_SameBoundsValue(AssemblyProgram* program, AssemblyFunction* function, int32_t left, int32_t right, int32_t depth) ZIRAN_MAYBE_UNUSED;
static int32_t compiler_zir_lower_BoundsDisjunction(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t depth) ZIRAN_MAYBE_UNUSED;
static int32_t compiler_zir_lower_Select(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t condition, int32_t yes_root, int32_t no_root, int32_t short_circuit, int32_t depth) ZIRAN_MAYBE_UNUSED;
static int32_t compiler_zir_lower_LowerSlice(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t result_type, int32_t depth) ZIRAN_MAYBE_UNUSED;
static uint8_t* compiler_zir_lower_PrintServiceName(int32_t service) ZIRAN_MAYBE_UNUSED;
@@ -8069,391 +8067,6 @@ compiler_zir_lower_Binary(uint8_t* op)
return (LirOp)(0);
}
static bool
compiler_zir_lower_SameBoundsValue(AssemblyProgram* program, AssemblyFunction* function, int32_t left, int32_t right, int32_t depth)
{
if (depth > 32 || left < 0 || right < 0 || left >= function->source->expr_count || right >= function->source->expr_count) {
return false;
}
ZirExpr* a = &(function->source->exprs[left]);
ZirExpr* b = &(function->source->exprs[right]);
AssemblyProgram* value_0 = program;
ZirSourceSpan value_1 = a->span;
int32_t value_2 = 0;
{
AssemblyProgram* program = value_0;
ZirSourceSpan span = value_1;
if (program->failed != 0) {
value_2 = 0;
goto value_3;
}
int64_t value_4 = program->work;
if (value_4 > 0LL) {
int64_t* value_5 = &(program->work);
(*value_5) = (int64_t)((uint64_t)((*value_5)) - UINT64_C(1));
value_2 = 1;
goto value_3;
}
AssemblyProgram* value_6 = program;
ZirSourceSpan value_7 = span;
String value_8 = StringLiteral("lowering work budget exhausted");
int32_t value_9 = 0;
{
AssemblyProgram* program = value_6;
ZirSourceSpan span = value_7;
String message = value_8;
if (program->failed == 0) {
compiler_zir_lower_SayTarget(span, StringLiteral("assembly.lower"), message);
}
int32_t* value_11 = &(program->failed);
(*value_11) = 1;
value_9 = -1;
}
(void)value_9;
value_2 = 0;
value_3: ;
}
if (value_2 == 0) {
return false;
}
bool value_12 = ((ZirExprKind)(a->kind)) != ((ZirExprKind)(b->kind)) || a->is_move != 0 || b->is_move != 0 || a->checked != b->checked;
bool value_13 = value_12;
bool value_14 = value_13;
if (!value_14) {
String value_15 = compiler_ir_CText((uint8_t*)a->type);
bool value_16 = !StringEqual(value_15, compiler_ir_CText((uint8_t*)b->type));
value_14 = value_16;
}
if (value_14) {
return false;
}
if (((ZirExprKind)(a->kind)) == ((ZirExprKind)(1))) {
bool value_17 = a->is_global_value != 0 || b->is_global_value != 0;
bool value_18 = value_17;
if (!value_18) {
String value_19 = compiler_ir_CText((uint8_t*)a->name);
bool value_20 = !StringEqual(value_19, compiler_ir_CText((uint8_t*)b->name));
value_18 = value_20;
}
if (value_18) {
return false;
}
return compiler_zir_lower_Binding(function, (uint8_t*)a->name) >= 0;
}
if (((ZirExprKind)(a->kind)) == ((ZirExprKind)(2))) {
String value_21 = compiler_ir_CText((uint8_t*)a->text);
return StringEqual(value_21, compiler_ir_CText((uint8_t*)b->text));
}
if (((ZirExprKind)(a->kind)) != ((ZirExprKind)(8)) && ((ZirExprKind)(a->kind)) != ((ZirExprKind)(10))) {
return false;
}
bool value_22 = compiler_zir_lower_SameBoundsValue(program, function, a->left, b->left, (int32_t)((uint32_t)depth + 1u));
if (!value_22) {
return false;
}
AssemblyProgram* value_23 = program;
AssemblyFunction* value_24 = function;
uint8_t* value_25 = (uint8_t*)(function->source->exprs[a->left]).type;
ZirSourceSpan value_26 = a->span;
int32_t value_27 = 0;
{
AssemblyProgram* program = value_23;
AssemblyFunction* function = value_24;
uint8_t* name = value_25;
ZirSourceSpan span = value_26;
value_27 = compiler_zir_lower_TypeIn(program, function->module, name, span, 0);
}
int32_t parent = value_27;
if (parent < 0) {
return false;
}
if (((ZirExprKind)(a->kind)) == ((ZirExprKind)(8))) {
AssemblyProgram* value_29 = program;
LirType* value_30 = (void *)0;
{
AssemblyProgram* program = value_29;
int32_t identity = parent;
value_30 = &(program->types.data[identity]);
}
bool value_32 = ((LirTypeKind)(value_30->kind)) == ((LirTypeKind)(7));
bool value_33 = value_32;
if (value_33) {
String value_34 = compiler_ir_CText((uint8_t*)a->name);
bool value_35 = StringEqual(value_34, compiler_ir_CText((uint8_t*)b->name));
value_33 = value_35;
}
return value_33;
}
AssemblyProgram* value_36 = program;
LirType* value_37 = (void *)0;
{
AssemblyProgram* program = value_36;
int32_t identity = parent;
value_37 = &(program->types.data[identity]);
}
bool value_39 = ((LirTypeKind)(value_37->kind)) == ((LirTypeKind)(6));
return value_39 && compiler_zir_lower_SameBoundsValue(program, function, a->right, b->right, (int32_t)((uint32_t)depth + 1u));
}
static int32_t
compiler_zir_lower_BoundsDisjunction(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t depth)
{
bool value_0 = !StringEqual(compiler_ir_CText(&(expression->op[0])), StringLiteral("||"));
bool value_1 = value_0 || expression->left < 0 || expression->right < 0 || expression->left >= function->source->expr_count;
if (value_1 || expression->right >= function->source->expr_count) {
return -1;
}
ZirExpr* high = &(function->source->exprs[expression->left]);
ZirExpr* low = &(function->source->exprs[expression->right]);
if (StringEqual(compiler_ir_CText(&(high->op[0])), StringLiteral("<"))) {
high = &(function->source->exprs[expression->right]);
low = &(function->source->exprs[expression->left]);
}
bool value_2 = ((ZirExprKind)(high->kind)) != ((ZirExprKind)(6)) || ((ZirExprKind)(low->kind)) != ((ZirExprKind)(6));
bool value_3 = value_2 || high->checked != low->checked;
bool value_4 = value_3 || !StringEqual(compiler_ir_CText(&(high->op[0])), StringLiteral(">"));
bool value_5 = value_4;
bool value_6 = value_5 || !StringEqual(compiler_ir_CText(&(low->op[0])), StringLiteral("<"));
if (value_6 || high->right < 0 || low->right < 0 || high->right >= function->source->expr_count || low->right >= function->source->expr_count) {
return -1;
}
ZirExpr* upper = &(function->source->exprs[high->right]);
ZirExpr* zero = &(function->source->exprs[low->right]);
if (((ZirExprKind)(upper->kind)) != ((ZirExprKind)(2)) || ((ZirExprKind)(zero->kind)) != ((ZirExprKind)(2))) {
return -1;
}
uint64_t bound = 0;
uint64_t bottom = 0;
bool value_7 = zir_f_0fe5ce4064831140_CZirIntegerLiteral((uint8_t*)upper->text, &(bound)) == 0;
bool value_8 = value_7 || zir_f_0fe5ce4064831140_CZirIntegerLiteral((uint8_t*)zero->text, &(bottom)) == 0;
if (value_8 || bottom != 0ULL) {
return -1;
}
bool value_9 = compiler_zir_lower_SameBoundsValue(program, function, high->left, low->left, 0);
if (!value_9) {
return -1;
}
AssemblyProgram* value_10 = program;
AssemblyFunction* value_11 = function;
uint8_t* value_12 = (uint8_t*)(function->source->exprs[high->left]).type;
ZirSourceSpan value_13 = expression->span;
int32_t value_14 = 0;
{
AssemblyProgram* program = value_10;
AssemblyFunction* function = value_11;
uint8_t* name = value_12;
ZirSourceSpan span = value_13;
value_14 = compiler_zir_lower_TypeIn(program, function->module, name, span, 0);
}
int32_t value_type = value_14;
AssemblyProgram* value_16 = program;
AssemblyFunction* value_17 = function;
uint8_t* value_18 = (uint8_t*)upper->type;
ZirSourceSpan value_19 = upper->span;
int32_t value_20 = 0;
{
AssemblyProgram* program = value_16;
AssemblyFunction* function = value_17;
uint8_t* name = value_18;
ZirSourceSpan span = value_19;
value_20 = compiler_zir_lower_TypeIn(program, function->module, name, span, 0);
}
int32_t upper_type = value_20;
AssemblyProgram* value_22 = program;
AssemblyFunction* value_23 = function;
uint8_t* value_24 = (uint8_t*)zero->type;
ZirSourceSpan value_25 = zero->span;
int32_t value_26 = 0;
{
AssemblyProgram* program = value_22;
AssemblyFunction* function = value_23;
uint8_t* name = value_24;
ZirSourceSpan span = value_25;
value_26 = compiler_zir_lower_TypeIn(program, function->module, name, span, 0);
}
int32_t zero_type = value_26;
if (value_type < 0 || upper_type < 0 || zero_type < 0) {
return -1;
}
AssemblyProgram* value_28 = program;
LirType* value_29 = (void *)0;
{
AssemblyProgram* program = value_28;
int32_t identity = value_type;
value_29 = &(program->types.data[identity]);
}
LirType* shape = value_29;
bool value_31 = ((LirTypeKind)(shape->kind)) != ((LirTypeKind)(3)) || !shape->is_signed || shape->bits < 1 || shape->bits > 64;
bool value_32 = value_31;
bool value_33 = value_32;
if (!value_33) {
AssemblyProgram* value_34 = program;
LirType* value_35 = (void *)0;
{
AssemblyProgram* program = value_34;
int32_t identity = upper_type;
value_35 = &(program->types.data[identity]);
}
value_33 = (((LirTypeKind)(value_35->kind)) != ((LirTypeKind)(3)));
}
bool value_37 = value_33;
bool value_38 = value_37;
if (!value_38) {
AssemblyProgram* value_39 = program;
LirType* value_40 = (void *)0;
{
AssemblyProgram* program = value_39;
int32_t identity = upper_type;
value_40 = &(program->types.data[identity]);
}
value_38 = !value_40->is_signed;
}
bool value_42 = value_38;
bool value_43 = value_42;
if (!value_43) {
AssemblyProgram* value_44 = program;
LirType* value_45 = (void *)0;
{
AssemblyProgram* program = value_44;
int32_t identity = zero_type;
value_45 = &(program->types.data[identity]);
}
value_43 = (((LirTypeKind)(value_45->kind)) != ((LirTypeKind)(3)));
}
bool value_47 = value_43;
bool value_48 = value_47;
if (!value_48) {
AssemblyProgram* value_49 = program;
LirType* value_50 = (void *)0;
{
AssemblyProgram* program = value_49;
int32_t identity = zero_type;
value_50 = &(program->types.data[identity]);
}
value_48 = !value_50->is_signed;
}
bool value_52 = value_48;
if (!value_52) {
uint64_t value_53 = (uint64_t)((uint64_t)((ZiShl64(1ULL, (uint64_t)((uint64_t)(((int32_t)((uint32_t)(shape->bits) - 1u)))), 64))) - UINT64_C(1));
value_52 = (bound > value_53);
}
if (value_52) {
return -1;
}
int32_t unsigned_type = -1;
{
int32_t range_first_36 = 0;
int32_t range_last_36 = (int32_t)((uint32_t)(program->types.count) - 1u);
int32_t at = range_first_36;
if (at <= range_last_36) for (;;) {
AssemblyProgram* value_54 = program;
ZirSourceSpan value_55 = expression->span;
int32_t value_56 = 0;
{
AssemblyProgram* program = value_54;
ZirSourceSpan span = value_55;
if (program->failed != 0) {
value_56 = 0;
goto value_57;
}
int64_t value_58 = program->work;
if (value_58 > 0LL) {
int64_t* value_59 = &(program->work);
(*value_59) = (int64_t)((uint64_t)((*value_59)) - UINT64_C(1));
value_56 = 1;
goto value_57;
}
AssemblyProgram* value_60 = program;
ZirSourceSpan value_61 = span;
String value_62 = StringLiteral("lowering work budget exhausted");
int32_t value_63 = 0;
{
AssemblyProgram* program = value_60;
ZirSourceSpan span = value_61;
String message = value_62;
if (program->failed == 0) {
compiler_zir_lower_SayTarget(span, StringLiteral("assembly.lower"), message);
}
int32_t* value_65 = &(program->failed);
(*value_65) = 1;
value_63 = -1;
}
(void)value_63;
value_56 = 0;
value_57: ;
}
if (value_56 == 0) {
return -1;
}
AssemblyProgram* value_66 = program;
LirType* value_67 = (void *)0;
{
AssemblyProgram* program = value_66;
int32_t identity = at;
value_67 = &(program->types.data[identity]);
}
LirType* candidate = value_67;
if (((LirTypeKind)(candidate->kind)) == ((LirTypeKind)(3)) && !candidate->is_signed && candidate->bits == shape->bits) {
unsigned_type = at;
break;
}
if (at == range_last_36) {
break;
}
at = (int32_t)((uint32_t)at + 1u);
}
}
if (unsigned_type < 0) {
return -1;
}
ZirExpr* first = &(function->source->exprs[expression->left]);
bool saved_checking = function->checking;
if (first->checked != 0) {
bool* value_69 = &(function->checking);
(*value_69) = true;
}
AssemblyProgram* value_70 = program;
AssemblyFunction* value_71 = function;
int32_t value_72 = first->left;
int32_t value_73 = (int32_t)((uint32_t)depth + 1u);
int32_t value_74 = 0;
{
AssemblyProgram* program = value_70;
AssemblyFunction* function = value_71;
int32_t root = value_72;
int32_t depth = value_73;
bool saved = function->checking;
if (root >= 0 && root < function->source->expr_count && (function->source->exprs[root]).checked != 0) {
bool* value_76 = &(function->checking);
(*value_76) = true;
}
int32_t value = compiler_zir_lower_ExpressionValue(program, function, root, depth);
bool* value_77 = &(function->checking);
(*value_77) = saved;
if (program->failed != 0 || value < 0 || root < 0 || root >= function->source->expr_count || (function->source->exprs[root]).is_move == 0) {
value_74 = value;
goto value_75;
}
compiler_zir_lower_MoveOut(program, function, root, function->values.data[value], (function->source->exprs[root]).span);
value_74 = value;
value_75: ;
}
int32_t value = value_74;
bool* value_78 = &(function->checking);
(*value_78) = saved_checking;
if (value < 0) {
return -1;
}
value = compiler_zir_lower_Emit(program, function, (LirOp)(24), unsigned_type, &(value), 1, -1, expression->span);
int32_t value_79[2] = {0};
value_79[0] = value;
int32_t value_80 = compiler_zir_lower_Constant(program, function, unsigned_type, bound, expression->span);
value_79[1] = value_80;
int32_t operands[2] = {0};
memmove(operands, value_79, sizeof(operands));
return compiler_zir_lower_Emit(program, function, (LirOp)(21), 1, &(operands[0]), 2, -1, expression->span);
}
static int32_t
compiler_zir_lower_Select(AssemblyProgram* program, AssemblyFunction* function, ZirExpr* expression, int32_t condition, int32_t yes_root, int32_t no_root, int32_t short_circuit, int32_t depth)
{
@@ -32004,12 +31617,6 @@ compiler_zir_lower_ExpressionValue(AssemblyProgram* program, AssemblyFunction* f
return compiler_zir_lower_Emit(value_192, value_193, value_194, 1, compared, 2, -1, expression->span);
}
}
if (StringEqual(compiler_ir_CText(&(expression->op[0])), StringLiteral("||"))) {
int32_t folded = compiler_zir_lower_BoundsDisjunction(program, function, expression, depth);
if (folded >= 0 || program->failed != 0) {
return folded;
}
}
void* value_195 = compiler_zir_lower_Allocate(program, 2, sizeof(int32_t));
int32_t* operands = (int32_t*)(value_195);
if (operands == ((void *)0)) {
-89
View File
@@ -2636,91 +2636,6 @@ Binary :: (op: *u8) -> LIR.LirOp {
return LirOp.Invalid
}
// Repeating a local value, record member or fixed-array element cannot change
// it between two comparisons. Do not extend this to calls, pointer reads,
// slices, moves or arbitrary expressions: their second evaluation matters.
SameBoundsValue :: (program: *AssemblyProgram, function: *AssemblyFunction,
left: s32, right: s32, depth: s32) -> bool {
if depth > 32 || left < 0 || right < 0 ||
left >= function.source.expr_count || right >= function.source.expr_count { return false }
a := *function.source.exprs[left]
b := *function.source.exprs[right]
if Spend(program, a.span) == 0 { return false }
if a.kind != b.kind || a.is_move != 0 || b.is_move != 0 ||
a.checked != b.checked || IR.CText(a.type) != IR.CText(b.type) { return false }
if a.kind == ZirExprKind.IDENT {
if a.is_global_value != 0 || b.is_global_value != 0 ||
IR.CText(a.name) != IR.CText(b.name) { return false }
return Binding(function, a.name) >= 0
}
if a.kind == ZirExprKind.INT { return IR.CText(a.text) == IR.CText(b.text) }
if a.kind != ZirExprKind.MEMBER && a.kind != ZirExprKind.INDEX { return false }
if !SameBoundsValue(program, function, a.left, b.left, depth + 1) { return false }
parent := Type(program, function, function.source.exprs[a.left].type, a.span)
if parent < 0 { return false }
if a.kind == ZirExprKind.MEMBER {
return TypeAt(program, parent).kind == LirTypeKind.Record &&
IR.CText(a.name) == IR.CText(b.name)
}
return TypeAt(program, parent).kind == LirTypeKind.Array &&
SameBoundsValue(program, function, a.right, b.right, depth + 1)
}
// For a signed integer x and a nonnegative literal U that fits x,
// x > U || x < 0 is exactly unsigned(x) > U. Both comparisons must read
// the same stable local value; otherwise retain normal short circuiting.
BoundsDisjunction :: (program: *AssemblyProgram, function: *AssemblyFunction,
expression: *IR.ZirExpr, depth: s32) -> s32 {
if IR.CText(*expression.op[0]) != "||" || expression.left < 0 || expression.right < 0 ||
expression.left >= function.source.expr_count || expression.right >= function.source.expr_count { return -1 }
high := *function.source.exprs[expression.left]
low := *function.source.exprs[expression.right]
if IR.CText(*high.op[0]) == "<" {
high = *function.source.exprs[expression.right]
low = *function.source.exprs[expression.left]
}
if high.kind != ZirExprKind.BINARY || low.kind != ZirExprKind.BINARY || high.checked != low.checked ||
IR.CText(*high.op[0]) != ">" || IR.CText(*low.op[0]) != "<" ||
high.right < 0 || low.right < 0 || high.right >= function.source.expr_count ||
low.right >= function.source.expr_count { return -1 }
upper := *function.source.exprs[high.right]
zero := *function.source.exprs[low.right]
if upper.kind != ZirExprKind.INT || zero.kind != ZirExprKind.INT { return -1 }
bound: u64
bottom: u64
if CZirIntegerLiteral(upper.text, *bound) == 0 ||
CZirIntegerLiteral(zero.text, *bottom) == 0 || bottom != 0 { return -1 }
if !SameBoundsValue(program, function, high.left, low.left, 0) { return -1 }
value_type := Type(program, function, function.source.exprs[high.left].type, expression.span)
upper_type := Type(program, function, upper.type, upper.span)
zero_type := Type(program, function, zero.type, zero.span)
if value_type < 0 || upper_type < 0 || zero_type < 0 { return -1 }
shape := TypeAt(program, value_type)
if shape.kind != LirTypeKind.Integer || !shape.is_signed || shape.bits < 1 || shape.bits > 64 ||
TypeAt(program, upper_type).kind != LirTypeKind.Integer || !TypeAt(program, upper_type).is_signed ||
TypeAt(program, zero_type).kind != LirTypeKind.Integer || !TypeAt(program, zero_type).is_signed ||
bound > (cast(u64)1 << cast(u64)(shape.bits - 1)) - 1 { return -1 }
unsigned_type: s32 = -1
for at: cast(s32)0..program.types.count - 1 {
if Spend(program, expression.span) == 0 { return -1 }
candidate := TypeAt(program, at)
if candidate.kind == LirTypeKind.Integer && !candidate.is_signed && candidate.bits == shape.bits {
unsigned_type = at
break
}
}
if unsigned_type < 0 { return -1 }
first := *function.source.exprs[expression.left]
saved_checking := function.checking
if first.checked != 0 { function.checking = true }
value := Expression(program, function, first.left, depth + 1)
function.checking = saved_checking
if value < 0 { return -1 }
value = Emit(program, function, LirOp.Bitcast, unsigned_type, *value, 1, -1, expression.span)
operands: [2]s32 = .[value, Constant(program, function, unsigned_type, bound, expression.span)]
return Emit(program, function, LirOp.Greater, 1, *operands[0], 2, -1, expression.span)
}
// Both arms of a conditional or short-circuiting expression, joined on one
// block that receives the selected value as a parameter.
Select :: (program: *AssemblyProgram, function: *AssemblyFunction, expression: *IR.ZirExpr,
@@ -5930,10 +5845,6 @@ ExpressionValue :: (program: *AssemblyProgram, function: *AssemblyFunction,
compared, 2, -1, expression.span)
}
}
if IR.CText(*expression.op[0]) == "||" {
folded := BoundsDisjunction(program, function, expression, depth)
if folded >= 0 || program.failed != 0 { return folded }
}
operands := cast(*s32)Allocate(program, 2, size_of(s32))
if operands == null { return -1 }
operands[0] = Expression(program, function, expression.left, depth + 1)
+42 -3
View File
@@ -1953,7 +1953,11 @@ Pillow when it is installed.
decoding it: `VorbisProbe(bytes, *audio)` checks that the bytes are whole
pages of one stream with a Vorbis identification header and gives its
channels, rate and length, so a program can bound a stream before any
decoder allocates for it. It needs no library.
decoder allocates for it. It validates CRCs, page order, headers and the exact
packet timeline. `VorbisInspect` and `VorbisInspectComments` also report bitrate
hints, block sizes, end trim, vendor and user comments. `VorbisRecognizes` only
classifies a header; it does not validate a stream. The bounded packet reader,
CRC and page builder live in `std/ogg`. These modules need no native library.
`std/vorbis_linux.zi` decodes one whole Ogg Vorbis stream held in memory
into interleaved signed 16-bit little-endian PCM over the platform
libvorbisfile: `VorbisDecode(bytes, *pcm, max_frames, *audio)` probes first,
@@ -1964,7 +1968,42 @@ checked on every call. Only programs that import it link
`-l:libvorbisfile.so.3` (or `-lvorbisfile` with the development package).
`tests/vorbis_linux.sh` needs ffmpeg with libvorbis; with the Vorbis
development headers (or `VORBIS_INCLUDE`) it also compares the record sizes
with the C compiler's.
with the C compiler's. `VorbisDecoderOpen`/`VorbisDecoderOpenFile` support
incremental float or PCM16 reads, exact frame seeks and owned comments.
`VorbisDecodeFloat` and `VorbisDecodeS16` provide bounded whole-file output.
Their status codes and float PCM record come from `std/audio_types`.
`std/audio` is the device-independent 48 kHz stereo float mixer. Voices
support gain, pitch, looping, pause/resume, exact seek and position. `AudioSeek(voice, seconds)` preserves
playing/paused state and returns false for live PCM or an unsupported source. `AudioOpenStream(rate,
channels, block_frames)` accepts copied PCM16 blocks through
`AudioStreamSubmit`; `AudioStreamWritable` provides backpressure, and underruns
produce silence. `AudioRender` can render offline without opening a device.
Import `std/audio_decode_wav` or `std/audio_decode_mp3` to register decoders by
content. `std/audio_decode_vorbis` registers the existing guarded libvorbisfile decoder
for incremental playback and exact seek. `std/audio_wav` also exposes bounded WAV encode/decode; `std/audio_mp3`
and `std/audio_mpeg` provide incremental MP3 decoding and portable inspection.
MP3 consumers build `make audio-mp3` and link
`build/audio/native/libziran_mp3.a -lm`. The independent CMake recipe is
`std/native/AudioCodecs.cmake`; it verifies the pinned dr_mp3 header and license.
`std/audio_sink` selects the device interface (`AudioSinkOpen`, `AudioSinkReady`,
`AudioSinkClose`). Native desktop programs use SDL2 without needing a window.
Native open starts a worker and immediately returns false while pending;
poll `AudioSinkReady`, `AudioSinkPending` or `AudioSinkUnavailable`. Repeated
opens back off for one second after failure. Device teardown may join the
worker and callbacks; perform it during explicit teardown, not per cue.
Android targets use dynamically resolved AAudio
on API 26+, with OpenSL ES for API 21–25; minSdk 21 binaries do not link AAudio.
Both native sinks use the same mixer lock and retain loaded voices across
close/reopen. Web targets use WebAudio; call `AudioSinkResume` from a
trusted user gesture when the browser suspends audio. The web sink does not
consume voices while suspended. Applications own device open/close and gesture
policy. `make check CHECK_FILTER=audio_checks` exercises the mixer, deterministic
Android failure paths, and SDL device failure/disk output on private Xvfb.
`make audio-android-test ANDROID_NDK=… ANDROID_SERIAL=…` tests AAudio and
OpenSL PCM callbacks on an explicit armv7 device; `make android-parity
ANDROID_ARCH=armv7 ANDROID_API=21 ANDROID_SERIAL=…` separately verifies ZX.
The reusable `audio` package, maintained in `ziranlang/packages/audio`, adds
Opus and quality sinc conversion without a GUI or audio-device dependency.
@@ -1974,7 +2013,7 @@ with automatic sinc resampling. The Ogg decoder applies
pre-skip, header gain and final trim; `DecoderRewind` resets a validated
immutable input without rescanning it. `audio/resample` wraps libsamplerate's
best-quality sinc, including 44.1–48 kHz conversion and incremental processing.
`audio/ogg` inspection and `audio/wav` PCM16/float32 input with PCM16 output
`std/ogg` container inspection and `std/audio_wav` PCM16/float32 input with PCM16 output
also run in portable bundles. Native codec/sinc calls require the C target;
portable bundles reject those FFI calls explicitly. Native consumers declare
`links = ["opus", "samplerate", "m"]` in their root package manifest.
+1 -1
View File
@@ -13,7 +13,7 @@
<a href="examples.html"><span>Learn by doing</span><strong>Examples</strong><p><!-- generated:example_count -->16<!-- /generated:example_count --> complete programs with commands, each printing the same output on every target.</p><b>Browse examples →</b></a>
<a href="language.html"><span>Language</span><strong>Syntax reference</strong><p>Modules, declarations, types, generics, control flow, compile-time forms, laws, and foreign calls.</p><b>Read the reference →</b></a>
<a href="api.html#toolchain"><span>Toolchain</span><strong>CLI reference</strong><p>Check, build C or Go, bundle, run, format, and query the toolchain.</p><b>See commands →</b></a>
<a href="modules.html"><span>Libraries</span><strong>Modules and packages</strong><p>Every public declaration in the <!-- generated:std_count -->108<!-- /generated:std_count --> standard modules and the ziranlang packages, generated from the source.</p><b>Browse modules →</b></a>
<a href="modules.html"><span>Libraries</span><strong>Modules and packages</strong><p>Every public declaration in the <!-- generated:std_count -->125<!-- /generated:std_count --> standard modules and the ziranlang packages, generated from the source.</p><b>Browse modules →</b></a>
<a href="status.html"><span>Project</span><strong>Implementation status</strong><p>See what works in the tested subset and what still needs implementation.</p><b>Check support →</b></a>
<a href="guide/packages.html"><span>Projects</span><strong>Packages</strong><p><code>ziran.toml</code> projects, pinned Git dependencies, locks, and installing applications.</p><b>Read the guide →</b></a>
</div></section>
+40 -3
View File
@@ -1663,7 +1663,11 @@ Pillow when it is installed.
decoding it: <code>VorbisProbe(bytes, *audio)</code> checks that the bytes are whole
pages of one stream with a Vorbis identification header and gives its
channels, rate and length, so a program can bound a stream before any
decoder allocates for it. It needs no library.
decoder allocates for it. It validates CRCs, page order, headers and the exact
packet timeline. <code>VorbisInspect</code> and <code>VorbisInspectComments</code> also report bitrate
hints, block sizes, end trim, vendor and user comments. <code>VorbisRecognizes</code> only
classifies a header; it does not validate a stream. The bounded packet reader,
CRC and page builder live in <code>std/ogg</code>. These modules need no native library.
<code>std/vorbis_linux.zi</code> decodes one whole Ogg Vorbis stream held in memory
into interleaved signed 16-bit little-endian PCM over the platform
libvorbisfile: <code>VorbisDecode(bytes, *pcm, max_frames, *audio)</code> probes first,
@@ -1674,7 +1678,40 @@ checked on every call. Only programs that import it link
<code>-l:libvorbisfile.so.3</code> (or <code>-lvorbisfile</code> with the development package).
<code>tests/vorbis_linux.sh</code> needs ffmpeg with libvorbis; with the Vorbis
development headers (or <code>VORBIS_INCLUDE</code>) it also compares the record sizes
with the C compiler's.</p>
with the C compiler's. <code>VorbisDecoderOpen</code>/<code>VorbisDecoderOpenFile</code> support
incremental float or PCM16 reads, exact frame seeks and owned comments.
<code>VorbisDecodeFloat</code> and <code>VorbisDecodeS16</code> provide bounded whole-file output.
Their status codes and float PCM record come from <code>std/audio_types</code>.</p>
<p><code>std/audio</code> is the device-independent 48 kHz stereo float mixer. Voices
support gain, pitch, looping, pause/resume, exact seek and position. <code>AudioSeek(voice, seconds)</code> preserves
playing/paused state and returns false for live PCM or an unsupported source. <code>AudioOpenStream(rate,
channels, block_frames)</code> accepts copied PCM16 blocks through
<code>AudioStreamSubmit</code>; <code>AudioStreamWritable</code> provides backpressure, and underruns
produce silence. <code>AudioRender</code> can render offline without opening a device.
Import <code>std/audio_decode_wav</code> or <code>std/audio_decode_mp3</code> to register decoders by
content. <code>std/audio_decode_vorbis</code> registers the existing guarded libvorbisfile decoder
for incremental playback and exact seek. <code>std/audio_wav</code> also exposes bounded WAV encode/decode; <code>std/audio_mp3</code>
and <code>std/audio_mpeg</code> provide incremental MP3 decoding and portable inspection.
MP3 consumers build <code>make audio-mp3</code> and link
<code>build/audio/native/libziran_mp3.a -lm</code>. The independent CMake recipe is
<code>std/native/AudioCodecs.cmake</code>; it verifies the pinned dr_mp3 header and license.</p>
<p><code>std/audio_sink</code> selects the device interface (<code>AudioSinkOpen</code>, <code>AudioSinkReady</code>,
<code>AudioSinkClose</code>). Native desktop programs use SDL2 without needing a window.
Native open starts a worker and immediately returns false while pending;
poll <code>AudioSinkReady</code>, <code>AudioSinkPending</code> or <code>AudioSinkUnavailable</code>. Repeated
opens back off for one second after failure. Device teardown may join the
worker and callbacks; perform it during explicit teardown, not per cue.
Android targets use dynamically resolved AAudio
on API 26+, with OpenSL ES for API 21–25; minSdk 21 binaries do not link AAudio.
Both native sinks use the same mixer lock and retain loaded voices across
close/reopen. Web targets use WebAudio; call <code>AudioSinkResume</code> from a
trusted user gesture when the browser suspends audio. The web sink does not
consume voices while suspended. Applications own device open/close and gesture
policy. <code>make check CHECK_FILTER=audio_checks</code> exercises the mixer, deterministic
Android failure paths, and SDL device failure/disk output on private Xvfb.
<code>make audio-android-test ANDROID_NDK=… ANDROID_SERIAL=…</code> tests AAudio and
OpenSL PCM callbacks on an explicit armv7 device; <code>make android-parity
ANDROID_ARCH=armv7 ANDROID_API=21 ANDROID_SERIAL=…</code> separately verifies ZX.</p>
<p>The reusable <code>audio</code> package, maintained in <code>ziranlang/packages/audio</code>, adds
Opus and quality sinc conversion without a GUI or audio-device dependency.
<code>audio/opus</code> exposes bounded Ogg decoding and single-owner encoder/decoder
@@ -1683,7 +1720,7 @@ with automatic sinc resampling. The Ogg decoder applies
pre-skip, header gain and final trim; <code>DecoderRewind</code> resets a validated
immutable input without rescanning it. <code>audio/resample</code> wraps libsamplerate's
best-quality sinc, including 44.1–48 kHz conversion and incremental processing.
<code>audio/ogg</code> inspection and <code>audio/wav</code> PCM16/float32 input with PCM16 output
<code>std/ogg</code> container inspection and <code>std/audio_wav</code> PCM16/float32 input with PCM16 output
also run in portable bundles. Native codec/sinc calls require the C target;
portable bundles reject those FFI calls explicitly. Native consumers declare
<code>links = ["opus", "samplerate", "m"]</code> in their root package manifest.
+1 -1
View File
@@ -130,7 +130,7 @@ build/bin/ziran version</code></pre><a class="btn btn-primary" href="get-started
<section class="status-callout modules-callout" aria-labelledby="modules-title">
<div><p class="eyebrow">Libraries</p><h2 id="modules-title">Modules and <em>packages.</em></h2></div>
<div><p><!-- generated:module_counts -->108 standard modules and 17 packages<!-- /generated:module_counts -->, each with an API reference generated from its source, from text and JSON to image codecs.</p><a class="btn" href="modules.html">Browse all modules →</a></div>
<div><p><!-- generated:module_counts -->125 standard modules and 17 packages<!-- /generated:module_counts -->, each with an API reference generated from its source, from text and JSON to image codecs.</p><a class="btn" href="modules.html">Browse all modules →</a></div>
</section>
<section class="status-callout">
<div><p class="eyebrow"><span class="status-dot" aria-hidden="true"></span>Project status</p><h2>Working core.<br><em>Experimental edges.</em></h2></div>
+22 -5
View File
@@ -1,11 +1,27 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Every Ziran standard module and package: 108 std modules and 17 packages with API references generated from the source."><title>Ziran modules and packages</title><link rel="canonical" href="https://ziran-lang.org/modules"><link rel="icon" href="assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="styles.css"><script defer src="site.js"></script></head>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Every Ziran standard module and package: 125 std modules and 17 packages with API references generated from the source."><title>Ziran modules and packages</title><link rel="canonical" href="https://ziran-lang.org/modules"><link rel="icon" href="assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="styles.css"><script defer src="site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="index.html"><img class="brand-icon" src="assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="get-started.html">Get started</a><a href="examples.html">Examples</a><a href="targets.html">Targets</a><a href="modules.html" aria-current="page">Modules</a><a href="docs.html">Docs</a><a href="status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow">Reference / Modules</p><h1>Modules and <em>packages.</em></h1><p>108 standard modules and 17 packages, listed from the source on every site build. Each page shows the public declarations <code>ziran api</code> reports, with the comment written above them.</p><p class="module-meta"><span class="status-badge is-stable">Stable</span> ships in the latest release, <a href="https://github.com/ziranlang/ziran/releases/tag/v0.6.0">v0.6.0</a> (for a package: it has a tagged release). <span class="status-badge is-in-progress">In progress</span> exists only on <code>master</code> or has no release yet.</p></div>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow">Reference / Modules</p><h1>Modules and <em>packages.</em></h1><p>125 standard modules and 17 packages, listed from the source on every site build. Each page shows the public declarations <code>ziran api</code> reports, with the comment written above them.</p><p class="module-meta"><span class="status-badge is-stable">Stable</span> ships in the latest release, <a href="https://github.com/ziranlang/ziran/releases/tag/v0.6.0">v0.6.0</a> (for a package: it has a tagged release). <span class="status-badge is-in-progress">In progress</span> exists only on <code>master</code> or has no release yet.</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Sections</strong><a href="#std">Standard library</a><a href="#packages">Packages</a></aside><div class="article-body">
<section id="std"><h2>Standard library</h2><p>Import a module with <code>#import "std/NAME"</code>. Modules ending in <code>_linux</code>, <code>_windows</code> or <code>_go</code> build only for that target. A module that needs a host capability runs in a portable bundle only when the program hosting the bundle binds it. 108 of 108 modules shipped in the latest release.</p><div class="table-scroll"><table class="module-table"><thead><tr><th scope="col">Module</th><th scope="col">Summary</th><th scope="col">Needs</th><th scope="col">Status</th></tr></thead><tbody>
<section id="std"><h2>Standard library</h2><p>Import a module with <code>#import "std/NAME"</code>. Modules ending in <code>_linux</code>, <code>_windows</code> or <code>_go</code> build only for that target. A module that needs a host capability runs in a portable bundle only when the program hosting the bundle binds it. 108 of 125 modules shipped in the latest release.</p><div class="table-scroll"><table class="module-table"><thead><tr><th scope="col">Module</th><th scope="col">Summary</th><th scope="col">Needs</th><th scope="col">Status</th></tr></thead><tbody>
<tr><th scope="row"><a href="std/atomic_go.html">atomic_go</a></th><td>Go unsigned 64-bit atomic counters.</td><td>Go target</td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/audio.html">audio</a></th><td>Audio mixer: voices of decoded or streamed sound, each with its own gain, pitch and loop, mixed into interleaved float32 stereo at 48 kHz, with a tap that sees every mixed block.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_android_aaudio.html">audio_android_aaudio</a></th><td>AAudio is loaded at runtime so an API-21 app still loads on API 21-25.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_android_buffer.html">audio_android_buffer</a></th><td>Shared Android mixer boundary.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_android_opensl.html">audio_android_opensl</a></th><td>API-21 PCM output.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_decode_mp3.html">audio_decode_mp3</a></th><td>MPEG audio for std/audio: MP3 (MPEG-1, 2 and 2.5 Layer III) and Layers I and II, decoded as it plays by std/audio_mp3 over dr_mp3 at the stream's own rate.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_decode_vorbis.html">audio_decode_vorbis</a></th><td>Register the existing guarded libvorbisfile decoder with std/audio.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_decode_wav.html">audio_decode_wav</a></th><td>RIFF WAVE for std/audio, PCM16 or float32, decoded whole by std/audio_wav.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_device.html">audio_device</a></th><td>Caller-owned asynchronous device open.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_mp3.html">audio_mp3</a></th><td>MP3 decoding: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III, mono and stereo, through dr_mp3 (the pinned `dr_libs` source dependency, compiled by native/ziran_mp3.c into libziran_mp3.a).</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_mpeg.html">audio_mpeg</a></th><td>Portable MPEG audio stream inspection for MP3 files: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_sink.html">audio_sink</a></th><td>Import the output device for the compilation target.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_sink_android.html">audio_sink_android</a></th><td>Android's output device for the shared audio mixer.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_sink_sdl.html">audio_sink_sdl</a></th><td>Desktop audio output for std/audio: SDL2 opens the default output for 48 kHz float32 stereo, converting to what the device takes, and its audio thread pulls each block from the mixer.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_sink_web.html">audio_sink_web</a></th><td>WebAudio output for std/audio.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_types.html">audio_types</a></th><td><span class=muted>No module description yet.</span></td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/audio_wav.html">audio_wav</a></th><td><span class=muted>No module description yet.</span></td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/binary.html">binary</a></th><td>Little-endian numbers in byte text, such as file or asset contents, read the same way on every native target and in the engine.</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/binary_linux.html">binary_linux</a></th><td>Little-endian binary fields for native Linux programs.</td><td>Native Linux</td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/bundle_host.html">bundle_host</a></th><td>Native C ABI for embedding a portable Ziran bundle.</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
@@ -59,6 +75,7 @@
<tr><th scope="row"><a href="std/net_http_linux.html">net_http_linux</a></th><td><span class=muted>No module description yet.</span></td><td>Native Linux</td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/net_ws_curl_linux.html">net_ws_curl_linux</a></th><td>Blocking, bounded WebSocket text receive for native libcurl hosts.</td><td>Native Linux</td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/number_text.html">number_text</a></th><td><span class=muted>No module description yet.</span></td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/ogg.html">ogg</a></th><td>Portable Ogg container validation and bounded packet/page construction.</td><td><span class=muted>—</span></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="std/option.html">option</a></th><td><span class=muted>No module description yet.</span></td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/pair.html">pair</a></th><td><span class=muted>No module description yet.</span></td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/parallel.html">parallel</a></th><td><span class=muted>No module description yet.</span></td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
@@ -105,7 +122,7 @@
<tr><th scope="row"><a href="std/url_go.html">url_go</a></th><td>Native Go URLs preserve escaped-path selection and their original encoding.</td><td>Go target</td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/utf8.html">utf8</a></th><td>Advance one Unicode scalar in an immutable UTF-8 string.</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/vec.html">vec</a></th><td>VecResizeBounded(values, count:s64, maximum_capacity:s64) -&gt; bool has VecResize's initialized-length semantics and caps the backing element capacity.</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/vorbis.html">vorbis</a></th><td>What an Ogg Vorbis stream held in memory declares, read from its pages alone: nothing is decoded or allocated, so a program can bound a stream before handing it to a decoder (std/vorbis_linux on Linux, or another platform's).</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/vorbis.html">vorbis</a></th><td>Portable Ogg Vorbis inspection (Vorbis I).</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/vorbis_linux.html">vorbis_linux</a></th><td>Whole Ogg Vorbis streams held in memory, decoded over the platform libvorbisfile into signed 16-bit little-endian PCM.</td><td>Native Linux</td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/web.html">web</a></th><td>Browser access for Ziran code compiled to WebAssembly.</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
<tr><th scope="row"><a href="std/zip.html">zip</a></th><td>Classic ZIP directory reader for byte buffers.</td><td><span class=muted>—</span></td><td><span class="status-badge is-stable">Stable</span></td></tr>
@@ -115,7 +132,7 @@
<tr><th scope="row"><a href="std/zstd_go.html">zstd_go</a></th><td>Native Go Zstandard streams.</td><td>Go target</td><td><span class="status-badge is-stable">Stable</span></td></tr>
</tbody></table></div></section>
<section id="packages"><h2>Packages</h2><p>Packages live in their own repositories under <a href="https://github.com/ziranlang">github.com/ziranlang</a> and are added as <code>ziran.toml</code> dependencies; see the <a href="guide/packages.html">package guide</a>.</p><div class="table-scroll"><table class="module-table"><thead><tr><th scope="col">Package</th><th scope="col">Summary</th><th scope="col">Modules</th><th scope="col">Status</th></tr></thead><tbody>
<tr><th scope="row"><a href="packages/audio.html">audio</a></th><td>Reusable Opus encoding/decoding, Ogg Opus inspection, best-quality sinc sample-rate conversion and WAV I/O, with a native audio command.</td><td><a href="packages/audio.html#module-types">types</a>, <a href="packages/audio.html#module-ogg">ogg</a>, <a href="packages/audio.html#module-wav">wav</a>, <a href="packages/audio.html#module-opus">opus</a>, <a href="packages/audio.html#module-pipeline">pipeline</a>, <a href="packages/audio.html#module-resample">resample</a></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="packages/audio.html">audio</a></th><td>Reusable Opus encoding/decoding, MP3 and Ogg Vorbis decoding, Ogg Opus, Ogg Vorbis and MPEG audio inspection, best-quality sinc sample-rate conversion and WAV I/O, with a native audio command.</td><td><a href="packages/audio.html#module-types">types</a>, <a href="packages/audio.html#module-ogg">ogg</a>, <a href="packages/audio.html#module-wav">wav</a>, <a href="packages/audio.html#module-opus">opus</a>, <a href="packages/audio.html#module-pipeline">pipeline</a>, <a href="packages/audio.html#module-resample">resample</a>, <a href="packages/audio.html#module-mpeg_audio">mpeg_audio</a>, <a href="packages/audio.html#module-mp3">mp3</a>, <a href="packages/audio.html#module-mp3_resample">mp3_resample</a>, <a href="packages/audio.html#module-ogg_vorbis">ogg_vorbis</a>, <a href="packages/audio.html#module-vorbis">vorbis</a>, <a href="packages/audio.html#module-vorbis_resample">vorbis_resample</a></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="packages/av1.html">av1</a></th><td>Owned AV1 decoder in handwritten Ziran.</td><td><a href="packages/av1.html#module-decoder">decoder</a></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="packages/avif.html">avif</a></th><td>Optional, headless Ziran image package.</td><td><a href="packages/avif.html#module-api">api</a>, <a href="packages/avif.html#module-engine">engine</a>, <a href="packages/avif.html#module-bmff">bmff</a>, <a href="packages/avif.html#module-bridge">bridge</a>, <a href="packages/avif.html#module-encode">encode</a>, <a href="packages/avif.html#module-preview">preview</a></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
<tr><th scope="row"><a href="packages/clip-tokenizer.html">clip-tokenizer</a></th><td>Portable Ziran byte-level BPE for CLIP's 77-token text input.</td><td><a href="packages/clip-tokenizer.html#module-Tokenizer">Tokenizer</a></td><td><span class="status-badge is-in-progress">In progress</span></td></tr>
+299 -33
View File
@@ -1,16 +1,19 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Reusable Opus encoding/decoding, Ogg Opus inspection, best-quality sinc sample-rate conversion and WAV I/O, with a native audio command."><title>Audio for Ziran · Ziran package</title><link rel="canonical" href="https://ziran-lang.org/packages/audio"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Reusable Opus encoding/decoding, MP3 and Ogg Vorbis decoding, Ogg Opus, Ogg Vorbis and MPEG audio inspection, best-quality sinc sample-rate conversion and WAV I/O, with a native audio command."><title>Audio for Ziran · Ziran package</title><link rel="canonical" href="https://ziran-lang.org/packages/audio"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#packages">Modules</a> / Packages</p><h1>Audio for Ziran</h1><p>Reusable Opus encoding/decoding, Ogg Opus inspection, best-quality sinc sample-rate conversion and WAV I/O, with a native audio command. The modules have no audio-device or runtime subprocess dependency. GUI hosts choose their own playback sink and call the same modules as command-line tools.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> No tagged release yet.</p><p><a class="text-link" href="https://github.com/ziranlang/audio">Repository ↗</a></p></div>
<div class="article-grid"><aside class="page-toc"><strong>Contents</strong><a href="#install">Install</a><a href="#overview">Overview</a><a href="#module-types">types</a><a href="#module-ogg">ogg</a><a href="#module-wav">wav</a><a href="#module-opus">opus</a><a href="#module-pipeline">pipeline</a><a href="#module-resample">resample</a></aside><div class="article-body api-body">
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#packages">Modules</a> / Packages</p><h1>Audio for Ziran</h1><p>Reusable Opus encoding/decoding, MP3 and Ogg Vorbis decoding, Ogg Opus, Ogg Vorbis and MPEG audio inspection, best-quality sinc sample-rate conversion and WAV I/O, with a native audio command.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> No tagged release yet.</p><p><a class="text-link" href="https://github.com/ziranlang/audio">Repository ↗</a></p></div>
<div class="article-grid"><aside class="page-toc"><strong>Contents</strong><a href="#install">Install</a><a href="#overview">Overview</a><a href="#module-types">types</a><a href="#module-ogg">ogg</a><a href="#module-wav">wav</a><a href="#module-opus">opus</a><a href="#module-pipeline">pipeline</a><a href="#module-resample">resample</a><a href="#module-mpeg_audio">mpeg_audio</a><a href="#module-mp3">mp3</a><a href="#module-mp3_resample">mp3_resample</a><a href="#module-ogg_vorbis">ogg_vorbis</a><a href="#module-vorbis">vorbis</a><a href="#module-vorbis_resample">vorbis_resample</a></aside><div class="article-body api-body">
<section id="install"><h2>Add the dependency</h2><p>In your project’s <code>ziran.toml</code>; pin <code>ref</code> to a commit for reproducible builds.</p><pre><code>[dependencies.audio]
git = "https://github.com/ziranlang/audio.git"
ref = "master"</code></pre></section>
<section id="overview" class="prose"><h2>Overview</h2><h2 id="build-and-use">Build and use</h2>
<p>Install Ziran plus the development/link libraries for <strong>libopus</strong> and
<p>Install Ziran, CMake plus the development/link libraries for <strong>libopus</strong> and
<strong>libsamplerate</strong> (<code>libopus-dev</code> and <code>libsamplerate0-dev</code> on Debian-family
Linux), then run:</p>
Linux). The MP3 and Vorbis decoders are compiled from the pinned <code>dr_libs</code>
and <code>stb</code> sources: <code>make</code> builds <code>build/native/linux/libziran_mp3.a</code> and
<code>build/native/linux/libziran_vorbis.a</code> through <code>native/CMakeLists.txt</code> before
the CLI. Then run:</p>
<pre><code class="language-sh">make
build/bin/audio --help
build/bin/audio encode input.wav output.opus --bitrate 64000 --vbr on
@@ -19,15 +22,40 @@ build/bin/audio inspect output.opus
build/bin/audio decode output.opus decoded.wav
build/bin/audio transcode input.opus smaller.opus --bitrate 32000
build/bin/audio resample input.wav speech.wav --rate 16000
build/bin/audio inspect song.mp3
build/bin/audio decode song.mp3 song.wav
build/bin/audio resample song.mp3 song-48k.wav --rate 48000
build/bin/audio inspect music.ogg
build/bin/audio decode music.ogg music.wav
build/bin/audio resample music.ogg music-48k.wav --rate 48000
</code></pre>
<p>Formats are chosen from the content, not the file name: <code>OggS</code> whose first
packet is a Vorbis identification header is Ogg Vorbis, any other <code>OggS</code> is
Ogg Opus, <code>RIFF</code> is WAV, anything else is read as MPEG audio. <code>inspect</code> on an
MP3 prints the MPEG version and layer, channels, rate, exact frames and
duration, bitrate, VBR or CBR, the LAME delay/padding and the frame count:</p>
<pre><code class="language-text">MP3: MPEG-1 Layer III, 2 channels, 44100 Hz, 13230 frames, 0.300 s, 128000 bps CBR, delay 1105, padding 641, 13 MPEG frames
</code></pre>
<p>On Ogg Vorbis it prints the channels, rate, exact frames and duration, the
nominal bitrate hint, the block sizes, mode count, end trim and packet and
comment counts, then the vendor string and each comment (control bytes shown
as <code>?</code>):</p>
<pre><code class="language-text">Vorbis: 1 channels, 32000 Hz, 9600 frames, 0.300 s, 52000 bps nominal, blocks 256/2048, 2 modes, end trim 0, 13 packets, 4 comments
Vorbis vendor: ffmpeg
Vorbis comment: encoder=Lavc libvorbis
Vorbis comment: title=Ziran fixture
Vorbis comment: artist=Ziran audio
Vorbis comment: DESCRIPTION=Vorbis comments, ünïcödé
</code></pre>
<p>The CLI supports PCM16 and IEEE float32 RIFF WAV input, and mapping-family-0
Ogg Opus (mono/stereo) with the exact 19-byte version-1 identification header.
Other Opus header versions/extensions are outside this bounded profile.
Decoded WAV output is PCM16 at 48 kHz. <code>resample</code>
Decoded Opus WAV output is PCM16 at 48 kHz; decoded MP3 and Vorbis WAV
output is PCM16 at the stream's own rate. <code>resample</code>
accepts either format and writes PCM16 WAV at the requested 8000–192000 Hz
rate. <code>transcode</code> decodes WAV/Opus and encodes Opus; it is a lossy re-encode
when its source is already Opus. Other audio formats belong to separate
modules; existing <code>std/vorbis</code> and <code>std/vorbis_linux</code> support is independent.</p>
rate. <code>transcode</code> decodes WAV, Opus, Vorbis or MP3 and encodes Opus; it is a
lossy re-encode unless its source is WAV. Ziran's whole-file <code>std/vorbis</code> and
<code>std/vorbis_linux</code> are independent of <code>audio/vorbis</code>.</p>
<p>Encoder options are <code>--bitrate</code> in bits/second (6000–510000), <code>--vbr</code>
<code>on|off|constrained</code>, <code>--bandwidth</code> <code>auto|narrow|wide|superwide|full</code>,
<code>--application</code> <code>audio|voice|lowdelay</code>, <code>--complexity</code> 0–10 and <code>--frame-ms</code>
@@ -58,11 +86,19 @@ Literal and resolved source/destination aliases are rejected. The CLI does
not play audio or open audio devices.</p>
<h2 id="callable-modules">Callable modules</h2>
<p>Exports are <code>audio/types</code>, <code>audio/ogg</code>, <code>audio/wav</code>, <code>audio/opus</code>,
<code>audio/resample</code> and <code>audio/pipeline</code>.
<code>audio/resample</code>, <code>audio/pipeline</code>, <code>audio/mpeg_audio</code>, <code>audio/mp3</code>,
<code>audio/mp3_resample</code>, <code>audio/ogg_vorbis</code>, <code>audio/vorbis</code> and
<code>audio/vorbis_resample</code>.
Full-pipeline native consumers declare <code>links = ["opus", "samplerate", "m"]</code> in their
root manifest's <code>[package]</code> table, or use equivalent linker flags in a custom
host. Ziran does not inherit system links from dependencies. Codec-only consumers need
only <code>links = ["opus", "m"]</code>; <code>audio/opus</code> does not import the resampler.</p>
only <code>links = ["opus", "m"]</code>; <code>audio/opus</code> does not import the resampler.
MP3 decode-only consumers link <code>libziran_mp3.a</code> and <code>-lm</code>
(<code>links = ["ziran_mp3", "m"]</code> with the archive's directory in <code>LDFLAGS</code>);
<code>audio/mp3_resample</code> adds <code>samplerate</code>. <code>audio/mpeg_audio</code> is portable.
Vorbis decode-only consumers likewise link <code>libziran_vorbis.a</code> and <code>-lm</code>
(<code>links = ["ziran_vorbis", "m"]</code>); <code>audio/vorbis_resample</code> adds
<code>samplerate</code>, and <code>audio/ogg_vorbis</code> is portable.</p>
<pre><code class="language-zi">Types :: #import &quot;audio/types&quot;
Pipeline :: #import &quot;audio/pipeline&quot;
#import &quot;std/vec&quot;
@@ -96,6 +132,123 @@ sample rate is informational and does not change the Ogg 48-kHz timebase.</p>
and incremental decode instead permit up to 24 hours at 48 kHz, without
allocating full PCM. Ogg packets/comments are bounded to 65536 bytes. These
limits are explicit capability boundaries, including on otherwise valid input.</p>
<h2 id="mp3">MP3</h2>
<p><code>audio/mp3</code> decodes MPEG-1, MPEG-2 and MPEG-2.5 audio, Layers I, II and III,
mono and stereo, through <a href="https://github.com/mackron/dr_libs">dr_mp3</a> (public
domain or MIT-0; its <code>LICENSE</code> is in the pinned source). The manifest pins
<code>dr_libs</code> at commit <code>f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c</code> (dr_mp3 0.7.5)
as a <code>source = true</code> dependency. <code>native/ziran_mp3.c</code> is dr_mp3's one
implementation unit, built with float output and no stdio, plus two calls
that size and free the native decoder state. Redistributors ship dr_libs'
<code>LICENSE</code> alongside the binary as they do libopus' <code>COPYING</code>.</p>
<ul>
<li><code>Mp3Inspect([]u8, *Mp3Info) -&gt; s32</code> (<code>audio/mpeg_audio</code>, portable)</li>
<li><code>Mp3DecoderOpen(*Mp3Decoder, input:[]u8, max_frames:s64) -&gt; s32</code>, or
<code>Mp3DecoderOpenFile(*Mp3Decoder, path, max_frames)</code>, which reads the file
(at most 256 MiB) into the decoder</li>
<li><code>Mp3DecoderRead(*Mp3Decoder, []float32, frames:*s64)</code> and
<code>Mp3DecoderReadS16(*Mp3Decoder, []s16, frames:*s64)</code>: interleaved chunks
of whole frames</li>
<li><code>Mp3DecoderSeek(*Mp3Decoder, frame:s64)</code>, <code>Mp3DecoderRewind</code>, and the
idempotent <code>Mp3DecoderClose</code></li>
<li><code>Mp3Decode([]u8, max_frames, *PCM)</code> and
<code>Mp3DecodeS16([]u8, max_frames, *Vec(s16), *Mp3Info)</code>: whole file</li>
<li><code>Mp3DecodeResampled([]u8, max_frames, rate, *PCM)</code> (<code>audio/mp3_resample</code>):
whole file through <code>audio/resample</code>'s best sinc</li>
</ul>
<p><code>Mp3Info</code> gives the MPEG version (1, 2 or 25) and layer, channels, rate,
exact PCM <code>frames</code>, <code>mp3_frames</code>, <code>frame_samples</code>, LAME <code>delay</code>/<code>padding</code>,
<code>bitrate</code> (nominal for CBR, average for VBR), <code>vbr</code>, and the frame byte range;
<code>Mp3Seconds</code> converts frames to seconds. With a Xing/Info header the frame
count is its declared frames times the frame length less the LAME encoder
delay (+529) and padding (−529), so duration is exact without decoding, as
FFmpeg trims it; without one it is the walked frames times the frame length.
VBR is a Xing or VBRI header or a bitrate change between frames.</p>
<p>Inspection walks every frame header before dr_mp3 sees the bytes. It skips
leading ID3v2 tags (several, with footers) and trailing ID3v1 and APEv2 tags,
then requires complete frames that keep the first frame's version, layer,
rate and channel count, optionally followed by zero padding. A partial last
frame, fewer frames than a Xing header declares, junk between frames, a
mono/stereo or rate change (<code>Unsupported</code>), free-format frames
(<code>Unsupported</code>) and non-MPEG input are rejected; dr_mp3 is then opened over
just the validated frame bytes. A decoder that ends before the declared frame
count fails the read with <code>Malformed</code>. Lyrics3 tags and mid-stream tags are
outside this bounded profile.</p>
<p>Reads behave like <code>DecoderRead</code>: caller-owned interleaved scratch of whole
frames, <code>OK</code> with zero frames at the logical end, and a failed read may have
filled a prefix. S16 samples are the float output through <code>Pcm16</code> (clip to
[-1, 32767/32768], scale by 32768, truncate), the same PCM16 boundary
<code>WavEncode</code> uses, so they equal the CLI's decoded WAV. Seeks
land on the exact requested frame: the decoder binds a seek table of about
one point per second (at most 16384) at open, starts up to 16 frames before
the target and decodes forward, so the samples after a seek are bit-identical
to a linear decode. Input bytes are borrowed until close, as for Opus. Live
decoders have one owner and must not be copied or shared across threads.
For streaming at another rate, pass <code>Mp3DecoderRead</code> chunks to
<code>SincOpen</code>/<code>SincProcess</code>.</p>
<h2 id="ogg-vorbis">Ogg Vorbis</h2>
<p><code>audio/vorbis</code> decodes Ogg Vorbis (Vorbis I, floor 1, mono and stereo,
8–192 kHz) through <a href="https://github.com/nothings/stb">stb_vorbis</a> (public
domain or MIT; its <code>LICENSE</code> is in the pinned source). The manifest pins
<code>stb</code> at commit <code>9600522de53973336fa033a289858a4354cbb04c</code> (stb_vorbis 1.24)
as a <code>source = true</code> dependency. <code>native/ziran_vorbis.c</code> is stb_vorbis' one
implementation unit, built without stdio, the pushdata API, integer
conversion or comment parsing, plus open, read and seek calls.
Redistributors ship stb's <code>LICENSE</code> alongside the binary.</p>
<ul>
<li><code>VorbisProbe([]u8) -&gt; bool</code> and <code>VorbisInspect([]u8, *VorbisInfo) -&gt; s32</code>
(<code>audio/ogg_vorbis</code>, portable); <code>VorbisInspectComments([]u8, *VorbisInfo,
*VorbisComments)</code> also copies the comment header</li>
<li><code>VorbisDecoderOpen(*VorbisDecoder, input:[]u8, max_frames:s64) -&gt; s32</code>, or
<code>VorbisDecoderOpenFile(*VorbisDecoder, path, max_frames)</code>, which reads the
file (at most 256 MiB) into the decoder</li>
<li><code>VorbisDecoderRead(*VorbisDecoder, []float32, frames:*s64)</code> and
<code>VorbisDecoderReadS16(*VorbisDecoder, []s16, frames:*s64)</code>: interleaved
chunks of whole frames</li>
<li><code>VorbisDecoderSeek(*VorbisDecoder, frame:s64)</code>, <code>VorbisDecoderRewind</code>, and
the idempotent <code>VorbisDecoderClose</code></li>
<li><code>VorbisDecode([]u8, max_frames, *PCM)</code> and
<code>VorbisDecodeS16([]u8, max_frames, *Vec(s16), *VorbisInfo)</code>: whole file</li>
<li><code>VorbisDecodeResampled([]u8, max_frames, rate, *PCM)</code>
(<code>audio/vorbis_resample</code>): whole file through <code>audio/resample</code>'s best sinc</li>
<li><code>VorbisVendor</code>, <code>VorbisCommentCount</code>, <code>VorbisComment(*VorbisComments,
index)</code> and <code>VorbisCommentValue(*VorbisComments, field)</code>, which matches the
field name without regard to ASCII case; an open decoder holds its
stream's comments in <code>decoder.comments</code></li>
</ul>
<p><code>VorbisInfo</code> gives channels, rate, exact PCM <code>frames</code>, the header's nominal,
maximum and minimum bitrate hints (0 when unset), the short and long block
sizes, the mode count, audio <code>packets</code>, the comment count and <code>end_trim</code>;
<code>VorbisSeconds</code> converts frames to seconds. <code>frames</code> is the final granule
position, which trims the last packet, so the duration is exact without
decoding; libvorbisfile's <code>ov_pcm_total</code> agrees on every fixture.</p>
<p>Inspection reads the whole stream before stb_vorbis sees it, because
stb_vorbis checks neither page CRCs nor serial numbers. <code>audio/ogg</code>'s reader
checks every page (capture, CRC, one serial, sequence, BOS/EOS, lacing).
The identification header must be a 30-byte version-0 header on its own BOS
page; the comment header's vendor, comments and framing bit must fit its
packet; the setup header must end its page. The mode table is read
backwards from the setup header's framing bit, as FFmpeg's and liboggz's
parsers do, so every audio packet's block size, and with it each page's
granule position, is checked: the timeline must start at zero, and the
final granule may only trim frames that were decoded. Truncation (even one
byte), CRC errors, trailing bytes, non-audio packets and granule mismatches
are <code>Malformed</code>; chained or multiplexed streams (a second beginning-of-stream
page), a timeline not starting at zero, more than two channels and rates
outside 8000–192000 Hz are <code>Unsupported</code>. Floor 0 streams (pre-2004
encoders) fail to open in stb_vorbis and return <code>Malformed</code>. A decoder that
ends before the final granule position fails the read with <code>Malformed</code>.</p>
<p>Reads behave like <code>DecoderRead</code>: caller-owned interleaved scratch of whole
frames, <code>OK</code> with zero frames at the logical end, and a failed read may have
filled a prefix. <code>ziran_vorbis_read</code> keeps decoding past frames that return
no samples, which stb_vorbis' own interleaved reader treats as the end. S16
samples are the float output through <code>Pcm16</code>, as for MP3. Seeks land on the
exact requested frame: stb_vorbis bisects the pages for the one holding it,
then decodes forward from the packet before, so the samples after a seek
are bit-identical to a linear decode. Input bytes are borrowed until close.
Live decoders have one owner and must not be copied or shared across
threads. For streaming at another rate, pass <code>VorbisDecoderRead</code> chunks to
<code>SincOpen</code>/<code>SincProcess</code>.</p>
<h2 id="incremental-apis-and-ownership">Incremental APIs and ownership</h2>
<p><code>DecoderOpen(*Decoder, input:[]u8, max_frames:s64) -&gt; s32</code> validates the
single logical stream, then <code>DecoderRead(*Decoder, output:[]float32,
@@ -126,47 +279,70 @@ separate streams. The CLI conveniences are bounded whole-file operations;
only the explicit state APIs stream PCM.</p>
<h2 id="android">Android</h2>
<p>The manifest pins the codec sources as <code>source = true</code> dependencies:
<code>libopus</code> (xiph/opus v1.5.2) and <code>libsamplerate</code> (libsndfile/libsamplerate
0.2.2). An NDK CMake build includes <code>native/AudioCodecs.cmake</code> and calls
<code>ziran_audio_codecs("&lt;libopus&gt;" "&lt;libsamplerate&gt;")</code> with the paths from
<code>ziran pkg path libopus</code> / <code>ziran pkg path libsamplerate</code>. It defines static,
position-independent <code>opus</code> and <code>samplerate</code> targets (float API; no programs,
tests or DNN extensions) to link into the app's native library. Generate the
app's C with Breeze's Android defines, <code>--define ANDROID_BUILD</code> plus the ABI's
<code>__aarch64__</code>, <code>__arm__</code>, <code>__i386__</code> or <code>__x86_64__</code>; <code>std</code> file mapping and
renames need them on bionic.</p>
<code>libopus</code> (xiph/opus v1.5.2), <code>libsamplerate</code> (libsndfile/libsamplerate
0.2.2), <code>dr_libs</code> (mackron/dr_libs, dr_mp3 0.7.5) and <code>stb</code> (nothings/stb,
stb_vorbis 1.24). An NDK CMake build includes <code>native/AudioCodecs.cmake</code> and
calls <code>ziran_audio_codecs("&lt;libopus&gt;" "&lt;libsamplerate&gt;")</code>,
<code>ziran_audio_mp3("&lt;dr_libs&gt;")</code> and <code>ziran_audio_vorbis("&lt;stb&gt;")</code> with the
paths from <code>ziran pkg path NAME</code>. They define static, position-independent
<code>opus</code>, <code>samplerate</code>, <code>ziran_mp3</code> and <code>ziran_vorbis</code> targets (float API; no
programs, tests or DNN extensions) to link into the app's native library.
<code>native/CMakeLists.txt</code> builds whichever of <code>OPUS_DIR</code>+<code>SAMPLERATE_DIR</code>,
<code>DR_LIBS_DIR</code> and <code>STB_DIR</code> it is given. Generate the
app's C with <code>--target-os android</code> and <code>--target-cpu</code> (<code>arm64</code>, <code>x64</code>, or
<code>none</code> for 32-bit ABIs) plus Breeze's Android defines, <code>--define
ANDROID_BUILD</code> and the ABI's <code>__aarch64__</code>, <code>__arm__</code>, <code>__i386__</code> or
<code>__x86_64__</code>. <code>std</code> file mapping and renames select bionic's calls from the
target OS; without it a 32-bit build calls <code>mmap</code> with a 64-bit offset and
every input fails to map.</p>
<p><code>make android-test</code> (after <code>make test</code>) builds both libraries and the CLI with
NDK 28.2.13676358 at API 21 for arm64-v8a, armeabi-v7a, x86 and x86_64
(<code>ANDROID_NDK_HOME</code>, <code>ANDROID_API</code> and <code>ANDROID_ABIS</code> override this). With
<code>ANDROID_SERIAL=SERIAL</code> it runs inspect, decode, resample and encode on that
device and compares the output with the Linux CLI. On a Moto e6 play
(armeabi-v7a, Android 9), decoded and resampled PCM16 matched Linux exactly
and the device-encoded stream decoded on Linux at the source duration. The
other three ABIs are build-tested only.</p>
device and compares the output with the Linux CLI, including the nine MP3
and six Vorbis fixtures (inspect and decode) and an MP3 and a Vorbis stream
resampled to 48 kHz. On a Moto e6 play (armeabi-v7a, Android 9), decoded and
resampled PCM16 matched Linux exactly, MP3 and Vorbis included, and the
device-encoded stream decoded on Linux at the source duration. The other three ABIs are build-tested only. Native
consumers link <code>libziran_mp3.a</code> from <code>ziran_audio_mp3</code> and
<code>libziran_vorbis.a</code> from <code>ziran_audio_vorbis</code> with <code>-lm</code>.</p>
<h2 id="windows">Windows</h2>
<p>The same recipe builds static <code>libopus.a</code> and <code>libsamplerate.a</code> for
x86_64 MinGW. With the pinned sources from <code>ziran pkg path</code>:</p>
<p>The same recipe builds static <code>libopus.a</code>, <code>libsamplerate.a</code>,
<code>libziran_mp3.a</code> and <code>libziran_vorbis.a</code> for x86_64 MinGW. With the pinned
sources from <code>ziran pkg path</code>:</p>
<pre><code class="language-sh">cmake -S native -B build/windows/native -DCMAKE_SYSTEM_NAME=Windows \
-DCMAKE_SYSTEM_PROCESSOR=AMD64 -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc \
-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY -DCMAKE_BUILD_TYPE=Release \
-DOPUS_DIR=&quot;$(ziran pkg path libopus)&quot; -DSAMPLERATE_DIR=&quot;$(ziran pkg path libsamplerate)&quot;
-DOPUS_DIR=&quot;$(ziran pkg path libopus)&quot; -DSAMPLERATE_DIR=&quot;$(ziran pkg path libsamplerate)&quot; \
-DDR_LIBS_DIR=&quot;$(ziran pkg path dr_libs)&quot; -DSTB_DIR=&quot;$(ziran pkg path stb)&quot;
cmake --build build/windows/native
</code></pre>
<p>The archives are <code>build/windows/native/libopus/libopus.a</code> and
<code>build/windows/native/libsamplerate/src/libsamplerate.a</code> (a CMake consumer
calls <code>ziran_audio_codecs</code> and links the <code>opus</code> target). Generate C with
<p>The archives are <code>build/windows/native/libopus/libopus.a</code>,
<code>build/windows/native/libsamplerate/src/libsamplerate.a</code>,
<code>build/windows/native/libziran_mp3.a</code> and
<code>build/windows/native/libziran_vorbis.a</code> (a CMake consumer calls
<code>ziran_audio_codecs</code>/<code>ziran_audio_mp3</code>/<code>ziran_audio_vorbis</code> and links the
<code>opus</code>/<code>ziran_mp3</code>/<code>ziran_vorbis</code> targets). Generate C with
<code>--define _WIN32 --define __x86_64__</code>; no other define is needed. libopus
keeps its default stack protector and <code>_FORTIFY_SOURCE=2</code>, so a MinGW link
adds GCC's <code>-lssp</code> after the archives: decoder-only consumers link
<code>libopus.a -lssp -lm</code>, full-pipeline consumers <code>libopus.a libsamplerate.a
-lssp -lm</code>. With <code>-static -static-libgcc</code> the programs import only
<code>libopus.a -lssp -lm</code> (plus <code>libziran_mp3.a</code> and <code>libziran_vorbis.a</code>
before it for MP3 and Vorbis),
full-pipeline consumers <code>libopus.a libsamplerate.a -lssp -lm</code>. With <code>-static -static-libgcc</code> the programs import only
<code>kernel32</code>, <code>msvcrt</code> and <code>advapi32</code>.</p>
<p><code>make windows-test</code> (after <code>make test</code>; <code>WINDOWS_CC</code> names the compiler)
builds both archives and two codec programs, then runs them in a private
Wine prefix under a private Xvfb display and compares them with the Linux
CLI. The decoder-only program streams nine mono/stereo fixtures through
<code>DecoderOpen</code>/<code>DecoderRead</code> in 997-frame chunks, rewinds with
<code>DecoderRewind</code> and requires an identical second pass. Its inspection
<code>DecoderRewind</code> and requires an identical second pass. It streams the nine
MP3 fixtures the same way through <code>Mp3DecoderRead</code>, also requires a
mid-stream <code>Mp3DecoderSeek</code> and a rewind to reproduce the first pass, and
rejects a truncated MP3; their inspection lines and PCM16 matched Linux
bit-exactly. The six Vorbis fixtures take the same path through
<code>VorbisDecoderRead</code> and <code>VorbisDecoderSeek</code>, and a truncated Vorbis file is
rejected; their inspection and comment lines and PCM16 matched Linux
bit-exactly too. Its Opus inspection
lines, five malformed-stream rejections and decoded frame counts matched
Linux; PCM16 differed by at most 2 LSBs against the system libopus build
(3 of 9 bit-exact). The full-pipeline program encoded <code>voice.wav</code> with the
@@ -207,6 +383,40 @@ libopus decoder (within 1 PCM16 LSB). FFmpeg's independent decoder also checks
duration and the CELT sine fixtures; SILK/resampler implementations can differ
without a container timing error. No listening score or universal compression
quality claim follows from these tests.</p>
<p>MP3 tests (<code>tests/mp3_contracts.zi</code>, run by the native contracts) decode the
committed FFmpeg/libmp3lame fixtures in <code>tests/fixtures/mp3</code> (CBR, Xing VBR,
mono, 22.05 kHz MPEG-2, 11.025 kHz MPEG-2.5, no Xing header, Layer II and
ID3v2+ID3v1 tags; the README there lists the commands) against FFmpeg's own
PCM16 decode: at most 1.5 PCM16 steps and 0.5 steps RMS. Measured, Layer III
differs by at most 0.505 steps (the reference's own rounding) and Layer II by
1.04. Durations equal FFmpeg's exactly. Irregular streamed chunks, rewinds and
s16 reads equal the whole-file decode; seeks forward and back on an 8-second
32 kbps stream return bit-identical samples. One-byte and larger truncation,
garbage, silence, text, WAV, tags alone, free format, mid-stream tags and
mono/stereo changes are rejected, and 600 corrupted-payload decodes return a
status without crashing. <code>tests/portable.zi</code> checks inspection of synthetic
streams in the <code>.zx</code> engine and Go.</p>
<p>Vorbis tests (<code>tests/vorbis_contracts.zi</code>, run by the native contracts)
decode the committed FFmpeg/libvorbis fixtures in <code>tests/fixtures/vorbis</code>
(44.1 kHz stereo and mono, 22.05 kHz, 48 kHz, and a 32 kHz stream with
title, artist and UTF-8 comments; the README there lists the commands)
against FFmpeg's own PCM16 decode over the frames both hold: at most 1 PCM16
step and 0.35 steps RMS; measured, at most 0.501 steps (the reference's own
rounding) and 0.29 RMS. Lengths equal the final granule positions, which
ffprobe and libvorbisfile also report; FFmpeg's own decode ends up to a block
away from them. Irregular streamed chunks, rewinds and s16 reads equal the
whole-file decode, and seeks forward and back on an 8-second stream and two
short ones (into the end-trimmed tail too) return bit-identical samples.
Comments read back verbatim and by field name. Truncation, garbage, silence,
text, WAV, a CRC error, trailing bytes and synthetic streams with a timeline
offset, six channels, a 4 kHz rate, a granule past the decoded frames or no
audio are rejected; chained streams are <code>Unsupported</code>; an Ogg Opus stream is
not Vorbis and still inspects as Opus; and 600 decodes of fixtures with
corrupted setup-header or audio bytes behind refreshed CRCs return a status
without crashing. <code>tests/portable.zi</code> checks Vorbis inspection of a synthetic
stream in the <code>.zx</code> engine and Go. <code>make sanitize-test</code> runs the native
contracts with dr_mp3 and stb_vorbis (assertions on) and the generated C
under AddressSanitizer and UndefinedBehaviorSanitizer.</p>
<p>References: <a href="https://www.opus-codec.org/docs/opus_api-1.5.pdf">Opus public API 1.5</a>,
<a href="https://www.rfc-editor.org/rfc/rfc7845.html">RFC 7845 Ogg Opus</a>,
<a href="https://libsndfile.github.io/libsamplerate/api_full.html">libsamplerate state API</a>.</p></section>
@@ -232,6 +442,7 @@ quality claim follows from these tests.</p>
<div><code>Little :: (input: []u8, at: s64, count: s64) -&gt; u64</code></div>
<div><code>PutLittle :: (output: []u8, at: s64, count: s64, value: u64)</code></div>
<div><code>Magic :: (input: []u8, at: s64, text: string) -&gt; bool</code></div>
<div><code>Pcm16 :: (value: float64) -&gt; s16</code><p>The package's PCM16 boundary for finite samples: clip overshoot to [-1, 32767/32768], scale by 32768 and truncate, as WAV output does.</p></div>
<div><code>SwapSamples :: (pcm: *PCM, samples: *Vec(float32))</code><p>Move ownership between caller vector and PCM without copying samples.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/types.zi">Source ↗</a></p></section>
<section id="module-ogg"><p class="eyebrow">audio/src/ogg.zi</p><h2>ogg</h2><p>Import with <code>#import "audio/ogg"</code>.</p><div class="api-list">
@@ -272,5 +483,60 @@ quality claim follows from these tests.</p>
<div><code>SincProcess :: (state: *SincState, input: []float32, output: []float32, final: bool, used: *s64, generated: *s64) -&gt; s32</code><p>Caller supplies disjoint buffers. Respect both used and generated counts; keep feeding the unconsumed input, and drain with final=true until generated=0.</p></div>
<div><code>Resample :: (pcm: *PCM, target_rate: s32, output: *PCM) -&gt; s32</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/resample.zi">Source ↗</a></p></section>
<section id="module-mpeg_audio"><p class="eyebrow">audio/src/mpeg_audio.zi</p><h2>mpeg_audio</h2><p>Portable MPEG audio stream inspection for MP3 files: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III. It skips ID3v2, ID3v1 and APEv2 tags, reads Xing/Info, VBRI and LAME gapless headers, and walks every frame header, so the exact duration and truncation are known without a codec library. audio/mp3 decodes the bytes this module accepts.</p><p>Import with <code>#import "audio/mpeg_audio"</code>.</p><div class="api-list">
<div><code>Mp3Info :: struct { version: s32; layer: s32; channels: s32; rate: s32; frames: s64; mp3_frames: s64; frame_samples: s32; delay: s32; padding: s32; bitrate: s32; vbr: bool; audio_at: s64; audio_end: s64; }</code><p>`frames` is the exact PCM frame count a decoder returns: a Xing/Info frame count (or the walked frames) times the frame length, minus the LAME encoder delay and padding. Bitrate is nominal for CBR, the average for VBR.</p></div>
<div><code>Mp3Header :: struct { version: s32; layer: s32; rate: s32; channels: s32; kbps: s32; samples: s32; bytes: s64; crc: bool; }</code></div>
<div><code>Mp3MaxStreamFrames :: 4147200000</code></div>
<div><code>Mp3ParseHeader :: (input: []u8, at: s64, header: *Mp3Header) -&gt; s32</code><p>Parses the four-byte frame header at AT: Malformed when there is none, Unsupported for free-format frames, whose length no header states.</p></div>
<div><code>Mp3Inspect :: (input: []u8, info: *Mp3Info) -&gt; s32</code><p>Validates the whole stream before any decoder sees it. Every byte between the leading ID3v2 tags and the trailing ID3v1/APEv2 tags must be a complete frame with the first frame's version, layer, rate and channel count, optionally followed by zero padding. A partial last frame, a Xing count above the walked frames, junk between frames and non-MPEG input are Malformed. Clears INFO on failure.</p></div>
<div><code>Mp3Seconds :: (info: *Mp3Info) -&gt; float64</code></div>
<div><code>Mp3PrintInfo :: (info: *Mp3Info)</code><p>One summary line, shared by the CLI and the Windows decode check.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/mpeg_audio.zi">Source ↗</a></p></section>
<section id="module-mp3"><p class="eyebrow">audio/src/mp3.zi</p><h2>mp3</h2><p>MP3 decoding: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III, mono and stereo, through dr_mp3 (the pinned `dr_libs` source dependency, compiled by native/ziran_mp3.c into libziran_mp3.a). Native C only: link `libziran_mp3.a -lm`. audio/mpeg_audio validates every frame first, so dr_mp3 only sees a complete frame stream with its tags removed.</p><p>Import with <code>#import "audio/mp3"</code>.</p><div class="api-list">
<div><code>Mp3Decoder :: struct { handle: *void; info: Mp3Info; position: s64; owned: Vec(u8); }</code><p>Single-owner native state over borrowed bytes (or bytes it read itself with Mp3DecoderOpenFile). Do not copy a live decoder or call it concurrently; keep borrowed input alive and unchanged until close.</p></div>
<div><code>Mp3DecoderClose :: (decoder: *Mp3Decoder)</code></div>
<div><code>Mp3DecoderOpen :: (decoder: *Mp3Decoder, input: []u8, max_frames: s64) -&gt; s32</code><p>Inspects INPUT, then opens dr_mp3 over its frames with a seek table of about one point per second. MAX_FRAMES bounds the declared duration.</p></div>
<div><code>Mp3DecoderOpenFile :: (decoder: *Mp3Decoder, path: string, max_frames: s64) -&gt; s32</code><p>Reads the whole file (at most MaxBytes) into the decoder, which then owns it until Mp3DecoderClose.</p></div>
<div><code>Mp3DecoderRead :: (decoder: *Mp3Decoder, output: []float32, frames: *s64) -&gt; s32</code><p>Fills interleaved float frames. OK with zero frames is the logical end. An error may leave a filled prefix: discard it, then rewind or close.</p></div>
<div><code>Mp3DecoderReadS16 :: (decoder: *Mp3Decoder, output: []s16, frames: *s64) -&gt; s32</code><p>The same stream as interleaved PCM16: the float samples converted with Pcm16, so they equal the WAV output of the same decode.</p></div>
<div><code>Mp3DecoderSeek :: (decoder: *Mp3Decoder, frame: s64) -&gt; s32</code><p>Moves to exact PCM frame FRAME (0..frames): the next read returns the same samples a read from the start would. Seeks begin at the nearest seek point and decode forward, so the bit reservoir and overlap are primed.</p></div>
<div><code>Mp3DecoderRewind :: (decoder: *Mp3Decoder) -&gt; s32</code></div>
<div><code>Mp3Decode :: (input: []u8, max_frames: s64, output: *PCM) -&gt; s32</code><p>Whole-file float decode at the stream's own rate, bounded by MaxFrames. OUTPUT is unchanged on an error.</p></div>
<div><code>Mp3DecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *Mp3Info) -&gt; s32</code><p>Whole-file interleaved s16 decode; INFO describes the samples. Both outputs are unchanged on an error.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/mp3.zi">Source ↗</a></p></section>
<section id="module-mp3_resample"><p class="eyebrow">audio/src/mp3_resample.zi</p><h2>mp3_resample</h2><p>Whole-file MP3 decode converted to another rate with audio/resample's best sinc. Kept apart from audio/mp3 so decode-only consumers need no libsamplerate; streaming callers feed Mp3DecoderRead chunks to SincProcess.</p><p>Import with <code>#import "audio/mp3_resample"</code>.</p><div class="api-list">
<div><code>Mp3DecodeResampled :: (input: []u8, max_frames: s64, rate: s32, output: *PCM) -&gt; s32</code><p>OUTPUT holds float PCM at RATE (8000..192000), or the decoded PCM itself when the stream is already at RATE. OUTPUT is unchanged on an error.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/mp3_resample.zi">Source ↗</a></p></section>
<section id="module-ogg_vorbis"><p class="eyebrow">audio/src/ogg_vorbis.zi</p><h2>ogg_vorbis</h2><p>Portable Ogg Vorbis inspection (Vorbis I, mono and stereo). audio/ogg's OggReader checks the container (capture, CRC, one serial, page order, BOS/EOS, lacing); this module checks the identification, comment and setup headers and reads every audio packet's block size from the setup header's mode table, so the exact duration, the zero-based timeline and the end trim are known without a codec library. audio/vorbis decodes what it accepts.</p><p>Import with <code>#import "audio/ogg_vorbis"</code>.</p><div class="api-list">
<div><code>VorbisInfo :: struct { channels: s32; rate: s32; frames: s64; nominal_bitrate: s32; maximum_bitrate: s32; minimum_bitrate: s32; short_block: s32; long_block: s32; modes: s32; packets: s64; comments: s64; end_trim: s64; }</code><p>`frames` is the exact PCM frame count a decoder returns: the final granule position, which trims the last packet(s). Bitrates are the header's hints, 0 when unset.</p></div>
<div><code>VorbisComments :: struct { text: Vec(u8); vendor: s64; spans: Vec(s64); }</code><p>An owned copy of the comment header: the vendor string, then each user comment ("FIELD=value", UTF-8 by the specification; not validated here). Free it with VorbisCommentsFree (or let the vectors go out of scope).</p></div>
<div><code>VorbisMaxStreamFrames :: 4147200000</code></div>
<div><code>VorbisProbe :: (input: []u8) -&gt; bool</code><p>True when the first Ogg packet is a Vorbis identification header; Ogg Opus and other Ogg codecs are not.</p></div>
<div><code>VorbisInspect :: (input: []u8, info: *VorbisInfo) -&gt; s32</code><p>Validates every page and header of a single logical Ogg Vorbis stream before any decoder sees it, clearing INFO on failure. Truncation, CRC errors, bad headers, packets that are not audio, granule positions that disagree with the packets' block sizes and non-Vorbis input are Malformed; chained or multiplexed streams, a timeline not starting at zero, more than two channels and rates outside 8000..192000 Hz are Unsupported.</p></div>
<div><code>VorbisInspectComments :: (input: []u8, info: *VorbisInfo, comments: *VorbisComments) -&gt; s32</code><p>VorbisInspect that also copies the comment header into COMMENTS, which is unchanged on failure.</p></div>
<div><code>VorbisCommentsFree :: (comments: *VorbisComments)</code></div>
<div><code>VorbisCommentCount :: (comments: *VorbisComments) -&gt; s64</code></div>
<div><code>VorbisVendor :: (comments: *VorbisComments) -&gt; string</code><p>The returned strings borrow COMMENTS until it is freed or refilled.</p></div>
<div><code>VorbisComment :: (comments: *VorbisComments, index: s64) -&gt; string</code><p>Comment INDEX (0..VorbisCommentCount-1) as stored, "" when out of range.</p></div>
<div><code>VorbisCommentValue :: (comments: *VorbisComments, field: string) -&gt; string</code><p>The value of the first comment whose field name equals FIELD, ignoring ASCII case (Vorbis field names are case-insensitive), or "".</p></div>
<div><code>VorbisSeconds :: (info: *VorbisInfo) -&gt; float64</code></div>
<div><code>VorbisPrintInfo :: (info: *VorbisInfo)</code><p>One summary line, shared by the CLI and the Windows decode check.</p></div>
<div><code>VorbisPrintComments :: (comments: *VorbisComments)</code><p>The vendor and each comment on its own line.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/ogg_vorbis.zi">Source ↗</a></p></section>
<section id="module-vorbis"><p class="eyebrow">audio/src/vorbis.zi</p><h2>vorbis</h2><p>Ogg Vorbis decoding (Vorbis I, mono and stereo, 8-192 kHz) through stb_vorbis (the pinned `stb` source dependency, compiled by native/ziran_vorbis.c into libziran_vorbis.a). Native C only: link `libziran_vorbis.a -lm`. audio/ogg_vorbis validates the whole stream first, so stb_vorbis, which checks neither CRCs nor serial numbers, only sees one complete logical stream whose timeline starts at zero.</p><p>Import with <code>#import "audio/vorbis"</code>.</p><div class="api-list">
<div><code>VorbisDecoder :: struct { handle: *void; info: VorbisInfo; comments: VorbisComments; position: s64; owned: Vec(u8); }</code><p>Single-owner native state over borrowed bytes (or bytes it read itself with VorbisDecoderOpenFile). Do not copy a live decoder or call it concurrently; keep borrowed input alive and unchanged until close. `comments` holds the stream's comment header while the decoder is open.</p></div>
<div><code>VorbisDecoderClose :: (decoder: *VorbisDecoder)</code></div>
<div><code>VorbisDecoderOpen :: (decoder: *VorbisDecoder, input: []u8, max_frames: s64) -&gt; s32</code><p>Inspects INPUT, then opens stb_vorbis over it. MAX_FRAMES bounds the declared duration.</p></div>
<div><code>VorbisDecoderOpenFile :: (decoder: *VorbisDecoder, path: string, max_frames: s64) -&gt; s32</code><p>Reads the whole file (at most MaxBytes) into the decoder, which then owns it until VorbisDecoderClose.</p></div>
<div><code>VorbisDecoderRead :: (decoder: *VorbisDecoder, output: []float32, frames: *s64) -&gt; s32</code><p>Fills interleaved float frames. OK with zero frames is the logical end. An error may leave a filled prefix: discard it, then rewind or close.</p></div>
<div><code>VorbisDecoderReadS16 :: (decoder: *VorbisDecoder, output: []s16, frames: *s64) -&gt; s32</code><p>The same stream as interleaved PCM16: the float samples converted with Pcm16, so they equal the WAV output of the same decode. A NaN, which only a corrupt stream can produce, becomes silence.</p></div>
<div><code>VorbisDecoderSeek :: (decoder: *VorbisDecoder, frame: s64) -&gt; s32</code><p>Moves to exact PCM frame FRAME (0..frames): the next read returns the same samples a read from the start would. stb_vorbis bisects the pages for the one holding FRAME, then decodes forward from the packet before it, so the window overlap is primed. An error leaves the decoder to rewind or close.</p></div>
<div><code>VorbisDecoderRewind :: (decoder: *VorbisDecoder) -&gt; s32</code></div>
<div><code>VorbisDecode :: (input: []u8, max_frames: s64, output: *PCM) -&gt; s32</code><p>Whole-file float decode at the stream's own rate, bounded by MaxFrames. OUTPUT is unchanged on an error.</p></div>
<div><code>VorbisDecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *VorbisInfo) -&gt; s32</code><p>Whole-file interleaved s16 decode; INFO describes the samples. Both outputs are unchanged on an error.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/vorbis.zi">Source ↗</a></p></section>
<section id="module-vorbis_resample"><p class="eyebrow">audio/src/vorbis_resample.zi</p><h2>vorbis_resample</h2><p>Whole-file Ogg Vorbis decode converted to another rate with audio/resample's best sinc. Kept apart from audio/vorbis so decode-only consumers need no libsamplerate; streaming callers feed VorbisDecoderRead chunks to SincOpen/SincProcess.</p><p>Import with <code>#import "audio/vorbis_resample"</code>.</p><div class="api-list">
<div><code>VorbisDecodeResampled :: (input: []u8, max_frames: s64, rate: s32, output: *PCM) -&gt; s32</code><p>OUTPUT holds float PCM at RATE (8000..192000), or the decoded PCM itself when the stream is already at RATE. OUTPUT is unchanged on an error.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/audio/blob/HEAD/src/vorbis_resample.zi">Source ↗</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+17
View File
@@ -44,6 +44,22 @@
<url><loc>https://ziran-lang.org/packages/webp</loc></url>
<url><loc>https://ziran-lang.org/status</loc></url>
<url><loc>https://ziran-lang.org/std/atomic_go</loc></url>
<url><loc>https://ziran-lang.org/std/audio</loc></url>
<url><loc>https://ziran-lang.org/std/audio_android_aaudio</loc></url>
<url><loc>https://ziran-lang.org/std/audio_android_buffer</loc></url>
<url><loc>https://ziran-lang.org/std/audio_android_opensl</loc></url>
<url><loc>https://ziran-lang.org/std/audio_decode_mp3</loc></url>
<url><loc>https://ziran-lang.org/std/audio_decode_vorbis</loc></url>
<url><loc>https://ziran-lang.org/std/audio_decode_wav</loc></url>
<url><loc>https://ziran-lang.org/std/audio_device</loc></url>
<url><loc>https://ziran-lang.org/std/audio_mp3</loc></url>
<url><loc>https://ziran-lang.org/std/audio_mpeg</loc></url>
<url><loc>https://ziran-lang.org/std/audio_sink</loc></url>
<url><loc>https://ziran-lang.org/std/audio_sink_android</loc></url>
<url><loc>https://ziran-lang.org/std/audio_sink_sdl</loc></url>
<url><loc>https://ziran-lang.org/std/audio_sink_web</loc></url>
<url><loc>https://ziran-lang.org/std/audio_types</loc></url>
<url><loc>https://ziran-lang.org/std/audio_wav</loc></url>
<url><loc>https://ziran-lang.org/std/binary</loc></url>
<url><loc>https://ziran-lang.org/std/binary_linux</loc></url>
<url><loc>https://ziran-lang.org/std/bundle_host</loc></url>
@@ -97,6 +113,7 @@
<url><loc>https://ziran-lang.org/std/net_http_linux</loc></url>
<url><loc>https://ziran-lang.org/std/net_ws_curl_linux</loc></url>
<url><loc>https://ziran-lang.org/std/number_text</loc></url>
<url><loc>https://ziran-lang.org/std/ogg</loc></url>
<url><loc>https://ziran-lang.org/std/option</loc></url>
<url><loc>https://ziran-lang.org/std/pair</loc></url>
<url><loc>https://ziran-lang.org/std/parallel</loc></url>
+47
View File
@@ -0,0 +1,47 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Audio mixer: voices of decoded or streamed sound, each with its own gain, pitch and loop, mixed into interleaved float32 stereo at 48 kHz, with a tap that sees every mixed block."><title>std/audio · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio</h1><p>Audio mixer: voices of decoded or streamed sound, each with its own gain, pitch and loop, mixed into interleaved float32 stereo at 48 kHz, with a tap that sees every mixed block. It owns no device: a sink (std/audio_sink) asks it for blocks from its audio thread, and a test can render into a buffer of its own. Decoders join through AudioUseDecoder (std/audio_decode_wav, std/audio_decode_mp3); each recognizes its content, never a file name. A sound loads decoded whole; music decodes while it plays. A PCM stream plays signed 16-bit blocks the program submits and never finishes: it plays silence until the next block. Every call here belongs to the application thread; while a sink runs, each holds the sink's lock, so the audio thread sees a voice either before or after a change.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#AUDIO_RATE">AUDIO_RATE</a><a href="#AUDIO_VOICES">AUDIO_VOICES</a><a href="#AudioSource">AudioSource</a><a href="#AudioSourceRead">AudioSourceRead</a><a href="#AudioSourceRewind">AudioSourceRewind</a><a href="#AudioSourceClose">AudioSourceClose</a><a href="#AudioSourceSeek">AudioSourceSeek</a><a href="#AudioDecoderProbe">AudioDecoderProbe</a><a href="#AudioDecoderOpen">AudioDecoderOpen</a><a href="#AudioTap">AudioTap</a><a href="#AudioLockCall">AudioLockCall</a><a href="#AudioVoiceState">AudioVoiceState</a><a href="#AudioVoice">AudioVoice</a><a href="#AudioDecodedSource">AudioDecodedSource</a><a href="#AudioUseDecoder">AudioUseDecoder</a><a href="#AudioUseLock">AudioUseLock</a><a href="#AudioUseTap">AudioUseTap</a><a href="#AudioSetMasterGain">AudioSetMasterGain</a><a href="#AudioRender">AudioRender</a><a href="#AudioLoad">AudioLoad</a><a href="#AudioLoadFile">AudioLoadFile</a><a href="#AudioOpenStream">AudioOpenStream</a><a href="#AudioStreamWritable">AudioStreamWritable</a><a href="#AudioStreamSubmit">AudioStreamSubmit</a><a href="#AudioPlay">AudioPlay</a><a href="#AudioStop">AudioStop</a><a href="#AudioPause">AudioPause</a><a href="#AudioResume">AudioResume</a><a href="#AudioState">AudioState</a><a href="#AudioPlaying">AudioPlaying</a><a href="#AudioSetGain">AudioSetGain</a><a href="#AudioSetPitch">AudioSetPitch</a><a href="#AudioSetLooping">AudioSetLooping</a><a href="#AudioSeek">AudioSeek</a><a href="#AudioPosition">AudioPosition</a><a href="#AudioLength">AudioLength</a><a href="#AudioUnload">AudioUnload</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio"</code>.</p><div class="api-list">
<div id="AUDIO_RATE"><code>AUDIO_RATE :: 48000</code></div>
<div id="AUDIO_VOICES"><code>AUDIO_VOICES :: 32</code></div>
<div id="AudioSource"><code>AudioSource :: struct { state: *void; read: AudioSourceRead; rewind: AudioSourceRewind; close: AudioSourceClose; seek: AudioSourceSeek; rate: s32; channels: s32; frames: s64; }</code><p>Interleaved float32 frames at `rate`, from a decoder.</p></div>
<div id="AudioSourceRead"><code>AudioSourceRead :: #type (state: *void, output: []float32, frames: s64) -&gt; s64</code></div>
<div id="AudioSourceRewind"><code>AudioSourceRewind :: #type (state: *void) -&gt; bool</code></div>
<div id="AudioSourceClose"><code>AudioSourceClose :: #type (state: *void)</code></div>
<div id="AudioSourceSeek"><code>AudioSourceSeek :: #type (state: *void, frame: s64) -&gt; bool</code><p>A decoder: whether BYTES are its format, and a source over them. The bytes</p></div>
<div id="AudioDecoderProbe"><code>AudioDecoderProbe :: #type (bytes: []u8) -&gt; bool</code><p>A decoder: whether BYTES are its format, and a source over them. The bytes stay valid and unchanged until the source closes.</p></div>
<div id="AudioDecoderOpen"><code>AudioDecoderOpen :: #type (bytes: []u8, source: *AudioSource) -&gt; bool</code></div>
<div id="AudioTap"><code>AudioTap :: #type (samples: []float32, frames: s64)</code><p>Sees each mixed block: `frames` stereo frames, on the sink's audio thread.</p></div>
<div id="AudioLockCall"><code>AudioLockCall :: #type ()</code></div>
<div id="AudioVoiceState"><code>AudioVoiceState :: enum { Unloaded = 0; Stopped = 1; Playing = 2; Paused = 3; Finished = 4; }</code></div>
<div id="AudioVoice"><code>AudioVoice :: struct { slot: s32; generation: u32; }</code></div>
<div id="AudioDecodedSource"><code>AudioDecodedSource :: (samples: *Vec(float32), rate: s32, channels: s32, source: *AudioSource) -&gt; bool</code><p>A source over frames decoded whole, which it takes from SAMPLES.</p></div>
<div id="AudioUseDecoder"><code>AudioUseDecoder :: (probe: AudioDecoderProbe, open: AudioDecoderOpen) -&gt; bool</code><p>A decoder module registers itself from its initializer.</p></div>
<div id="AudioUseLock"><code>AudioUseLock :: (enter: AudioLockCall, leave: AudioLockCall)</code><p>The sink's lock around changes the audio thread could see.</p></div>
<div id="AudioUseTap"><code>AudioUseTap :: (next: AudioTap)</code></div>
<div id="AudioSetMasterGain"><code>AudioSetMasterGain :: (gain: float32)</code></div>
<div id="AudioRender"><code>AudioRender :: (output: []float32, frames: s64)</code><p>Mixes FRAMES stereo frames of every playing voice into OUTPUT, replacing what it held, then shows them to the tap. The sink's audio thread calls this; a test can call it directly.</p></div>
<div id="AudioLoad"><code>AudioLoad :: (bytes: string, stream: bool) -&gt; AudioVoice</code><p>A voice of BYTES in the first registered format that recognizes them: decoded whole now, or, for music (`stream`), while it plays. The bytes are copied; slot -1 when no decoder knows them or every voice is in use.</p></div>
<div id="AudioLoadFile"><code>AudioLoadFile :: (path: string, stream: bool) -&gt; AudioVoice</code></div>
<div id="AudioOpenStream"><code>AudioOpenStream :: (rate: s32, channels: s32, frames: s32) -&gt; AudioVoice</code><p>A stream of signed 16-bit blocks of FRAMES frames each, at RATE.</p></div>
<div id="AudioStreamWritable"><code>AudioStreamWritable :: (voice: AudioVoice) -&gt; bool</code><p>Room for another whole block.</p></div>
<div id="AudioStreamSubmit"><code>AudioStreamSubmit :: (voice: AudioVoice, samples: []s16) -&gt; bool</code><p>Copies one whole block of interleaved samples; false when it is not exactly one block or there is no room.</p></div>
<div id="AudioPlay"><code>AudioPlay :: (voice: AudioVoice) -&gt; bool</code><p>From the start.</p></div>
<div id="AudioStop"><code>AudioStop :: (voice: AudioVoice)</code></div>
<div id="AudioPause"><code>AudioPause :: (voice: AudioVoice)</code></div>
<div id="AudioResume"><code>AudioResume :: (voice: AudioVoice)</code></div>
<div id="AudioState"><code>AudioState :: (voice: AudioVoice) -&gt; AudioVoiceState</code></div>
<div id="AudioPlaying"><code>AudioPlaying :: (voice: AudioVoice) -&gt; bool</code></div>
<div id="AudioSetGain"><code>AudioSetGain :: (voice: AudioVoice, gain: float32)</code><p>0 is silent, 1 as decoded.</p></div>
<div id="AudioSetPitch"><code>AudioSetPitch :: (voice: AudioVoice, pitch: float32)</code><p>Speed and pitch together: 2 plays an octave up in half the time.</p></div>
<div id="AudioSetLooping"><code>AudioSetLooping :: (voice: AudioVoice, looping: bool)</code></div>
<div id="AudioSeek"><code>AudioSeek :: (voice: AudioVoice, seconds: float64) -&gt; bool</code><p>Seeks to seconds within a seekable source. Playing/paused/stopped states are preserved; a finished voice becomes paused, ready to resume there. Live PCM streams and unsupported decoder sources return false unchanged.</p></div>
<div id="AudioPosition"><code>AudioPosition :: (voice: AudioVoice) -&gt; float64</code><p>Seconds played since the start, or since the loop began again.</p></div>
<div id="AudioLength"><code>AudioLength :: (voice: AudioVoice) -&gt; float64</code><p>Seconds of the whole sound, or -1 when its decoder cannot say.</p></div>
<div id="AudioUnload"><code>AudioUnload :: (voice: AudioVoice)</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="AAudio is loaded at runtime so an API-21 app still loads on API 21-25."><title>std/audio_android_aaudio · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_android_aaudio"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_android_aaudio</h1><p>AAudio is loaded at runtime so an API-21 app still loads on API 21-25. All entry points below were introduced in API 26. No AAudio link is needed.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#Available">Available</a><a href="#Ready">Ready</a><a href="#Close">Close</a><a href="#Open">Open</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_android_aaudio"</code>.</p><div class="api-list">
<div id="Available"><code>Available :: () -&gt; bool</code></div>
<div id="Ready"><code>Ready :: () -&gt; bool</code></div>
<div id="Close"><code>Close :: ()</code></div>
<div id="Open"><code>Open :: () -&gt; bool</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_android_aaudio.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Shared Android mixer boundary."><title>std/audio_android_buffer · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_android_buffer"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_android_buffer</h1><p>Shared Android mixer boundary. Bionic pthread_mutex_t fits this aligned storage on all Android ABIs; its static zero initializer is PTHREAD_MUTEX_INITIALIZER. The lock outlives devices, so voices remain safe after close and reopen.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#Enter">Enter</a><a href="#Leave">Leave</a><a href="#Install">Install</a><a href="#Library">Library</a><a href="#Resolve">Resolve</a><a href="#RenderFloat">RenderFloat</a><a href="#RenderPCM">RenderPCM</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_android_buffer"</code>.</p><div class="api-list">
<div id="Enter"><code>Enter :: ()</code></div>
<div id="Leave"><code>Leave :: ()</code></div>
<div id="Install"><code>Install :: ()</code></div>
<div id="Library"><code>Library :: (name: string) -&gt; *void</code></div>
<div id="Resolve"><code>Resolve :: (library: *void, slot: *void, name: string) -&gt; bool</code></div>
<div id="RenderFloat"><code>RenderFloat :: (output: *void, frames: s32)</code></div>
<div id="RenderPCM"><code>RenderPCM :: (output: []s16, frames: s32)</code><p>OpenSL ES on API 21 accepts signed 16-bit PCM. Convert the mixer's clipped stereo float output without allocating or retaining a caller's buffer.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_android_buffer.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="API-21 PCM output."><title>std/audio_android_opensl · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_android_opensl"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_android_opensl</h1><p>API-21 PCM output. Android's simple buffer queue owns two alternating signed-16 stereo blocks. Only the completed block is refilled.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#Ready">Ready</a><a href="#Close">Close</a><a href="#Open">Open</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_android_opensl"</code>.</p><div class="api-list">
<div id="Ready"><code>Ready :: () -&gt; bool</code></div>
<div id="Close"><code>Close :: ()</code></div>
<div id="Open"><code>Open :: () -&gt; bool</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_android_opensl.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+9
View File
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="MPEG audio for std/audio: MP3 (MPEG-1, 2 and 2.5 Layer III) and Layers I and II, decoded as it plays by std/audio_mp3 over dr_mp3 at the stream&#x27;s own rate."><title>std/audio_decode_mp3 · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_decode_mp3"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_decode_mp3</h1><p>MPEG audio for std/audio: MP3 (MPEG-1, 2 and 2.5 Layer III) and Layers I and II, decoded as it plays by std/audio_mp3 over dr_mp3 at the stream's own rate. Importing this module is what adds the format; native programs link audio's libziran_mp3.a (make's $(MP3_A)) and -lm.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><span>None</span></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_decode_mp3"</code>.</p><p>No public declarations.</p><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_decode_mp3.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+9
View File
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Register the existing guarded libvorbisfile decoder with std/audio."><title>std/audio_decode_vorbis · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_decode_vorbis"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_decode_vorbis</h1><p>Register the existing guarded libvorbisfile decoder with std/audio.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><span>None</span></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_decode_vorbis"</code>.</p><p>No public declarations.</p><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_decode_vorbis.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+9
View File
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="RIFF WAVE for std/audio, PCM16 or float32, decoded whole by std/audio_wav."><title>std/audio_decode_wav · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_decode_wav"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_decode_wav</h1><p>RIFF WAVE for std/audio, PCM16 or float32, decoded whole by std/audio_wav. Importing this module is what adds the format.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><span>None</span></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_decode_wav"</code>.</p><p>No public declarations.</p><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_decode_wav.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Caller-owned asynchronous device open."><title>std/audio_device · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_device"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_device</h1><p>Caller-owned asynchronous device open. Only the application thread touches this record; the worker publishes its result through ThreadFinished.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#OpenCall">OpenCall</a><a href="#CloseCall">CloseCall</a><a href="#Device">Device</a><a href="#Poll">Poll</a><a href="#Pending">Pending</a><a href="#Unavailable">Unavailable</a><a href="#Ready">Ready</a><a href="#Open">Open</a><a href="#Close">Close</a><a href="#Invalidate">Invalidate</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_device"</code>.</p><div class="api-list">
<div id="OpenCall"><code>OpenCall :: #type () -&gt; bool</code></div>
<div id="CloseCall"><code>CloseCall :: #type ()</code></div>
<div id="Device"><code>Device :: struct { worker: Thread; open: OpenCall; close: CloseCall; result: bool; ready: bool; attempted: bool; retry_at: s64; }</code></div>
<div id="Poll"><code>Poll :: (device: *Device)</code></div>
<div id="Pending"><code>Pending :: (device: *Device) -&gt; bool</code></div>
<div id="Unavailable"><code>Unavailable :: (device: *Device) -&gt; bool</code></div>
<div id="Ready"><code>Ready :: (device: *Device) -&gt; bool</code></div>
<div id="Open"><code>Open :: (device: *Device, open: OpenCall, close: CloseCall) -&gt; bool</code></div>
<div id="Close"><code>Close :: (device: *Device)</code></div>
<div id="Invalidate"><code>Invalidate :: (device: *Device)</code><p>A backend's disconnect callback made a previously opened device unusable.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_device.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="MP3 decoding: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III, mono and stereo, through dr_mp3 (the pinned `dr_libs` source dependency, compiled by native/ziran_mp3.c into libziran_mp3.a)."><title>std/audio_mp3 · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_mp3"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_mp3</h1><p>MP3 decoding: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III, mono and stereo, through dr_mp3 (the pinned `dr_libs` source dependency, compiled by native/ziran_mp3.c into libziran_mp3.a). Native C only: link `libziran_mp3.a -lm`. std/audio_mpeg validates every frame first, so dr_mp3 only sees a complete frame stream with its tags removed.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#Mp3Decoder">Mp3Decoder</a><a href="#Mp3DecoderClose">Mp3DecoderClose</a><a href="#Mp3DecoderOpen">Mp3DecoderOpen</a><a href="#Mp3DecoderOpenFile">Mp3DecoderOpenFile</a><a href="#Mp3DecoderRead">Mp3DecoderRead</a><a href="#Mp3DecoderReadS16">Mp3DecoderReadS16</a><a href="#Mp3DecoderSeek">Mp3DecoderSeek</a><a href="#Mp3DecoderRewind">Mp3DecoderRewind</a><a href="#Mp3Decode">Mp3Decode</a><a href="#Mp3DecodeS16">Mp3DecodeS16</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_mp3"</code>.</p><div class="api-list">
<div id="Mp3Decoder"><code>Mp3Decoder :: struct { handle: *void; info: Mp3Info; position: s64; owned: Vec(u8); }</code><p>Single-owner native state over borrowed bytes (or bytes it read itself with Mp3DecoderOpenFile). Do not copy a live decoder or call it concurrently; keep borrowed input alive and unchanged until close.</p></div>
<div id="Mp3DecoderClose"><code>Mp3DecoderClose :: (decoder: *Mp3Decoder)</code></div>
<div id="Mp3DecoderOpen"><code>Mp3DecoderOpen :: (decoder: *Mp3Decoder, input: []u8, max_frames: s64) -&gt; s32</code><p>Inspects INPUT, then opens dr_mp3 over its frames with a seek table of about one point per second. MAX_FRAMES bounds the declared duration.</p></div>
<div id="Mp3DecoderOpenFile"><code>Mp3DecoderOpenFile :: (decoder: *Mp3Decoder, path: string, max_frames: s64) -&gt; s32</code><p>Reads the whole file (at most MaxBytes) into the decoder, which then owns it until Mp3DecoderClose.</p></div>
<div id="Mp3DecoderRead"><code>Mp3DecoderRead :: (decoder: *Mp3Decoder, output: []float32, frames: *s64) -&gt; s32</code><p>Fills interleaved float frames. OK with zero frames is the logical end. An error may leave a filled prefix: discard it, then rewind or close.</p></div>
<div id="Mp3DecoderReadS16"><code>Mp3DecoderReadS16 :: (decoder: *Mp3Decoder, output: []s16, frames: *s64) -&gt; s32</code><p>The same stream as interleaved PCM16: the float samples converted with Pcm16, so they equal the WAV output of the same decode.</p></div>
<div id="Mp3DecoderSeek"><code>Mp3DecoderSeek :: (decoder: *Mp3Decoder, frame: s64) -&gt; s32</code><p>Moves to exact PCM frame FRAME (0..frames): the next read returns the same samples a read from the start would. Seeks begin at the nearest seek point and decode forward, so the bit reservoir and overlap are primed.</p></div>
<div id="Mp3DecoderRewind"><code>Mp3DecoderRewind :: (decoder: *Mp3Decoder) -&gt; s32</code></div>
<div id="Mp3Decode"><code>Mp3Decode :: (input: []u8, max_frames: s64, output: *PCM) -&gt; s32</code><p>Whole-file float decode at the stream's own rate, bounded by MaxFrames. OUTPUT is unchanged on an error.</p></div>
<div id="Mp3DecodeS16"><code>Mp3DecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *Mp3Info) -&gt; s32</code><p>Whole-file interleaved s16 decode; INFO describes the samples. Both outputs are unchanged on an error.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_mp3.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Portable MPEG audio stream inspection for MP3 files: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III."><title>std/audio_mpeg · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_mpeg"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_mpeg</h1><p>Portable MPEG audio stream inspection for MP3 files: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III. It skips ID3v2, ID3v1 and APEv2 tags, reads Xing/Info, VBRI and LAME gapless headers, and walks every frame header, so the exact duration and truncation are known without a codec library. std/audio_mp3 decodes the bytes this module accepts.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#Mp3Info">Mp3Info</a><a href="#Mp3Header">Mp3Header</a><a href="#Mp3MaxStreamFrames">Mp3MaxStreamFrames</a><a href="#Mp3ParseHeader">Mp3ParseHeader</a><a href="#Mp3Inspect">Mp3Inspect</a><a href="#Mp3Seconds">Mp3Seconds</a><a href="#Mp3PrintInfo">Mp3PrintInfo</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_mpeg"</code>.</p><div class="api-list">
<div id="Mp3Info"><code>Mp3Info :: struct { version: s32; layer: s32; channels: s32; rate: s32; frames: s64; mp3_frames: s64; frame_samples: s32; delay: s32; padding: s32; bitrate: s32; vbr: bool; audio_at: s64; audio_end: s64; }</code><p>`frames` is the exact PCM frame count a decoder returns: a Xing/Info frame count (or the walked frames) times the frame length, minus the LAME encoder delay and padding. Bitrate is nominal for CBR, the average for VBR.</p></div>
<div id="Mp3Header"><code>Mp3Header :: struct { version: s32; layer: s32; rate: s32; channels: s32; kbps: s32; samples: s32; bytes: s64; crc: bool; }</code></div>
<div id="Mp3MaxStreamFrames"><code>Mp3MaxStreamFrames :: 4147200000</code></div>
<div id="Mp3ParseHeader"><code>Mp3ParseHeader :: (input: []u8, at: s64, header: *Mp3Header) -&gt; s32</code><p>Parses the four-byte frame header at AT: Malformed when there is none, Unsupported for free-format frames, whose length no header states.</p></div>
<div id="Mp3Inspect"><code>Mp3Inspect :: (input: []u8, info: *Mp3Info) -&gt; s32</code><p>Validates the whole stream before any decoder sees it. Every byte between the leading ID3v2 tags and the trailing ID3v1/APEv2 tags must be a complete frame with the first frame's version, layer, rate and channel count, optionally followed by zero padding. A partial last frame, a Xing count above the walked frames, junk between frames and non-MPEG input are Malformed. Clears INFO on failure.</p></div>
<div id="Mp3Seconds"><code>Mp3Seconds :: (info: *Mp3Info) -&gt; float64</code></div>
<div id="Mp3PrintInfo"><code>Mp3PrintInfo :: (info: *Mp3Info)</code><p>One summary line, shared by the CLI and the Windows decode check.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_mpeg.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+9
View File
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Import the output device for the compilation target."><title>std/audio_sink · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_sink"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_sink</h1><p>Import the output device for the compilation target. PCM voices and mixing live in std/audio and can also be rendered without opening a device.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><span>None</span></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_sink"</code>.</p><p>No public declarations.</p><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_sink.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Android&#x27;s output device for the shared audio mixer."><title>std/audio_sink_android · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_sink_android"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_sink_android</h1><p>Android's output device for the shared audio mixer. The API-21 scaffold needs OpenSL ES on Android 5/6/7; devices with AAudio use float32 output. Public contract matches audio_sink_sdl. Call open/close on the application thread.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#AudioSinkOpen">AudioSinkOpen</a><a href="#AudioSinkReady">AudioSinkReady</a><a href="#AudioSinkPending">AudioSinkPending</a><a href="#AudioSinkUnavailable">AudioSinkUnavailable</a><a href="#AudioSinkClose">AudioSinkClose</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_sink_android"</code>.</p><div class="api-list">
<div id="AudioSinkOpen"><code>AudioSinkOpen :: () -&gt; bool</code></div>
<div id="AudioSinkReady"><code>AudioSinkReady :: () -&gt; bool</code></div>
<div id="AudioSinkPending"><code>AudioSinkPending :: () -&gt; bool</code></div>
<div id="AudioSinkUnavailable"><code>AudioSinkUnavailable :: () -&gt; bool</code></div>
<div id="AudioSinkClose"><code>AudioSinkClose :: ()</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_sink_android.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Desktop audio output for std/audio: SDL2 opens the default output for 48 kHz float32 stereo, converting to what the device takes, and its audio thread pulls each block from the mixer."><title>std/audio_sink_sdl · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_sink_sdl"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_sink_sdl</h1><p>Desktop audio output for std/audio: SDL2 opens the default output for 48 kHz float32 stereo, converting to what the device takes, and its audio thread pulls each block from the mixer. It needs no window. With SDL_AUDIODRIVER=disk SDL writes the blocks to SDL_DISKAUDIOFILE instead, so a test hears exactly what was mixed without a device.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#AudioSinkOpen">AudioSinkOpen</a><a href="#AudioSinkReady">AudioSinkReady</a><a href="#AudioSinkPending">AudioSinkPending</a><a href="#AudioSinkUnavailable">AudioSinkUnavailable</a><a href="#AudioSinkClose">AudioSinkClose</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_sink_sdl"</code>.</p><div class="api-list">
<div id="AudioSinkOpen"><code>AudioSinkOpen :: () -&gt; bool</code><p>Requests a background open; false while pending or unavailable. Retry is throttled for one second after failure. Ready/Pending/Unavailable poll it.</p></div>
<div id="AudioSinkReady"><code>AudioSinkReady :: () -&gt; bool</code></div>
<div id="AudioSinkPending"><code>AudioSinkPending :: () -&gt; bool</code></div>
<div id="AudioSinkUnavailable"><code>AudioSinkUnavailable :: () -&gt; bool</code></div>
<div id="AudioSinkClose"><code>AudioSinkClose :: ()</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_sink_sdl.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="WebAudio output for std/audio."><title>std/audio_sink_web · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_sink_web"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_sink_web</h1><p>WebAudio output for std/audio. A short timer schedules two immutable PCM buffers ahead of the audio clock; suspended contexts do not consume voices. The application calls AudioSinkResume from a trusted gesture when required.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#AudioSinkReady">AudioSinkReady</a><a href="#AudioSinkPending">AudioSinkPending</a><a href="#AudioSinkUnavailable">AudioSinkUnavailable</a><a href="#AudioSinkRunning">AudioSinkRunning</a><a href="#AudioSinkResume">AudioSinkResume</a><a href="#AudioSinkClose">AudioSinkClose</a><a href="#AudioSinkOpen">AudioSinkOpen</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_sink_web"</code>.</p><div class="api-list">
<div id="AudioSinkReady"><code>AudioSinkReady :: () -&gt; bool</code></div>
<div id="AudioSinkPending"><code>AudioSinkPending :: () -&gt; bool</code></div>
<div id="AudioSinkUnavailable"><code>AudioSinkUnavailable :: () -&gt; bool</code></div>
<div id="AudioSinkRunning"><code>AudioSinkRunning :: () -&gt; bool</code></div>
<div id="AudioSinkResume"><code>AudioSinkResume :: () -&gt; bool</code></div>
<div id="AudioSinkClose"><code>AudioSinkClose :: ()</code></div>
<div id="AudioSinkOpen"><code>AudioSinkOpen :: () -&gt; bool</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_sink_web.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+28
View File
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="API reference for the Ziran std/audio_types module."><title>std/audio_types · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_types"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_types</h1><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#OK">OK</a><a href="#Invalid">Invalid</a><a href="#Malformed">Malformed</a><a href="#Unsupported">Unsupported</a><a href="#LimitExceeded">LimitExceeded</a><a href="#NativeFailure">NativeFailure</a><a href="#AllocationFailed">AllocationFailed</a><a href="#IOFailure">IOFailure</a><a href="#PCM">PCM</a><a href="#MaxBytes">MaxBytes</a><a href="#MaxFrames">MaxFrames</a><a href="#ValidPCM">ValidPCM</a><a href="#ErrorText">ErrorText</a><a href="#Little">Little</a><a href="#PutLittle">PutLittle</a><a href="#Magic">Magic</a><a href="#Pcm16">Pcm16</a><a href="#SwapSamples">SwapSamples</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_types"</code>.</p><div class="api-list">
<div id="OK"><code>OK :: 0</code></div>
<div id="Invalid"><code>Invalid :: 2</code></div>
<div id="Malformed"><code>Malformed :: 3</code></div>
<div id="Unsupported"><code>Unsupported :: 4</code></div>
<div id="LimitExceeded"><code>LimitExceeded :: 5</code></div>
<div id="NativeFailure"><code>NativeFailure :: 6</code></div>
<div id="AllocationFailed"><code>AllocationFailed :: 7</code></div>
<div id="IOFailure"><code>IOFailure :: 8</code></div>
<div id="PCM"><code>PCM :: struct { samples: Vec(float32); rate: s32; channels: s32; }</code><p>Memory/work bounds apply before allocations. Rates are bounded to avoid</p></div>
<div id="MaxBytes"><code>MaxBytes :: 268435456</code><p>Memory/work bounds apply before allocations. Rates are bounded to avoid enormous output for hostile headers. Whole-file APIs are intentionally bounded.</p></div>
<div id="MaxFrames"><code>MaxFrames :: 28800000</code></div>
<div id="ValidPCM"><code>ValidPCM :: (pcm: *PCM) -&gt; bool</code></div>
<div id="ErrorText"><code>ErrorText :: (code: s32) -&gt; string</code></div>
<div id="Little"><code>Little :: (input: []u8, at: s64, count: s64) -&gt; u64</code></div>
<div id="PutLittle"><code>PutLittle :: (output: []u8, at: s64, count: s64, value: u64)</code></div>
<div id="Magic"><code>Magic :: (input: []u8, at: s64, text: string) -&gt; bool</code></div>
<div id="Pcm16"><code>Pcm16 :: (value: float64) -&gt; s16</code><p>The PCM16 boundary for finite samples: clip overshoot to [-1, 32767/32768], scale by 32768 and truncate, as WAV output does.</p></div>
<div id="SwapSamples"><code>SwapSamples :: (pcm: *PCM, samples: *Vec(float32))</code><p>Move ownership between caller vector and PCM without copying samples.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_types.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="API reference for the Ziran std/audio_wav module."><title>std/audio_wav · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/audio_wav"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/audio_wav</h1><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#WavDecode">WavDecode</a><a href="#WavEncode">WavEncode</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/audio_wav"</code>.</p><div class="api-list">
<div id="WavDecode"><code>WavDecode :: (input: []u8, max_frames: s64, output: *PCM) -&gt; s32</code><p>Canonical RIFF WAVE PCM16 or IEEE float32 mono/stereo. Unknown chunks are skipped with padding, but duplicate fmt/data, RF64 and compressed WAV reject.</p></div>
<div id="WavEncode"><code>WavEncode :: (pcm: *PCM, output: *Vec(u8)) -&gt; s32</code><p>PCM16 output clips finite sinc/codec overshoots at the integer boundary.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/audio_wav.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Portable Ogg container validation and bounded packet/page construction."><title>std/ogg · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/ogg"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/ogg</h1><p>Portable Ogg container validation and bounded packet/page construction.</p><p class="module-meta"><span class="status-badge is-in-progress">In progress</span> Available on master (Unreleased).</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#OggCRC">OggCRC</a><a href="#OggReader">OggReader</a><a href="#NextPacket">NextPacket</a><a href="#AppendPage">AppendPage</a><a href="#PageBuilder">PageBuilder</a><a href="#PageAdd">PageAdd</a><a href="#PageFlush">PageFlush</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/ogg"</code>.</p><div class="api-list">
<div id="OggCRC"><code>OggCRC :: (page: []u8) -&gt; u32</code><p>Ogg CRC-32 (non-reflected), with the checksum field treated as zero.</p></div>
<div id="OggReader"><code>OggReader :: struct { input: []u8; at: s64; end: s64; body: s64; segment: s64; segments: s64; serial: u64; sequence: u64; granule: s64; flags: u8; packet: [65536]u8; packet_count: s64; done: bool; page_last: bool; last_complete: bool; }</code><p>Bounded packet iterator. Borrowed input must outlive this record. A returned packet is valid until the next call; never retain a view over NextPacket.</p></div>
<div id="NextPacket"><code>NextPacket :: (reader: *OggReader) -&gt; s32</code></div>
<div id="AppendPage"><code>AppendPage :: (output: *Vec(u8), packet: []u8, flags: u8, granule: s64, serial: u32, sequence: u32) -&gt; s32</code><p>One complete packet per page. Output is staged by the whole-file encoder.</p></div>
<div id="PageBuilder"><code>PageBuilder :: struct { body: [65025]u8; laces: [255]u8; count: s64; segments: s64; }</code><p>Efficient file muxing: accumulate up to 200 ms or 255 lacing entries in a page, amortizing the 27-byte header without changing Opus frame latency.</p></div>
<div id="PageAdd"><code>PageAdd :: (page: *PageBuilder, packet: []u8) -&gt; s32</code></div>
<div id="PageFlush"><code>PageFlush :: (page: *PageBuilder, output: *Vec(u8), final: bool, granule: s64, sequence: u32) -&gt; s32</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/ogg.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+18 -5
View File
@@ -1,12 +1,25 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="What an Ogg Vorbis stream held in memory declares, read from its pages alone: nothing is decoded or allocated, so a program can bound a stream before handing it to a decoder (std/vorbis_linux on Linux, or another platform&#x27;s)."><title>std/vorbis · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/vorbis"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Portable Ogg Vorbis inspection (Vorbis I)."><title>std/vorbis · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/vorbis"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/vorbis</h1><p>What an Ogg Vorbis stream held in memory declares, read from its pages alone: nothing is decoded or allocated, so a program can bound a stream before handing it to a decoder (std/vorbis_linux on Linux, or another platform's). Portable: no foreign library. audio: VorbisAudio if VorbisProbe(ogg_bytes, *audio) &amp;&amp; audio.channels == 1 { ... }</p><p class="module-meta"><span class="status-badge is-stable">Stable</span> Shipped in release <a href="https://github.com/ziranlang/ziran/releases/tag/v0.6.0">v0.6.0</a>.</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#VorbisAudio">VorbisAudio</a><a href="#VorbisProbe">VorbisProbe</a></aside><div class="article-body api-body">
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/vorbis</h1><p>Portable Ogg Vorbis inspection (Vorbis I). std/ogg's OggReader checks the container (capture, CRC, one serial, page order, BOS/EOS, lacing); this module checks the identification, comment and setup headers and reads every audio packet's block size from the setup header's mode table, so the exact duration, the zero-based timeline and the end trim are known without a codec library. std/vorbis_linux decodes what it accepts.</p><p class="module-meta"><span class="status-badge is-stable">Stable</span> Shipped in release <a href="https://github.com/ziranlang/ziran/releases/tag/v0.6.0">v0.6.0</a>.</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#VorbisAudio">VorbisAudio</a><a href="#VorbisComments">VorbisComments</a><a href="#VorbisMaxStreamFrames">VorbisMaxStreamFrames</a><a href="#VorbisRecognizes">VorbisRecognizes</a><a href="#VorbisInspect">VorbisInspect</a><a href="#VorbisInspectComments">VorbisInspectComments</a><a href="#VorbisCommentsFree">VorbisCommentsFree</a><a href="#VorbisCommentCount">VorbisCommentCount</a><a href="#VorbisVendor">VorbisVendor</a><a href="#VorbisComment">VorbisComment</a><a href="#VorbisCommentValue">VorbisCommentValue</a><a href="#VorbisSeconds">VorbisSeconds</a><a href="#VorbisPrintInfo">VorbisPrintInfo</a><a href="#VorbisPrintComments">VorbisPrintComments</a><a href="#VorbisProbe">VorbisProbe</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/vorbis"</code>.</p><div class="api-list">
<div id="VorbisAudio"><code>VorbisAudio :: struct { channels: s32; rate: s32; frames: s64; }</code><p>Interleaved CHANNELS at RATE, FRAMES long.</p></div>
<div id="VorbisProbe"><code>VorbisProbe :: (input: []u8, audio: *VorbisAudio) -&gt; bool</code><p>Whether INPUT is exactly one Ogg Vorbis stream: whole pages of a single logical stream and nothing else, beginning with its first page, ending with its last, and starting with a Vorbis identification header. AUDIO then holds its channels, rate and length, the last page's granule position (streams start at zero, as encoders write them). Page CRCs are left to the decoder. AUDIO is zero when the answer is false.</p></div>
<div id="VorbisAudio"><code>VorbisAudio :: struct { channels: s32; rate: s32; frames: s64; nominal_bitrate: s32; maximum_bitrate: s32; minimum_bitrate: s32; short_block: s32; long_block: s32; modes: s32; packets: s64; comments: s64; end_trim: s64; }</code><p>`frames` is the exact PCM frame count a decoder returns: the final granule position, which trims the last packet(s). Bitrates are the header's hints, 0 when unset.</p></div>
<div id="VorbisComments"><code>VorbisComments :: struct { text: Vec(u8); vendor: s64; spans: Vec(s64); }</code><p>An owned copy of the comment header: the vendor string, then each user comment ("FIELD=value", UTF-8 by the specification; not validated here). Free it with VorbisCommentsFree (or let the vectors go out of scope).</p></div>
<div id="VorbisMaxStreamFrames"><code>VorbisMaxStreamFrames :: 4147200000</code></div>
<div id="VorbisRecognizes"><code>VorbisRecognizes :: (input: []u8) -&gt; bool</code><p>True when the first Ogg packet is a Vorbis identification header; Ogg Opus and other Ogg codecs are not.</p></div>
<div id="VorbisInspect"><code>VorbisInspect :: (input: []u8, info: *VorbisAudio) -&gt; s32</code><p>Validates every page and header of a single logical Ogg Vorbis stream before any decoder sees it, clearing INFO on failure. Truncation, CRC errors, bad headers, packets that are not audio, granule positions that disagree with the packets' block sizes and non-Vorbis input are Malformed; chained or multiplexed streams and a timeline not starting at zero are Unsupported.</p></div>
<div id="VorbisInspectComments"><code>VorbisInspectComments :: (input: []u8, info: *VorbisAudio, comments: *VorbisComments) -&gt; s32</code><p>VorbisInspect that also copies the comment header into COMMENTS, which is unchanged on failure.</p></div>
<div id="VorbisCommentsFree"><code>VorbisCommentsFree :: (comments: *VorbisComments)</code></div>
<div id="VorbisCommentCount"><code>VorbisCommentCount :: (comments: *VorbisComments) -&gt; s64</code></div>
<div id="VorbisVendor"><code>VorbisVendor :: (comments: *VorbisComments) -&gt; string</code><p>The returned strings borrow COMMENTS until it is freed or refilled.</p></div>
<div id="VorbisComment"><code>VorbisComment :: (comments: *VorbisComments, index: s64) -&gt; string</code><p>Comment INDEX (0..VorbisCommentCount-1) as stored, "" when out of range.</p></div>
<div id="VorbisCommentValue"><code>VorbisCommentValue :: (comments: *VorbisComments, field: string) -&gt; string</code><p>The value of the first comment whose field name equals FIELD, ignoring ASCII case (Vorbis field names are case-insensitive), or "".</p></div>
<div id="VorbisSeconds"><code>VorbisSeconds :: (info: *VorbisAudio) -&gt; float64</code></div>
<div id="VorbisPrintInfo"><code>VorbisPrintInfo :: (info: *VorbisAudio)</code><p>One summary line, shared by the CLI and the Windows decode check.</p></div>
<div id="VorbisPrintComments"><code>VorbisPrintComments :: (comments: *VorbisComments)</code><p>The vendor and each comment on its own line.</p></div>
<div id="VorbisProbe"><code>VorbisProbe :: (input: []u8, audio: *VorbisAudio) -&gt; bool</code><p>Full portable validation with the stream's channels, rate and exact length. Metadata is cleared on failure; no native decoder is needed.</p></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/vorbis.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+11 -1
View File
@@ -3,7 +3,7 @@
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#f7f3eb"><meta name="description" content="Whole Ogg Vorbis streams held in memory, decoded over the platform libvorbisfile into signed 16-bit little-endian PCM."><title>std/vorbis_linux · Ziran</title><link rel="canonical" href="https://ziran-lang.org/std/vorbis_linux"><link rel="icon" href="../assets/logo-capybara.png" type="image/png"><link rel="stylesheet" href="../styles.css"><script defer src="../site.js"></script></head>
<body><a class="skip-link" href="#main">Skip to content</a><header class="site-header"><div class="site-header-inner"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><button class="menu-button" type="button" aria-expanded="false" aria-controls="primary-nav">Menu</button><nav class="header-nav" id="primary-nav" aria-label="Primary"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html" aria-current="page">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a><button class="theme-toggle" type="button" aria-label="Switch color theme"></button></nav></div></header>
<main id="main" class="article-layout"><div class="article-head"><p class="eyebrow"><a href="../modules.html#std">Modules</a> / Standard library</p><h1>std/vorbis_linux</h1><p>Whole Ogg Vorbis streams held in memory, decoded over the platform libvorbisfile into signed 16-bit little-endian PCM. std/vorbis checks the stream's pages and length first, before the library allocates anything. Only programs that import this module need the library; link it with -lvorbisfile, or with -l:libvorbisfile.so.3 where only the runtime package is installed. pcm: Vec(u8) audio: VorbisAudio if VorbisDecode(ogg_bytes, *pcm, 22050 * 60, *audio) { ... } The records below mirror the public declarations in libogg's ogg.h and libvorbis's codec.h and vorbisfile.h field for field, so the C compiler lays them out exactly as the library does. Every decode also checks a guard placed after its OggVorbis_File, so a library that wrote past the mirror fails the decode instead of passing unnoticed.</p><p class="module-meta"><span class="status-badge is-stable">Stable</span> <span class="module-target">Needs: Native Linux.</span> Shipped in release <a href="https://github.com/ziranlang/ziran/releases/tag/v0.6.0">v0.6.0</a>.</p></div>
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#OggSyncState">OggSyncState</a><a href="#OggStreamState">OggStreamState</a><a href="#OggPackBuffer">OggPackBuffer</a><a href="#VorbisInfo">VorbisInfo</a><a href="#VorbisDspState">VorbisDspState</a><a href="#VorbisBlock">VorbisBlock</a><a href="#VorbisRead">VorbisRead</a><a href="#VorbisSeek">VorbisSeek</a><a href="#VorbisClose">VorbisClose</a><a href="#VorbisTell">VorbisTell</a><a href="#VorbisCallbacks">VorbisCallbacks</a><a href="#VorbisFile">VorbisFile</a><a href="#VorbisDecode">VorbisDecode</a></aside><div class="article-body api-body">
<div class="article-grid"><aside class="page-toc"><strong>Declarations</strong><a href="#OggSyncState">OggSyncState</a><a href="#OggStreamState">OggStreamState</a><a href="#OggPackBuffer">OggPackBuffer</a><a href="#VorbisInfo">VorbisInfo</a><a href="#VorbisDspState">VorbisDspState</a><a href="#VorbisBlock">VorbisBlock</a><a href="#VorbisRead">VorbisRead</a><a href="#VorbisSeek">VorbisSeek</a><a href="#VorbisClose">VorbisClose</a><a href="#VorbisTell">VorbisTell</a><a href="#VorbisCallbacks">VorbisCallbacks</a><a href="#VorbisFile">VorbisFile</a><a href="#VorbisDecode">VorbisDecode</a><a href="#VorbisDecoder">VorbisDecoder</a><a href="#VorbisDecoderClose">VorbisDecoderClose</a><a href="#VorbisDecoderOpen">VorbisDecoderOpen</a><a href="#VorbisDecoderOpenFile">VorbisDecoderOpenFile</a><a href="#VorbisDecoderRead">VorbisDecoderRead</a><a href="#VorbisDecoderReadS16">VorbisDecoderReadS16</a><a href="#VorbisDecoderSeek">VorbisDecoderSeek</a><a href="#VorbisDecoderRewind">VorbisDecoderRewind</a><a href="#VorbisDecodeFloat">VorbisDecodeFloat</a><a href="#VorbisDecodeS16">VorbisDecodeS16</a></aside><div class="article-body api-body">
<section><p>Import with <code>#import "std/vorbis_linux"</code>.</p><div class="api-list">
<div id="OggSyncState"><code>OggSyncState :: struct { data: *u8; storage: s32; fill: s32; returned: s32; unsynced: s32; headerbytes: s32; bodybytes: s32; }</code><p>ogg_sync_state.</p></div>
<div id="OggStreamState"><code>OggStreamState :: struct { body_data: *u8; body_storage: isize; body_fill: isize; body_returned: isize; lacing_vals: *s32; granule_vals: *s64; lacing_storage: isize; lacing_fill: isize; lacing_packet: isize; lacing_returned: isize; header: [282]u8; header_fill: s32; e_o_s: s32; b_o_s: s32; serialno: isize; pageno: isize; packetno: s64; granulepos: s64; }</code><p>ogg_stream_state.</p></div>
@@ -18,6 +18,16 @@
<div id="VorbisCallbacks"><code>VorbisCallbacks :: struct { read: VorbisRead; seek: VorbisSeek; close: VorbisClose; tell: VorbisTell; }</code><p>ov_callbacks.</p></div>
<div id="VorbisFile"><code>VorbisFile :: struct { datasource: *void; seekable: s32; offset: s64; end: s64; oy: OggSyncState; links: s32; offsets: *s64; dataoffsets: *s64; serialnos: *isize; pcmlengths: *s64; vi: *VorbisInfo; vc: *void; pcm_offset: s64; ready_state: s32; current_serialno: isize; current_link: s32; bittrack: float64; samptrack: float64; os: OggStreamState; vd: VorbisDspState; vb: VorbisBlock; callbacks: VorbisCallbacks; }</code><p>OggVorbis_File.</p></div>
<div id="VorbisDecode"><code>VorbisDecode :: (input: []u8, output: *Vec(u8), max_frames: s64, audio: *VorbisAudio) -&gt; bool</code><p>Replaces OUTPUT with the decoded samples of the single Ogg Vorbis stream INPUT holds: interleaved, signed 16-bit little-endian. False, with OUTPUT empty, for anything else: an empty, damaged or truncated stream, trailing bytes, chained streams, a stream whose decoded length differs from its declared length, or one longer than MAX_FRAMES frames.</p></div>
<div id="VorbisDecoder"><code>VorbisDecoder :: struct { state: *void; info: VorbisAudio; comments: VorbisComments; position: s64; owned: Vec(u8); }</code><p>Single-owner state over borrowed input, or owned input opened from a file. Keep borrowed bytes alive and unchanged until close. No concurrent calls.</p></div>
<div id="VorbisDecoderClose"><code>VorbisDecoderClose :: (decoder: *VorbisDecoder)</code></div>
<div id="VorbisDecoderOpen"><code>VorbisDecoderOpen :: (decoder: *VorbisDecoder, input: []u8, max_frames: s64) -&gt; s32</code></div>
<div id="VorbisDecoderOpenFile"><code>VorbisDecoderOpenFile :: (decoder: *VorbisDecoder, path: string, max_frames: s64) -&gt; s32</code></div>
<div id="VorbisDecoderRead"><code>VorbisDecoderRead :: (decoder: *VorbisDecoder, output: []float32, frames: *s64) -&gt; s32</code><p>Fills whole interleaved frames; OK with zero frames denotes the logical end. Discard the output on error, then seek or close.</p></div>
<div id="VorbisDecoderReadS16"><code>VorbisDecoderReadS16 :: (decoder: *VorbisDecoder, output: []s16, frames: *s64) -&gt; s32</code></div>
<div id="VorbisDecoderSeek"><code>VorbisDecoderSeek :: (decoder: *VorbisDecoder, frame: s64) -&gt; s32</code></div>
<div id="VorbisDecoderRewind"><code>VorbisDecoderRewind :: (decoder: *VorbisDecoder) -&gt; s32</code></div>
<div id="VorbisDecodeFloat"><code>VorbisDecodeFloat :: (input: []u8, max_frames: s64, output: *PCM) -&gt; s32</code><p>Whole-file float output is unchanged on error.</p></div>
<div id="VorbisDecodeS16"><code>VorbisDecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *VorbisAudio) -&gt; s32</code></div>
</div><p><a class="text-link" href="https://github.com/ziranlang/ziran/blob/master/std/vorbis_linux.zi">Source ↗</a> · <a class="text-link" href="../modules.html#std">All modules</a></p></section>
</div></div></main>
<footer><div class="footer-top"><a class="brand" href="../index.html"><img class="brand-icon" src="../assets/logo-capybara.png" alt="" width="36" height="36"><span>Ziran</span></a><nav aria-label="Footer"><a href="../get-started.html">Get started</a><a href="../examples.html">Examples</a><a href="../targets.html">Targets</a><a href="../modules.html">Modules</a><a href="../docs.html">Docs</a><a href="../status.html">Status</a><a href="../index.html#support">Support</a><a href="https://github.com/ziranlang/ziran">GitHub ↗</a></nav></div><div class="footer-bottom"><p>A language for useful software.</p><p>© 2026 Kryon Labs · <a href="https://waozi.xyz/">Made by Waozi</a></p></div></footer></body></html>
+553
View File
@@ -0,0 +1,553 @@
// Audio mixer: voices of decoded or streamed sound, each
// with its own gain, pitch and loop, mixed into interleaved float32 stereo
// at 48 kHz, with a tap that sees every mixed block. It owns no device: a
// sink (std/audio_sink) asks it for blocks from its audio thread, and a test
// can render into a buffer of its own. Decoders join through
// AudioUseDecoder (std/audio_decode_wav, std/audio_decode_mp3); each recognizes its
// content, never a file name.
//
// A sound loads decoded whole; music decodes while it plays. A PCM stream
// plays signed 16-bit blocks the program submits and never finishes: it
// plays silence until the next block. Every call here belongs to the
// application thread; while a sink runs, each holds the sink's lock, so the
// audio thread sees a voice either before or after a change.
using Vectors :: #import "std/vec";
#import "std/file"
#import "std/byte_text_linux"
AUDIO_RATE :: 48000
AUDIO_VOICES :: 32
// Interleaved float32 frames at `rate`, from a decoder.
AudioSource :: struct {
state: *void
// Fills up to `frames` frames of OUTPUT; 0 only at the end, -1 on error.
read: AudioSourceRead
// Back to the first frame.
rewind: AudioSourceRewind
close: AudioSourceClose
// Exact PCM-frame seek when the decoder supports it; null for live PCM.
seek: AudioSourceSeek
rate: s32
channels: s32
// Every frame, or -1 when the decoder cannot say.
frames: s64
}
AudioSourceRead :: #type (state: *void, output: []float32, frames: s64) -> s64;
AudioSourceRewind :: #type (state: *void) -> bool;
AudioSourceClose :: #type (state: *void) -> void;
AudioSourceSeek :: #type (state: *void, frame: s64) -> bool;
// A decoder: whether BYTES are its format, and a source over them. The bytes
// stay valid and unchanged until the source closes.
AudioDecoderProbe :: #type (bytes: []u8) -> bool;
AudioDecoderOpen :: #type (bytes: []u8, source: *AudioSource) -> bool;
// Sees each mixed block: `frames` stereo frames, on the sink's audio thread.
AudioTap :: #type (samples: []float32, frames: s64) -> void;
AudioLockCall :: #type () -> void;
AudioVoiceState :: enum { Unloaded; Stopped; Playing; Paused; Finished; }
// A voice the program holds; a voice unloaded since is no longer valid.
AudioVoice :: struct { slot: s32; generation: u32; }
#scope_file
libc :: #system_library "c";
Allocate :: (count: usize, size: usize) -> *void #foreign libc "calloc";
Free :: (value: *void) #foreign libc "free";
Copy :: (output: *void, input: *void, count: usize) -> *void #foreign libc "memcpy";
// Source frames kept around the play position, for pitch and rate changes.
WINDOW :: 1024
DECODERS :: 8
Decoder :: struct { probe: AudioDecoderProbe; open: AudioDecoderOpen; }
Voice :: struct {
generation: u32
state: AudioVoiceState
source: AudioSource
// The compressed bytes a streamed decoder reads, owned here.
bytes: *u8
// Decoded frames at the play position: frame 0 is the one before.
window: [(WINDOW + 1) * 2]float32
window_frames: s64
phase: float64
ended: bool
looping: bool
gain: float32
pitch: float32
// Source frames decoded into the window since the start, over every loop.
decoded: s64
// A PCM stream's ring of submitted frames.
ring: *Ring
}
// Signed 16-bit blocks the program submits, as float frames.
Ring :: struct {
samples: *float32
capacity: s64
channels: s32
block: s64
start: s64
count: s64
}
voices: [AUDIO_VOICES]Voice;
decoders: [DECODERS]Decoder;
decoder_count: s32;
tap: AudioTap;
lock: AudioLockCall;
unlock: AudioLockCall;
master: float32 = 1.0;
Lock :: () { if lock != null { lock() } }
Unlock :: () { if unlock != null { unlock() } }
Find :: (voice: AudioVoice) -> *Voice {
if voice.slot < 0 || voice.slot >= AUDIO_VOICES { return null }
found := *voices[voice.slot]
if found.state == .Unloaded || found.generation != voice.generation { return null }
return found
}
// Decoded whole, for a sound.
Clip :: struct { samples: Vec(float32); channels: s32; frames: s64; at: s64; }
ClipRead :: (state: *void, output: []float32, frames: s64) -> s64 {
clip := cast(*Clip)state
count := clip.frames - clip.at
if count > frames { count = frames }
if count <= 0 { return 0 }
channels := cast(s64)clip.channels
unused Copy(cast(*void)*output[0], cast(*void)*clip.samples[clip.at * channels], cast(usize)(count * channels * 4))
clip.at += count
return count
}
ClipRewind :: (state: *void) -> bool { (cast(*Clip)state).at = 0; return true }
ClipSeek :: (state: *void, frame: s64) -> bool {
clip := cast(*Clip)state
if frame < 0 || frame > clip.frames { return false }
clip.at = frame
return true
}
ClipClose :: (state: *void) {
clip := cast(*Clip)state
VecFree(clip.samples)
Free(state)
}
// The frames submitted so far, up to FRAMES; 0 until the next block.
RingRead :: (state: *void, output: []float32, frames: s64) -> s64 {
ring := cast(*Ring)state
channels := cast(s64)ring.channels
taken := ifx ring.count < frames then ring.count else frames
for frame: 0..taken - 1 {
for channel: 0..channels - 1 {
output[frame * channels + channel] = ring.samples[((ring.start + frame) % ring.capacity) * channels + channel]
}
}
ring.start = (ring.start + taken) % ring.capacity
ring.count -= taken
return taken
}
RingRewind :: (state: *void) -> bool {
ring := cast(*Ring)state
ring.start = 0; ring.count = 0
return true
}
RingClose :: (state: *void) {
ring := cast(*Ring)state
Free(cast(*void)ring.samples)
Free(state)
}
// Takes a free slot for SOURCE, or -1 when every voice is in use.
Install :: (source: AudioSource, bytes: *u8, ring: *Ring) -> AudioVoice {
Lock()
defer Unlock()
for slot: cast(s32)0..AUDIO_VOICES - 1 {
voice := *voices[slot]
if voice.state != .Unloaded { continue }
generation := voice.generation + 1
voice.* = .{}
voice.generation = generation
voice.state = .Stopped
voice.source = source
voice.bytes = bytes
voice.ring = ring
voice.gain = 1.0
voice.pitch = 1.0
return .{slot, generation}
}
return .{-1, 0}
}
Reset :: (voice: *Voice) {
voice.window_frames = 0
voice.phase = 0.0
voice.decoded = 0
voice.ended = false
}
// Keeps the last frame as frame 0 and decodes what follows it. A PCM stream
// takes what has been submitted and waits for more; a loop starts over.
Refill :: (voice: *Voice) -> bool {
channels := cast(s64)voice.source.channels
keep: s64 = 0
if voice.window_frames > 0 {
last := voice.window_frames - 1
for channel: 0..channels - 1 { voice.window[channel] = voice.window[last * channels + channel] }
voice.phase -= cast(float64)last
keep = 1
}
voice.window_frames = keep
rewinds := 0
while voice.window_frames <= WINDOW && !voice.ended {
room := WINDOW + 1 - voice.window_frames
start := voice.window_frames * channels
made := voice.source.read(voice.source.state, voice.window[start:start + room * channels], room)
if made < 0 { voice.ended = true; break }
if made == 0 {
if voice.ring != null { break }
// A source that is empty from its start ends even when looping.
if voice.looping && rewinds == 0 && voice.source.rewind(voice.source.state) {
rewinds += 1
continue
}
// Silence after the last frame, so the last frame plays too.
for channel: 0..channels - 1 { voice.window[start + channel] = 0.0 }
voice.window_frames += 1
voice.decoded += 1
voice.ended = true
break
}
rewinds = 0
voice.window_frames += made
voice.decoded += made
if voice.ring != null && made < room { break }
}
return voice.window_frames > keep
}
Mix :: (voice: *Voice, output: []float32, frames: s64) {
channels := cast(s64)voice.source.channels
step := cast(float64)voice.source.rate / cast(float64)AUDIO_RATE * cast(float64)voice.pitch
gain := voice.gain * master
right := ifx channels > 1 then cast(s64)1 else cast(s64)0
for frame: 0..frames - 1 {
index := cast(s64)voice.phase
while index + 1 >= voice.window_frames {
if !voice.ended && Refill(voice) {
index = cast(s64)voice.phase
continue
}
// A stream waits in silence; anything else has played out.
if voice.ring == null { voice.state = .Finished }
return
}
t := cast(float32)(voice.phase - cast(float64)index)
at := index * channels
next := (index + 1) * channels
left_sample := voice.window[at] + (voice.window[next] - voice.window[at]) * t
right_sample := voice.window[at + right] + (voice.window[next + right] - voice.window[at + right]) * t
output[frame * 2] += left_sample * gain
output[frame * 2 + 1] += right_sample * gain
voice.phase += step
}
}
// The play position in seconds: what was decoded less what waits in the
// window, within the current loop.
Seconds :: (voice: *Voice) -> float64 {
if voice.source.rate <= 0 { return 0.0 }
played := cast(float64)(voice.decoded - voice.window_frames) + voice.phase
if played < 0.0 { played = 0.0 }
frames := cast(float64)voice.source.frames
if voice.looping && frames > 0.0 {
while played >= frames { played -= frames }
}
return played / cast(float64)voice.source.rate
}
#scope_export
// A source over frames decoded whole, which it takes from SAMPLES.
AudioDecodedSource :: (samples: *Vec(float32), rate: s32, channels: s32, source: *AudioSource) -> bool {
if rate <= 0 || channels < 1 || channels > 2 { return false }
clip := cast(*Clip)Allocate(1, size_of(Clip))
if clip == null { return false }
VecSwap(clip.samples, <<samples)
clip.channels = channels
clip.frames = clip.samples.count / cast(s64)channels
source.* = .{.state = cast(*void)clip, .read = ClipRead, .rewind = ClipRewind,
.close = ClipClose, .seek = ClipSeek, .rate = rate, .channels = channels, .frames = clip.frames}
return true
}
// A decoder module registers itself from its initializer.
AudioUseDecoder :: (probe: AudioDecoderProbe, open: AudioDecoderOpen) -> bool {
if decoder_count >= DECODERS { return false }
decoders[decoder_count] = .{probe, open}
decoder_count += 1
return true
}
// The sink's lock around changes the audio thread could see.
AudioUseLock :: (enter: AudioLockCall, leave: AudioLockCall) {
if lock == enter && unlock == leave { return }
lock = enter
unlock = leave
}
AudioUseTap :: (next: AudioTap) {
Lock()
tap = next
Unlock()
}
AudioSetMasterGain :: (gain: float32) {
if !(gain >= 0.0) { return }
Lock()
master = gain
Unlock()
}
// Mixes FRAMES stereo frames of every playing voice into OUTPUT, replacing
// what it held, then shows them to the tap. The sink's audio thread calls
// this; a test can call it directly.
AudioRender :: (output: []float32, frames: s64) {
if frames < 0 || frames > output.count / 2 { return }
for index: 0..frames * 2 - 1 { output[index] = 0.0 }
for slot: 0..AUDIO_VOICES - 1 {
if voices[slot].state == .Playing { Mix(*voices[slot], output, frames) }
}
for index: 0..frames * 2 - 1 {
if output[index] > 1.0 { output[index] = 1.0 }
if output[index] < -1.0 { output[index] = -1.0 }
}
if tap != null { tap(output[0:frames * 2], frames) }
}
// A voice of BYTES in the first registered format that recognizes them:
// decoded whole now, or, for music (`stream`), while it plays. The bytes
// are copied; slot -1 when no decoder knows them or every voice is in use.
AudioLoad :: (bytes: string, stream: bool) -> AudioVoice {
failed := AudioVoice.{-1, 0}
if bytes.count == 0 { return failed }
view := BytesFromPointer((cast(*TextDescriptor)(*bytes)).data, cast(u64)bytes.count)
chosen: s32 = -1
for index: 0..decoder_count - 1 {
if decoders[index].probe(view) { chosen = cast(s32)index; break }
}
if chosen < 0 { return failed }
owned := cast(*u8)Allocate(cast(usize)bytes.count, 1)
if owned == null { return failed }
unused Copy(cast(*void)owned, cast(*void)*view[0], cast(usize)bytes.count)
source: AudioSource
if !decoders[chosen].open(BytesFromPointer(owned, cast(u64)bytes.count), *source) ||
source.channels < 1 || source.channels > 2 || source.rate <= 0 {
if source.close != null { source.close(source.state) }
Free(cast(*void)owned)
return failed
}
if !stream {
// A sound decodes whole here, on the program's thread.
samples: Vec(float32)
block: [WINDOW * 2]float32
channels := cast(s64)source.channels
made: s64 = 1
while made > 0 {
made = source.read(source.state, block[0:WINDOW * channels], WINDOW)
for index: 0..made * channels - 1 { VecPush(samples, block[index]) }
}
rate := source.rate
source.close(source.state)
Free(cast(*void)owned)
owned = null
if made < 0 || !AudioDecodedSource(*samples, rate, cast(s32)channels, *source) {
VecFree(samples)
return failed
}
}
voice := Install(source, owned, null)
if voice.slot < 0 {
source.close(source.state)
if owned != null { Free(cast(*void)owned) }
}
return voice
}
AudioLoadFile :: (path: string, stream: bool) -> AudioVoice {
bytes: Vec(u8)
defer VecFree(bytes)
if !ReadFileInto(path, *bytes) { return .{-1, 0} }
return AudioLoad(TextView(bytes[:]), stream)
}
// A stream of signed 16-bit blocks of FRAMES frames each, at RATE.
AudioOpenStream :: (rate: s32, channels: s32, frames: s32) -> AudioVoice {
failed := AudioVoice.{-1, 0}
if rate < 8000 || rate > 192000 || channels < 1 || channels > 2 || frames < 64 || frames > 65536 { return failed }
ring := cast(*Ring)Allocate(1, size_of(Ring))
if ring == null { return failed }
ring.channels = channels
ring.block = frames
ring.capacity = cast(s64)frames * 4
ring.samples = cast(*float32)Allocate(cast(usize)(ring.capacity * cast(s64)channels), 4)
if ring.samples == null { Free(cast(*void)ring); return failed }
source := AudioSource.{.state = cast(*void)ring, .read = RingRead, .rewind = RingRewind,
.close = RingClose, .rate = rate, .channels = channels, .frames = -1}
voice := Install(source, null, ring)
if voice.slot < 0 { RingClose(cast(*void)ring) }
return voice
}
// Room for another whole block.
AudioStreamWritable :: (voice: AudioVoice) -> bool {
Lock()
defer Unlock()
found := Find(voice)
return found != null && found.ring != null && found.ring.capacity - found.ring.count >= found.ring.block
}
// Copies one whole block of interleaved samples; false when it is not
// exactly one block or there is no room.
AudioStreamSubmit :: (voice: AudioVoice, samples: []s16) -> bool {
Lock()
defer Unlock()
found := Find(voice)
if found == null || found.ring == null { return false }
ring := found.ring
channels := cast(s64)ring.channels
if samples.count != ring.block * channels || ring.capacity - ring.count < ring.block { return false }
for frame: 0..ring.block - 1 {
at := ((ring.start + ring.count + frame) % ring.capacity) * channels
for channel: 0..channels - 1 {
ring.samples[at + channel] = cast(float32)samples[frame * channels + channel] / 32768.0
}
}
ring.count += ring.block
return true
}
// From the start.
AudioPlay :: (voice: AudioVoice) -> bool {
Lock()
defer Unlock()
found := Find(voice)
if found == null || !found.source.rewind(found.source.state) { return false }
Reset(found)
found.state = .Playing
return true
}
AudioStop :: (voice: AudioVoice) {
Lock()
defer Unlock()
found := Find(voice)
if found == null { return }
found.state = .Stopped
Reset(found)
}
AudioPause :: (voice: AudioVoice) {
Lock()
defer Unlock()
found := Find(voice)
if found != null && found.state == .Playing { found.state = .Paused }
}
AudioResume :: (voice: AudioVoice) {
Lock()
defer Unlock()
found := Find(voice)
if found != null && found.state == .Paused { found.state = .Playing }
}
AudioState :: (voice: AudioVoice) -> AudioVoiceState {
Lock()
defer Unlock()
found := Find(voice)
if found == null { return .Unloaded }
return found.state
}
AudioPlaying :: (voice: AudioVoice) -> bool { return AudioState(voice) == .Playing }
// 0 is silent, 1 as decoded.
AudioSetGain :: (voice: AudioVoice, gain: float32) {
if !(gain >= 0.0) { return }
Lock()
defer Unlock()
found := Find(voice)
if found != null { found.gain = gain }
}
// Speed and pitch together: 2 plays an octave up in half the time.
AudioSetPitch :: (voice: AudioVoice, pitch: float32) {
if !(pitch > 0.0) || pitch > 16.0 { return }
Lock()
defer Unlock()
found := Find(voice)
if found != null { found.pitch = pitch }
}
AudioSetLooping :: (voice: AudioVoice, looping: bool) {
Lock()
defer Unlock()
found := Find(voice)
if found != null { found.looping = looping }
}
// Seeks to seconds within a seekable source. Playing/paused/stopped states
// are preserved; a finished voice becomes paused, ready to resume there.
// Live PCM streams and unsupported decoder sources return false unchanged.
AudioSeek :: (voice: AudioVoice, seconds: float64) -> bool {
if !(seconds >= 0.0) { return false }
Lock()
defer Unlock()
found := Find(voice)
if found == null || found.source.seek == null || seconds > 9223372036854774784.0 / cast(float64)found.source.rate { return false }
target := seconds * cast(float64)found.source.rate
if found.source.frames >= 0 && target > cast(float64)found.source.frames { return false }
frame := cast(s64)target
if !found.source.seek(found.source.state, frame) { return false }
Reset(found)
found.decoded = frame
if found.state == .Finished { found.state = .Paused }
return true
}
// Seconds played since the start, or since the loop began again.
AudioPosition :: (voice: AudioVoice) -> float64 {
Lock()
defer Unlock()
found := Find(voice)
if found == null { return 0.0 }
return Seconds(found)
}
// Seconds of the whole sound, or -1 when its decoder cannot say.
AudioLength :: (voice: AudioVoice) -> float64 {
Lock()
defer Unlock()
found := Find(voice)
if found == null || found.source.frames < 0 { return -1.0 }
return cast(float64)found.source.frames / cast(float64)found.source.rate
}
AudioUnload :: (voice: AudioVoice) {
Lock()
found := Find(voice)
if found == null { Unlock(); return }
source := found.source
bytes := found.bytes
generation := found.generation
found.* = .{}
found.generation = generation
Unlock()
if source.close != null { source.close(source.state) }
if bytes != null { Free(cast(*void)bytes) }
}
+103
View File
@@ -0,0 +1,103 @@
// AAudio is loaded at runtime so an API-21 app still loads on API 21-25.
// All entry points below were introduced in API 26. No AAudio link is needed.
Buffer :: #import "std/audio_android_buffer";
#scope_file
Create :: #type (**void) -> s32 #c_call;
Dispose :: #type (*void) -> s32 #c_call;
SetInt :: #type (*void, s32) -> void #c_call;
DataCallback :: #type (*void, *void, *void, s32) -> s32 #c_call;
ErrorCallback :: #type (*void, *void, s32) -> void #c_call;
SetData :: #type (builder: *void, callback: *void, argument: *void) -> void #c_call;
SetError :: #type (builder: *void, callback: *void, argument: *void) -> void #c_call;
OpenStream :: #type (*void, **void) -> s32 #c_call;
GetInt :: #type (*void) -> s32 #c_call;
create: Create;
delete: Dispose;
set_rate: SetInt;
set_channels: SetInt;
set_format: SetInt;
set_direction: SetInt;
set_data: SetData;
set_error: SetError;
open_stream: OpenStream;
start: Dispose;
stop: Dispose;
close: Dispose;
get_rate: GetInt;
get_channels: GetInt;
get_format: GetInt;
library: *void;
stream: *void;
failed: bool;
Resolve :: () -> bool {
return Buffer.Resolve(library, cast(*void)*create, "AAudio_createStreamBuilder") &&
Buffer.Resolve(library, cast(*void)*delete, "AAudioStreamBuilder_delete") &&
Buffer.Resolve(library, cast(*void)*set_rate, "AAudioStreamBuilder_setSampleRate") &&
Buffer.Resolve(library, cast(*void)*set_channels, "AAudioStreamBuilder_setChannelCount") &&
Buffer.Resolve(library, cast(*void)*set_format, "AAudioStreamBuilder_setFormat") &&
Buffer.Resolve(library, cast(*void)*set_direction, "AAudioStreamBuilder_setDirection") &&
Buffer.Resolve(library, cast(*void)*set_data, "AAudioStreamBuilder_setDataCallback") &&
Buffer.Resolve(library, cast(*void)*set_error, "AAudioStreamBuilder_setErrorCallback") &&
Buffer.Resolve(library, cast(*void)*open_stream, "AAudioStreamBuilder_openStream") &&
Buffer.Resolve(library, cast(*void)*start, "AAudioStream_requestStart") &&
Buffer.Resolve(library, cast(*void)*stop, "AAudioStream_requestStop") &&
Buffer.Resolve(library, cast(*void)*close, "AAudioStream_close") &&
Buffer.Resolve(library, cast(*void)*get_rate, "AAudioStream_getSampleRate") &&
Buffer.Resolve(library, cast(*void)*get_channels, "AAudioStream_getChannelCount") &&
Buffer.Resolve(library, cast(*void)*get_format, "AAudioStream_getFormat")
}
Pull :: (device: *void, argument: *void, output: *void, frames: s32) -> s32 {
unused device; unused argument
Buffer.RenderFloat(output, frames)
return 0 // AAUDIO_CALLBACK_RESULT_CONTINUE
}
Error :: (device: *void, argument: *void, code: s32) {
unused device; unused argument; unused code
// Never stop/close on AAudio's callback thread. The next UI-thread open
// recovers the device; mixer voices and queued PCM survive it.
Buffer.Enter(); failed = true; Buffer.Leave()
}
#scope_export
Available :: () -> bool {
if library == null { library = Buffer.Library("libaaudio.so") }
return library != null
}
Ready :: () -> bool {
Buffer.Enter()
ready := stream != null && !failed
Buffer.Leave()
return ready
}
Close :: () {
if stream == null { return }
// close joins the callback; do not hold the mixer's mutex while joining.
unused stop(stream)
unused close(stream)
stream = null
}
Open :: () -> bool {
if Ready() { return true }
Close()
if !Available() || !Resolve() { return false }
builder: *void
if create(*builder) != 0 || builder == null { return false }
defer delete(builder)
set_rate(builder, 48000)
set_channels(builder, 2)
set_format(builder, 2) // AAUDIO_FORMAT_PCM_FLOAT
set_direction(builder, 0) // AAUDIO_DIRECTION_OUTPUT
pull: DataCallback = Pull
set_data(builder, (cast(**void)*pull)[0], null)
error: ErrorCallback = Error
set_error(builder, (cast(**void)*error)[0], null)
if open_stream(builder, *stream) != 0 || stream == null { stream = null; return false }
if get_rate(stream) != 48000 || get_channels(stream) != 2 || get_format(stream) != 2 {
Close(); return false
}
Buffer.Enter(); failed = false; Buffer.Leave()
if start(stream) != 0 { Close(); return false }
return Ready()
}
+63
View File
@@ -0,0 +1,63 @@
// Shared Android mixer boundary. Bionic pthread_mutex_t fits this aligned
// storage on all Android ABIs; its static zero initializer is PTHREAD_MUTEX_INITIALIZER.
// The lock outlives devices, so voices remain safe after close and reopen.
Mixer :: #import "std/audio";
#import "std/byte_text_linux"
#import "std/c_string"
#scope_file
c :: #system_library "c";
dl :: #system_library "dl";
Lock :: (mutex: *void) -> s32 #foreign c "pthread_mutex_lock";
Unlock :: (mutex: *void) -> s32 #foreign c "pthread_mutex_unlock";
Copy :: (output: *void, input: *void, count: usize) -> *void #foreign c "memcpy";
Load :: (name: *u8, flags: s32) -> *void #foreign dl "dlopen";
Symbol :: (library: *void, name: *u8) -> *void #foreign dl "dlsym";
mutex: [8]u64;
#scope_export
Enter :: () { unused Lock(cast(*void)*mutex[0]) }
Leave :: () { unused Unlock(cast(*void)*mutex[0]) }
Install :: () { Mixer.AudioUseLock(Enter, Leave) }
Library :: (name: string) -> *void {
text: [64]u8
if !CopyCString(name, text[:]) { return null }
return Load(*text[0], 2) // RTLD_NOW, local symbols
}
Resolve :: (library: *void, slot: *void, name: string) -> bool {
text: [96]u8
if !CopyCString(name, text[:]) { return false }
symbol := Symbol(library, *text[0])
if symbol == null { return false }
unused Copy(slot, cast(*void)*symbol, size_of(*void))
return true
}
RenderFloat :: (output: *void, frames: s32) {
if output == null || frames <= 0 { return }
samples: []float32
view := cast(*ByteDescriptor)(*samples)
view.data = cast(*u8)output
view.length = cast(s64)frames * 2
Enter()
Mixer.AudioRender(samples, cast(s64)frames)
Leave()
}
// OpenSL ES on API 21 accepts signed 16-bit PCM. Convert the mixer's clipped
// stereo float output without allocating or retaining a caller's buffer.
RenderPCM :: (output: []s16, frames: s32) {
mixed: [1024]float32
at: s32
while at < frames {
count := frames - at
if count > 512 { count = 512 }
RenderFloat(cast(*void)*mixed[0], count)
for index: 0..cast(s64)count * 2 - 1 {
value := mixed[index]
output[cast(s64)at * 2 + index] = ifx value <= -1.0 then cast(s16)-32768 else cast(s16)(value * 32767.0)
}
at += count
}
}
+131
View File
@@ -0,0 +1,131 @@
// API-21 PCM output. Android's simple buffer queue owns two alternating
// signed-16 stereo blocks. Only the completed block is refilled.
Buffer :: #import "std/audio_android_buffer";
#scope_file
Realize :: #type (**Object, u32) -> u32 #c_call;
GetInterface :: #type (**Object, *void, *void) -> u32 #c_call;
Destroy :: #type (**Object) -> void #c_call;
CreatePlayer :: #type (**Engine, ***Object, *Data, *Data, u32, **void, *u32) -> u32 #c_call;
CreateMix :: #type (**Engine, ***Object, u32, **void, *u32) -> u32 #c_call;
SetState :: #type (**Play, u32) -> u32 #c_call;
Enqueue :: #type (**Queue, *void, u32) -> u32 #c_call;
Clear :: #type (**Queue) -> u32 #c_call;
SetCallback :: #type (queue: **Queue, callback: *void, argument: *void) -> u32 #c_call;
Object :: struct {
realize: Realize
resume: *void
state: *void
interface: GetInterface
callback: *void
abort: *void
destroy: Destroy
}
Engine :: struct {
led: *void
vibra: *void
player: CreatePlayer
recorder: *void
midi: *void
listener: *void
group: *void
mix: CreateMix
}
Play :: struct { state: SetState }
Callback :: #type (**Queue, *void) -> void #c_call;
Queue :: struct {
enqueue: Enqueue
clear: Clear
state: *void
callback: SetCallback
}
Data :: struct { locator: *void; format: *void }
QueueLocator :: struct { kind: u32; count: u32 }
MixLocator :: struct { kind: u32; output: **Object }
PCM :: struct { kind: u32; channels: u32; rate: u32; bits: u32; container: u32; mask: u32; endian: u32 }
Create :: #type (***Object, u32, *void, u32, **void, *u32) -> u32 #c_call;
create: Create;
engine_id: *void;
queue_id: *void;
play_id: *void;
library: *void;
engine_object: **Object;
output_object: **Object;
player_object: **Object;
queue: **Queue;
play: **Play;
blocks: [2048]s16;
next: s64;
running: bool;
// Interface IDs are exported pointer variables, not the address of the UUID.
Load :: () -> bool {
if library == null { library = Buffer.Library("libOpenSLES.so") }
if library == null { return false }
return Buffer.Resolve(library, cast(*void)*create, "slCreateEngine") &&
Buffer.Resolve(library, cast(*void)*engine_id, "SL_IID_ENGINE") &&
Buffer.Resolve(library, cast(*void)*queue_id, "SL_IID_ANDROIDSIMPLEBUFFERQUEUE") &&
Buffer.Resolve(library, cast(*void)*play_id, "SL_IID_PLAY")
}
Fill :: (target: **Queue, argument: *void) {
unused argument
Buffer.Enter()
active := running
Buffer.Leave()
if !active { return }
offset := next * 1024
Buffer.RenderPCM(blocks[offset:offset + 1024], 512)
result := target[0].enqueue(target, cast(*void)*blocks[offset], 2048)
next = 1 - next
if result != 0 { Buffer.Enter(); running = false; Buffer.Leave() }
}
#scope_export
Ready :: () -> bool {
Buffer.Enter(); ready := running; Buffer.Leave()
return ready
}
Close :: () {
Buffer.Enter(); running = false; Buffer.Leave()
// Do not hold the mixer lock while stopping/joining native callbacks.
if play != null { unused play[0].state(play, 1) }
if player_object != null { player_object[0].destroy(player_object) }
queue = null; play = null; player_object = null
if output_object != null { output_object[0].destroy(output_object); output_object = null }
if engine_object != null { engine_object[0].destroy(engine_object); engine_object = null }
}
Open :: () -> bool {
if Ready() { return true }
Close()
if !Load() { return false }
// Resolve copies a function address. For interface IDs it copied the
// address of the exported variable, so dereference that address once.
engine_iid := (cast(**void)engine_id)[0]
queue_iid := (cast(**void)queue_id)[0]
play_iid := (cast(**void)play_id)[0]
if create(*engine_object, 0, null, 0, null, null) != 0 { Close(); return false }
if engine_object[0].realize(engine_object, 0) != 0 { Close(); return false }
engine: **Engine
if engine_object[0].interface(engine_object, engine_iid, cast(*void)*engine) != 0 { Close(); return false }
if engine[0].mix(engine, *output_object, 0, null, null) != 0 { Close(); return false }
if output_object[0].realize(output_object, 0) != 0 { Close(); return false }
locator := QueueLocator.{cast(u32)0x800007BD, 2}
format := PCM.{2, 2, 48000000, 16, 16, 3, 2}
output := MixLocator.{4, output_object}
source := Data.{cast(*void)*locator, cast(*void)*format}
sink := Data.{cast(*void)*output, null}
required: u32 = 1
if engine[0].player(engine, *player_object, *source, *sink, 1, *queue_iid, *required) != 0 { Close(); return false }
if player_object[0].realize(player_object, 0) != 0 { Close(); return false }
if player_object[0].interface(player_object, play_iid, cast(*void)*play) != 0 ||
player_object[0].interface(player_object, queue_iid, cast(*void)*queue) != 0 { Close(); return false }
callback: Callback = Fill
if queue[0].callback(queue, (cast(**void)*callback)[0], null) != 0 { Close(); return false }
next = 0
Buffer.Enter(); running = true; Buffer.Leave()
Fill(queue, null)
Fill(queue, null)
if !Ready() || play[0].state(play, 3) != 0 { Close(); return false }
return true
}
+58
View File
@@ -0,0 +1,58 @@
// MPEG audio for std/audio: MP3 (MPEG-1, 2 and 2.5 Layer III) and Layers
// I and II, decoded as it plays by std/audio_mp3 over dr_mp3 at the stream's own
// rate. Importing this module is what adds the format; native programs link
// audio's libziran_mp3.a (make's $(MP3_A)) and -lm.
Mixer :: #import "std/audio";
Mp3 :: #import "std/audio_mp3";
Mpeg :: #import "std/audio_mpeg";
Types :: #import "std/audio_types";
#scope_file
libc :: #system_library "c";
Allocate :: (count: usize, size: usize) -> *void #foreign libc "calloc";
Free :: (value: *void) #foreign libc "free";
State :: struct { decoder: Mp3.Mp3Decoder; }
// Every frame of the stream checks out, tags aside.
Probe :: (bytes: []u8) -> bool {
info: Mpeg.Mp3Info
return Mpeg.Mp3Inspect(bytes, *info) == Types.OK
}
Read :: (argument: *void, output: []float32, frames: s64) -> s64 {
state := cast(*State)argument
made: s64
channels := cast(s64)state.decoder.info.channels
if Mp3.Mp3DecoderRead(*state.decoder, output[0:frames * channels], *made) != Types.OK { return -1 }
return made
}
Rewind :: (argument: *void) -> bool {
return Mp3.Mp3DecoderRewind(*(cast(*State)argument).decoder) == Types.OK
}
Seek :: (argument: *void, frame: s64) -> bool {
return Mp3.Mp3DecoderSeek(*(cast(*State)argument).decoder, frame) == Types.OK
}
Close :: (argument: *void) {
state := cast(*State)argument
Mp3.Mp3DecoderClose(*state.decoder)
Free(argument)
}
Open :: (bytes: []u8, source: *Mixer.AudioSource) -> bool {
state := cast(*State)Allocate(1, size_of(State))
if state == null { return false }
if Mp3.Mp3DecoderOpen(*state.decoder, bytes, Mpeg.Mp3MaxStreamFrames) != Types.OK {
Free(cast(*void)state)
return false
}
info := state.decoder.info
source.* = .{.state = cast(*void)state, .read = Read, .rewind = Rewind, .close = Close, .seek = Seek,
.rate = info.rate, .channels = info.channels, .frames = info.frames}
return true
}
registered: bool = Mixer.AudioUseDecoder(Probe, Open);
+52
View File
@@ -0,0 +1,52 @@
// Register the existing guarded libvorbisfile decoder with std/audio.
Mixer :: #import "std/audio";
Vorbis :: #import "std/vorbis_linux";
OggVorbis :: #import "std/vorbis";
#scope_file
libc :: #system_library "c";
Allocate :: (count: usize, size: usize) -> *void #foreign libc "calloc";
Free :: (value: *void) #foreign libc "free";
State :: struct { decoder: Vorbis.VorbisDecoder; }
// The first Ogg page holds the Vorbis identification header; opening
// validates the whole stream.
Probe :: (bytes: []u8) -> bool {
return OggVorbis.VorbisRecognizes(bytes)
}
Read :: (argument: *void, output: []float32, frames: s64) -> s64 {
state := cast(*State)argument
channels := cast(s64)state.decoder.info.channels
got: s64
if Vorbis.VorbisDecoderRead(*state.decoder, output[0:frames * channels], *got) != 0 { return -1 }
return got
}
Rewind :: (argument: *void) -> bool {
return Vorbis.VorbisDecoderSeek(*(cast(*State)argument).decoder, 0) == 0
}
Seek :: (argument: *void, frame: s64) -> bool {
return Vorbis.VorbisDecoderSeek(*(cast(*State)argument).decoder, frame) == 0
}
Close :: (argument: *void) {
state := cast(*State)argument
Vorbis.VorbisDecoderClose(*state.decoder)
Free(argument)
}
Open :: (bytes: []u8, source: *Mixer.AudioSource) -> bool {
state := cast(*State)Allocate(1, size_of(State))
if state == null { return false }
if Vorbis.VorbisDecoderOpen(*state.decoder, bytes, 4147200000) != 0 {
Free(cast(*void)state)
return false
}
info := state.decoder.info
source.* = .{.state = cast(*void)state, .read = Read, .rewind = Rewind, .close = Close, .seek = Seek,
.rate = info.rate, .channels = info.channels, .frames = info.frames}
return true
}
registered: bool = Mixer.AudioUseDecoder(Probe, Open);
+21
View File
@@ -0,0 +1,21 @@
// RIFF WAVE for std/audio, PCM16 or float32, decoded whole by std/audio_wav.
// Importing this module is what adds the format.
Mixer :: #import "std/audio";
Wav :: #import "std/audio_wav";
Types :: #import "std/audio_types";
using Vectors :: #import "std/vec";
#scope_file
Probe :: (bytes: []u8) -> bool {
return bytes.count >= 12 && TextView(bytes[0:4]) == "RIFF" && TextView(bytes[8:12]) == "WAVE"
}
Open :: (bytes: []u8, source: *Mixer.AudioSource) -> bool {
pcm: Types.PCM
if Wav.WavDecode(bytes, Types.MaxFrames, *pcm) != Types.OK { VecFree(pcm.samples); return false }
if Mixer.AudioDecodedSource(*pcm.samples, pcm.rate, pcm.channels, source) { return true }
VecFree(pcm.samples)
return false
}
registered: bool = Mixer.AudioUseDecoder(Probe, Open);
+53
View File
@@ -0,0 +1,53 @@
// Caller-owned asynchronous device open. Only the application thread touches
// this record; the worker publishes its result through ThreadFinished.
#import "std/thread"
#import "std/timer"
OpenCall :: #type () -> bool;
CloseCall :: #type () -> void;
Device :: struct {
worker: Thread
open: OpenCall
close: CloseCall
result: bool
ready: bool
attempted: bool
retry_at: s64
}
#scope_file
Run :: (argument: *void) {
device := cast(*Device)argument
device.result = device.open()
}
#scope_export
Poll :: (device: *Device) {
if ThreadFinished(*device.worker) {
device.ready = device.result
if !device.ready { device.retry_at = MonotonicMilliseconds() + 1000 }
}
}
Pending :: (device: *Device) -> bool { Poll(device); return ThreadRunning(*device.worker) }
Unavailable :: (device: *Device) -> bool {
Poll(device)
return device.attempted && !device.ready && !ThreadRunning(*device.worker)
}
Ready :: (device: *Device) -> bool { Poll(device); return device.ready }
Open :: (device: *Device, open: OpenCall, close: CloseCall) -> bool {
Poll(device)
if device.ready { return true }
if ThreadRunning(*device.worker) || device.attempted && MonotonicMilliseconds() < device.retry_at { return false }
device.open = open; device.close = close
device.attempted = true; device.result = false
run: ThreadProcedure = Run
if !ThreadStart(*device.worker, run, cast(*void)device) { device.retry_at = MonotonicMilliseconds() + 1000 }
return false
}
Close :: (device: *Device) {
// Teardown is explicit and may join an in-flight open or callback. Open
// and readiness queries never wait for hardware, a backend or a join.
ThreadWait(*device.worker)
if device.close != null { device.close() }
device.ready = false; device.result = false; device.attempted = false; device.retry_at = 0
}
// A backend's disconnect callback made a previously opened device unusable.
Invalidate :: (device: *Device) { device.ready = false; device.attempted = false }
+150
View File
@@ -0,0 +1,150 @@
// MP3 decoding: MPEG-1, MPEG-2 and MPEG-2.5, Layers I, II and III, mono and
// stereo, through dr_mp3 (the pinned `dr_libs` source dependency, compiled by
// native/ziran_mp3.c into libziran_mp3.a). Native C only: link
// `libziran_mp3.a -lm`. std/audio_mpeg validates every frame first, so
// dr_mp3 only sees a complete frame stream with its tags removed.
#import "std/audio_types"
#import "std/vec"
#import "std/file"
#import "std/audio_mpeg"
#scope_file
mp3 :: #system_library "ziran_mp3";
NativeOpen :: (data: *u8, size: usize, seek_points: u32) -> *void #foreign mp3 "ziran_mp3_open";
NativeClose :: (state: *void) #foreign mp3 "ziran_mp3_close";
NativeReadFloat :: (state: *void, frames: u64, output: *float32) -> u64 #foreign mp3 "drmp3_read_pcm_frames_f32";
NativeSeek :: (state: *void, frame: u64) -> u32 #foreign mp3 "drmp3_seek_to_pcm_frame";
// Frames the next read requests: the caller's whole frames, capped at the
// logical end; -1 rejects a closed decoder or a partial-frame buffer.
Wanted :: (decoder: *Mp3Decoder, samples: s64) -> s64 {
if decoder.handle == null || samples <= 0 || samples % decoder.info.channels != 0 { return -1 }
wanted := samples / decoder.info.channels
left := decoder.info.frames - decoder.position
return ifx wanted < left then wanted else left
}
// The decoder ending before the declared frame count is truncated or
// corrupt audio; the caller discards that read.
Advance :: (decoder: *Mp3Decoder, wanted: s64, got: u64, frames: *s64) -> s32 {
if got != cast(u64)wanted { return Malformed }
decoder.position += wanted; <<frames = wanted
return OK
}
#scope_export
// Single-owner native state over borrowed bytes (or bytes it read itself
// with Mp3DecoderOpenFile). Do not copy a live decoder or call it
// concurrently; keep borrowed input alive and unchanged until close.
Mp3Decoder :: struct {
handle: *void
info: Mp3Info
position: s64 // next PCM frame a read returns
owned: Vec(u8)
}
Mp3DecoderClose :: (decoder: *Mp3Decoder) {
if decoder.handle != null { NativeClose(decoder.handle) }
decoder.handle = null; decoder.info = Mp3Info.{}; decoder.position = 0
VecFree(decoder.owned)
}
// Inspects INPUT, then opens dr_mp3 over its frames with a seek table of
// about one point per second. MAX_FRAMES bounds the declared duration.
Mp3DecoderOpen :: (decoder: *Mp3Decoder, input: []u8, max_frames: s64) -> s32 {
if decoder.handle != null || max_frames <= 0 || max_frames > Mp3MaxStreamFrames { return Invalid }
metadata: Mp3Info
code := Mp3Inspect(input, *metadata)
if code != OK { return code }
if metadata.frames > max_frames { return LimitExceeded }
points := metadata.frames / metadata.rate + 1
if points > 16384 { points = 16384 }
audio := input[metadata.audio_at:metadata.audio_end]
handle := NativeOpen(*audio[0], cast(usize)audio.count, cast(u32)points)
if handle == null { return Malformed }
decoder.handle = handle; decoder.info = metadata; decoder.position = 0
return OK
}
// Reads the whole file (at most MaxBytes) into the decoder, which then owns
// it until Mp3DecoderClose.
Mp3DecoderOpenFile :: (decoder: *Mp3Decoder, path: string, max_frames: s64) -> s32 {
if decoder.handle != null || max_frames <= 0 || max_frames > Mp3MaxStreamFrames { return Invalid }
VecFree(decoder.owned)
if !ReadFileInto(path, *decoder.owned) { VecFree(decoder.owned); return IOFailure }
if decoder.owned.count > MaxBytes { VecFree(decoder.owned); return LimitExceeded }
code := Mp3DecoderOpen(decoder, VecSlice(decoder.owned, 0, decoder.owned.count), max_frames)
if code != OK { VecFree(decoder.owned) }
return code
}
// Fills interleaved float frames. OK with zero frames is the logical end.
// An error may leave a filled prefix: discard it, then rewind or close.
Mp3DecoderRead :: (decoder: *Mp3Decoder, output: []float32, frames: *s64) -> s32 {
<<frames = 0
wanted := Wanted(decoder, output.count)
if wanted < 0 { return Invalid }
if wanted == 0 { return OK }
return Advance(decoder, wanted, NativeReadFloat(decoder.handle, cast(u64)wanted, *output[0]), frames)
}
// The same stream as interleaved PCM16: the float samples converted with
// Pcm16, so they equal the WAV output of the same decode.
Mp3DecoderReadS16 :: (decoder: *Mp3Decoder, output: []s16, frames: *s64) -> s32 {
<<frames = 0
wanted := Wanted(decoder, output.count)
if wanted < 0 { return Invalid }
channels := cast(s64)decoder.info.channels
scratch: [2304]float32
done: s64
while done < wanted {
count := wanted - done
if count > 1152 { count = 1152 }
got: s64
code := Advance(decoder, count, NativeReadFloat(decoder.handle, cast(u64)count, *scratch[0]), *got)
if code != OK { return code }
for i: cast(s64)0..count * channels - 1 { output[done * channels + i] = Pcm16(cast(float64)scratch[i]) }
done += count
}
<<frames = done
return OK
}
// Moves to exact PCM frame FRAME (0..frames): the next read returns the
// same samples a read from the start would. Seeks begin at the nearest seek
// point and decode forward, so the bit reservoir and overlap are primed.
Mp3DecoderSeek :: (decoder: *Mp3Decoder, frame: s64) -> s32 {
if decoder.handle == null || frame < 0 || frame > decoder.info.frames { return Invalid }
if NativeSeek(decoder.handle, cast(u64)frame) == 0 { return Malformed }
decoder.position = frame
return OK
}
Mp3DecoderRewind :: (decoder: *Mp3Decoder) -> s32 { return Mp3DecoderSeek(decoder, 0) }
// Whole-file float decode at the stream's own rate, bounded by MaxFrames.
// OUTPUT is unchanged on an error.
Mp3Decode :: (input: []u8, max_frames: s64, output: *PCM) -> s32 {
decoder: Mp3Decoder
code := Mp3DecoderOpen(*decoder, input, max_frames)
if code != OK { return code }
defer { Mp3DecoderClose(*decoder) }
if decoder.info.frames > MaxFrames { return LimitExceeded }
samples: Vec(float32)
count := decoder.info.frames * decoder.info.channels
if !VecResize(samples, count) { return AllocationFailed }
frames: s64
code = Mp3DecoderRead(*decoder, VecSlice(samples, 0, count), *frames)
if code != OK { return code }
output.rate = decoder.info.rate; output.channels = decoder.info.channels
SwapSamples(output, *samples)
return OK
}
// Whole-file interleaved s16 decode; INFO describes the samples. Both
// outputs are unchanged on an error.
Mp3DecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *Mp3Info) -> s32 {
decoder: Mp3Decoder
code := Mp3DecoderOpen(*decoder, input, max_frames)
if code != OK { return code }
defer { Mp3DecoderClose(*decoder) }
if decoder.info.frames > MaxFrames { return LimitExceeded }
samples: Vec(s16)
count := decoder.info.frames * decoder.info.channels
if !VecResize(samples, count) { return AllocationFailed }
frames: s64
code = Mp3DecoderReadS16(*decoder, VecSlice(samples, 0, count), *frames)
if code != OK { return code }
<<info = decoder.info
VecSwap(samples, <<output)
return OK
}
+182
View File
@@ -0,0 +1,182 @@
// Portable MPEG audio stream inspection for MP3 files: MPEG-1, MPEG-2 and
// MPEG-2.5, Layers I, II and III. It skips ID3v2, ID3v1 and APEv2 tags,
// reads Xing/Info, VBRI and LAME gapless headers, and walks every frame
// header, so the exact duration and truncation are known without a codec
// library. std/audio_mp3 decodes the bytes this module accepts.
#import "std/audio_types"
// `frames` is the exact PCM frame count a decoder returns: a Xing/Info
// frame count (or the walked frames) times the frame length, minus the LAME
// encoder delay and padding. Bitrate is nominal for CBR, the average for VBR.
Mp3Info :: struct {
version: s32 // 1 = MPEG-1, 2 = MPEG-2, 25 = MPEG-2.5
layer: s32 // 1, 2 or 3
channels: s32
rate: s32
frames: s64
mp3_frames: s64 // audio frames, without a Xing/Info tag frame
frame_samples: s32 // PCM frames per MPEG frame: 384, 576 or 1152
delay: s32 // leading PCM frames removed (LAME delay + 529)
padding: s32 // trailing PCM frames removed
bitrate: s32 // bits per second
vbr: bool
audio_at: s64 // first frame byte, a Xing/Info frame included
audio_end: s64 // byte after the last frame
}
Mp3Header :: struct { version: s32; layer: s32; rate: s32; channels: s32; kbps: s32; samples: s32; bytes: s64; crc: bool; }
// 24 hours at 48 kHz, as for incremental Opus decoding.
Mp3MaxStreamFrames :: 4147200000
#scope_file
Bitrate :: (version: s32, layer: s32, index: s32) -> s32 {
mpeg1: [45]s32 = .[0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,
0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]
mpeg2: [30]s32 = .[0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]
if version == 1 { return mpeg1[(layer - 1) * 15 + index] }
return mpeg2[ifx layer == 1 then index else 15 + index]
}
Big :: (input: []u8, at: s64) -> s64 {
return (cast(s64)input[at] << 24) | (cast(s64)input[at + 1] << 16) | (cast(s64)input[at + 2] << 8) | cast(s64)input[at + 3]
}
Zeros :: (input: []u8, at: s64) -> bool {
while at < input.count { if input[at] != 0 { return false }; at += 1 }
return true
}
#scope_export
// Parses the four-byte frame header at AT: Malformed when there is none,
// Unsupported for free-format frames, whose length no header states.
Mp3ParseHeader :: (input: []u8, at: s64, header: *Mp3Header) -> s32 {
<<header = Mp3Header.{}
if at < 0 || at > input.count || input.count - at < 4 { return Malformed }
b1 := cast(s32)input[at + 1]; b2 := cast(s32)input[at + 2]; b3 := cast(s32)input[at + 3]
if input[at] != 255 || (b1 & 224) != 224 { return Malformed }
version_bits := (b1 >> 3) & 3; layer_bits := (b1 >> 1) & 3
bitrate_index := (b2 >> 4) & 15; rate_index := (b2 >> 2) & 3
if version_bits == 1 || layer_bits == 0 || bitrate_index == 15 || rate_index == 3 { return Malformed }
if bitrate_index == 0 { return Unsupported }
rates: [3]s32 = .[44100, 48000, 32000]
header.version = ifx version_bits == 3 then 1 else ifx version_bits == 2 then 2 else 25
header.layer = 4 - layer_bits
header.rate = rates[rate_index] >> (ifx header.version == 1 then 0 else ifx header.version == 2 then 1 else 2)
header.channels = ifx (b3 >> 6) == 3 then 1 else 2
header.kbps = Bitrate(ifx header.version == 1 then 1 else 2, header.layer, bitrate_index)
header.samples = ifx header.layer == 1 then 384 else ifx header.layer == 2 || header.version == 1 then 1152 else 576
header.crc = (b1 & 1) == 0
bytes := cast(s64)header.samples * header.kbps * 125 / header.rate
if header.layer == 1 { bytes -= bytes % 4 }
if ((b2 >> 1) & 1) != 0 { bytes += ifx header.layer == 1 then 4 else 1 }
header.bytes = bytes
return OK
}
// Validates the whole stream before any decoder sees it. Every byte between
// the leading ID3v2 tags and the trailing ID3v1/APEv2 tags must be a
// complete frame with the first frame's version, layer, rate and channel
// count, optionally followed by zero padding. A partial last frame, a Xing
// count above the walked frames, junk between frames and non-MPEG input are
// Malformed. Clears INFO on failure.
Mp3Inspect :: (input: []u8, info: *Mp3Info) -> s32 {
<<info = Mp3Info.{}
if input.count > MaxBytes { return LimitExceeded }
at: s64 = 0
while input.count - at >= 10 && Magic(input, at, "ID3") {
if input[at + 3] == 255 || input[at + 4] == 255 { return Malformed }
size: s64
for i: 6..9 {
if input[at + i] >= 128 { return Malformed }
size = size * 128 + cast(s64)input[at + i]
}
if (cast(s32)input[at + 5] & 16) != 0 { size += 10 }
if size > input.count - at - 10 { return Malformed }
at += 10 + size
}
end := input.count
if end - at >= 128 && Magic(input, end - 128, "TAG") { end -= 128 }
if end - at >= 32 && Magic(input, end - 32, "APETAGEX") {
size := cast(s64)Little(input, end - 20, 4)
if (Little(input, end - 12, 4) >> 31) != 0 { size += 32 }
if size < 32 || size > end - at { return Malformed }
end -= size
}
stream := input[0:end]
while at < end && stream[at] == 0 { at += 1 }
first: Mp3Header
code := Mp3ParseHeader(stream, at, *first)
if code != OK { return code }
if first.bytes > end - at { return Malformed }
audio_at := at
declared: s64 = -1
delay: s64; padding: s64
vbr := false
if first.layer == 3 {
side: s64 = ifx first.version == 1 then (ifx first.channels == 1 then 17 else 32) else (ifx first.channels == 1 then 9 else 17)
tag := at + 4 + side + (ifx first.crc then 2 else 0)
frame_end := at + first.bytes
if frame_end - tag >= 8 && (Magic(stream, tag, "Xing") || Magic(stream, tag, "Info")) {
vbr = Magic(stream, tag, "Xing")
flags := cast(s32)stream[tag + 7]
field := tag + 8
if (flags & 1) != 0 {
if frame_end - field < 4 { return Malformed }
declared = Big(stream, field); field += 4
}
if (flags & 2) != 0 { field += 4 }
if (flags & 4) != 0 { field += 100 }
if (flags & 8) != 0 { field += 4 }
if frame_end - field < 1 { return Malformed }
if stream[field] != 0 {
if frame_end - field < 36 { return Malformed }
a := cast(s64)stream[field + 21]; b := cast(s64)stream[field + 22]; c := cast(s64)stream[field + 23]
delay = ((a << 4) | (b >> 4)) + 529
padding = (((b & 15) << 8) | c) - 529
if padding < 0 { padding = 0 }
}
at = frame_end
} else if Magic(stream, at + 36, "VBRI") { vbr = true }
}
// A tag frame may use another bitrate than the audio frames after it.
walked: s64; bytes: s64; kbps: s32
constant := true
while at < end {
header: Mp3Header
code = Mp3ParseHeader(stream, at, *header)
if code == Malformed && Zeros(stream, at) { break }
if code != OK { return code }
if header.version != first.version || header.layer != first.layer || header.rate != first.rate || header.channels != first.channels { return Unsupported }
if header.bytes > end - at { return Malformed }
if walked == 0 { kbps = header.kbps } else if header.kbps != kbps { constant = false }
walked += 1; bytes += header.bytes; at += header.bytes
}
if walked == 0 || declared > walked { return Malformed }
counted := ifx declared > 0 then declared else walked
frames := counted * first.samples - delay - padding
if frames <= 0 { return Malformed }
if frames > Mp3MaxStreamFrames { return LimitExceeded }
vbr = vbr || !constant
info.version = first.version; info.layer = first.layer; info.channels = first.channels; info.rate = first.rate
info.frames = frames; info.mp3_frames = walked; info.frame_samples = first.samples
info.delay = cast(s32)delay; info.padding = cast(s32)padding
duration := walked * first.samples
info.bitrate = ifx vbr then cast(s32)((bytes * 8 * first.rate + duration / 2) / duration) else kbps * 1000
info.vbr = vbr; info.audio_at = audio_at; info.audio_end = at
return OK
}
Mp3Seconds :: (info: *Mp3Info) -> float64 {
if info.rate <= 0 { return 0.0 }
return cast(float64)info.frames / cast(float64)info.rate
}
// One summary line, shared by the CLI and the Windows decode check.
Mp3PrintInfo :: (info: *Mp3Info) {
if info.rate <= 0 { print("MP3: no stream\n"); return }
version := ifx info.version == 25 then "2.5" else ifx info.version == 2 then "2" else "1"
layer := ifx info.layer == 1 then "I" else ifx info.layer == 2 then "II" else "III"
milliseconds := (info.frames * 1000 + info.rate / 2) / info.rate
fraction := milliseconds % 1000
print("MP3: MPEG-% Layer %, % channels, % Hz, % frames, %.", version, layer, info.channels, info.rate, info.frames, milliseconds / 1000)
if fraction < 100 { print("0") }
if fraction < 10 { print("0") }
print("% s, % bps %, delay %, padding %, % MPEG frames\n", fraction, info.bitrate, ifx info.vbr then "VBR" else "CBR", info.delay, info.padding, info.mp3_frames)
}
+11
View File
@@ -0,0 +1,11 @@
// Import the output device for the compilation target. PCM voices and mixing
// live in std/audio and can also be rendered without opening a device.
#if OS == .WEB || #defined(PLATFORM_WEB) {
using Platform :: #import "std/audio_sink_web"
} else {
#if OS == .ANDROID || #defined(ANDROID_BUILD) || #defined(PLATFORM_ANDROID) || #defined(__ANDROID__) {
using Platform :: #import "std/audio_sink_android"
} else {
using Platform :: #import "std/audio_sink_sdl"
}
}
+25
View File
@@ -0,0 +1,25 @@
// Android's output device for the shared audio mixer. The API-21 scaffold
// needs OpenSL ES on Android 5/6/7; devices with AAudio use float32 output.
// Public contract matches audio_sink_sdl. Call open/close on the application thread.
AAudio :: #import "std/audio_android_aaudio";
OpenSL :: #import "std/audio_android_opensl";
Buffer :: #import "std/audio_android_buffer";
Device :: #import "std/audio_device";
#scope_file
gate: Device.Device;
OpenDevice :: () -> bool {
if AAudio.Available() { return AAudio.Open() }
return OpenSL.Open()
}
CloseDevice :: () { AAudio.Close(); OpenSL.Close() }
#scope_export
AudioSinkOpen :: () -> bool {
Buffer.Install()
if Device.Ready(*gate) && !AAudio.Ready() && !OpenSL.Ready() { Device.Invalidate(*gate) }
return Device.Open(*gate, OpenDevice, CloseDevice)
}
AudioSinkReady :: () -> bool { return Device.Ready(*gate) && (AAudio.Ready() || OpenSL.Ready()) }
AudioSinkPending :: () -> bool { return Device.Pending(*gate) }
AudioSinkUnavailable :: () -> bool { return Device.Unavailable(*gate) }
AudioSinkClose :: () { Device.Close(*gate) }
+99
View File
@@ -0,0 +1,99 @@
// Desktop audio output for std/audio: SDL2 opens the default output
// for 48 kHz float32 stereo, converting to what the device takes, and its
// audio thread pulls each block from the mixer. It needs no window. With
// SDL_AUDIODRIVER=disk SDL writes the blocks to SDL_DISKAUDIOFILE instead,
// so a test hears exactly what was mixed without a device.
Mixer :: #import "std/audio";
Device :: #import "std/audio_device";
#import "std/byte_text_linux"
#scope_file
sdl :: #system_library "SDL2";
InitSubSystem :: (flags: u32) -> s32 #foreign sdl "SDL_InitSubSystem";
QuitSubSystem :: (flags: u32) #foreign sdl "SDL_QuitSubSystem";
OpenDevice :: (name: *u8, capture: s32, wanted: *Spec, obtained: *Spec,
changes: s32) -> u32 #foreign sdl "SDL_OpenAudioDevice";
CloseDevice :: (device: u32) #foreign sdl "SDL_CloseAudioDevice";
PauseDevice :: (device: u32, paused: s32) #foreign sdl "SDL_PauseAudioDevice";
CreateMutex :: () -> *void #foreign sdl "SDL_CreateMutex";
LockMutex :: (mutex: *void) -> s32 #foreign sdl "SDL_LockMutex";
UnlockMutex :: (mutex: *void) -> s32 #foreign sdl "SDL_UnlockMutex";
Pull :: #type (argument: *void, stream: *u8, length: s32) -> void #c_call;
// SDL_AudioSpec.
Spec :: struct {
frequency: s32
format: u16
channels: u8
silence: u8
samples: u16
padding: u16
size: u32
callback: Pull
argument: *void
}
// SDL_INIT_AUDIO and AUDIO_F32SYS on a little-endian host.
INIT_AUDIO :: 0x10
FLOAT32 :: 0x8120
device: u32;
mutex: *void;
gate: Device.Device;
Mix :: (argument: *void, stream: *u8, length: s32) {
unused argument
samples: []float32
view := cast(*ByteDescriptor)(*samples)
view.data = stream
view.length = cast(s64)length / 4
Enter()
Mixer.AudioRender(samples, cast(s64)length / 8)
Leave()
}
Enter :: () { if mutex != null { unused LockMutex(mutex) } }
Leave :: () { if mutex != null { unused UnlockMutex(mutex) } }
OpenDeviceThread :: () -> bool {
if device != 0 { return true }
if InitSubSystem(cast(u32)INIT_AUDIO) != 0 { return false }
pull: Pull = Mix
wanted: Spec
wanted.frequency = Mixer.AUDIO_RATE
wanted.format = cast(u16)FLOAT32
wanted.channels = 2
wanted.samples = 1024
wanted.callback = pull
obtained: Spec
opened := OpenDevice(null, 0, *wanted, *obtained, 0)
if opened == 0 { QuitSubSystem(cast(u32)INIT_AUDIO); return false }
device = opened
PauseDevice(device, 0)
return true
}
CloseDeviceThread :: () {
if device == 0 { return }
CloseDevice(device)
device = 0
QuitSubSystem(cast(u32)INIT_AUDIO)
}
#scope_export
// Requests a background open; false while pending or unavailable. Retry is
// throttled for one second after failure. Ready/Pending/Unavailable poll it.
AudioSinkOpen :: () -> bool {
if mutex == null {
mutex = CreateMutex()
if mutex == null { return false }
}
enter: Mixer.AudioLockCall = Enter
leave: Mixer.AudioLockCall = Leave
Mixer.AudioUseLock(enter, leave)
return Device.Open(*gate, OpenDeviceThread, CloseDeviceThread)
}
AudioSinkReady :: () -> bool { return Device.Ready(*gate) }
AudioSinkPending :: () -> bool { return Device.Pending(*gate) }
AudioSinkUnavailable :: () -> bool { return Device.Unavailable(*gate) }
AudioSinkClose :: () { Device.Close(*gate) }
+115
View File
@@ -0,0 +1,115 @@
// WebAudio output for std/audio. A short timer schedules two immutable PCM
// buffers ahead of the audio clock; suspended contexts do not consume voices.
// The application calls AudioSinkResume from a trusted gesture when required.
#import "std/web"
#import "std/byte_text_linux"
Mixer :: #import "std/audio";
#scope_file
context: s32;
attempted: bool;
timer: float64;
tick: s32;
ignore: s32;
sources: [4]s32;
ends: [4]float64;
next_time: float64;
samples: [2048]float32;
channel: [1024]float32;
Unlocked :: () {}
Ignore :: (data: s32, first: s32, second: s32, third: s32) {
unused data; unused first; unused second; unused third
}
ReleaseSource :: (slot: s64) {
if sources[slot] == 0 { return }
unused WebCall0(sources[slot], WebName("disconnect"))
WebRelease(sources[slot])
sources[slot] = 0
}
Running :: () -> bool {
scope := WebScope(); defer WebEnd(scope)
if context == 0 { return false }
state := WebGet(context, WebName("state"))
if state.tag != WebStringTag { return false }
text: [24]u8
unused WebCopyString(WebAsObject(state), text[:])
return TextFromCString(*text[0]) == "running"
}
Pump :: (data: s32, first: s32, second: s32, third: s32) {
unused data; unused first; unused second; unused third
if !Running() { return }
now := WebGetNumber(context, WebName("currentTime"))
for slot: 0..3 { if sources[slot] != 0 && ends[slot] <= now { ReleaseSource(slot) } }
if next_time < now { next_time = now }
for block: 0..1 {
unused block
if next_time >= now + 2048.0 / 48000.0 { break }
slot: s64 = -1
for index: 0..3 { if sources[index] == 0 { slot = index; break } }
if slot < 0 { break }
buffer := WebAsObject(WebCall3(context, WebName("createBuffer"), WebNumber(2.0), WebNumber(1024.0), WebNumber(48000.0)))
if buffer == 0 || WebFailed() { return }
Mixer.AudioRender(samples[:], 1024)
for side: 0..1 {
for frame: 0..1023 { channel[frame] = samples[frame * 2 + side] }
target := WebAsObject(WebCall1(buffer, WebName("getChannelData"), WebNumber(cast(float64)side)))
view := WebBytes(WebBytesFloat32, cast(*void)*channel[0], 1024)
unused WebCall1(target, WebName("set"), WebObject(view))
WebRelease(view)
}
source := WebAsObject(WebCall0(context, WebName("createBufferSource")))
if source == 0 || WebFailed() { WebRelease(buffer); return }
WebSet(source, WebName("buffer"), WebObject(buffer))
unused WebCall1(source, WebName("connect"), WebObject(WebGetObject(context, WebName("destination"))))
unused WebCall1(source, WebName("start"), WebNumber(next_time))
WebRelease(buffer)
if WebFailed() { WebRelease(source); return }
sources[slot] = WebKeep(source)
next_time += 1024.0 / 48000.0
ends[slot] = next_time
}
}
#scope_export
AudioSinkReady :: () -> bool { return context != 0 }
AudioSinkPending :: () -> bool { return false }
AudioSinkUnavailable :: () -> bool { return attempted && context == 0 }
AudioSinkRunning :: () -> bool { return Running() }
AudioSinkResume :: () -> bool {
scope := WebScope(); defer WebEnd(scope)
if context == 0 { return false }
promise := WebAsObject(WebCall0(context, WebName("resume")))
if promise != 0 { unused WebCall1(promise, WebName("catch"), WebObject(ignore)) }
return !WebFailed()
}
AudioSinkClose :: () {
scope := WebScope(); defer WebEnd(scope)
attempted = false
if context == 0 { return }
unused WebCall1(WebGlobal, WebName("clearInterval"), WebNumber(timer))
for slot: 0..3 {
if sources[slot] != 0 { unused WebCall0(sources[slot], WebName("stop")); ReleaseSource(slot) }
}
unused WebCall0(context, WebName("close"))
WebRelease(tick); WebRelease(ignore); WebRelease(context)
tick = 0; ignore = 0; context = 0; next_time = 0.0
}
AudioSinkOpen :: () -> bool {
scope := WebScope(); defer WebEnd(scope)
if context != 0 { return true }
attempted = true
constructor := WebGetObject(WebGlobal, WebName("AudioContext"))
if constructor == 0 { return false }
opened := WebNew0(constructor)
if opened == 0 || WebFailed() { return false }
context = WebKeep(opened)
ignore = WebFunction(Ignore, 0)
tick = WebFunction(Pump, 0)
result := WebCall2(WebGlobal, WebName("setInterval"), WebObject(tick), WebNumber(10.0))
if WebFailed() { AudioSinkClose(); return false }
timer = WebAsNumber(result)
unlocked: Mixer.AudioLockCall = Unlocked
Mixer.AudioUseLock(unlocked, unlocked) // Web callbacks and the application share one thread.
return true
}
+57
View File
@@ -0,0 +1,57 @@
#import "std/vec"
OK :: 0
Invalid :: 2
Malformed :: 3
Unsupported :: 4
LimitExceeded :: 5
NativeFailure :: 6
AllocationFailed :: 7
IOFailure :: 8
// Interleaved normalized float samples. The caller owns the vector.
PCM :: struct { samples: Vec(float32); rate: s32; channels: s32; }
// Memory/work bounds apply before allocations. Rates are bounded to avoid
// enormous output for hostile headers. Whole-file APIs are intentionally bounded.
MaxBytes :: 268435456
MaxFrames :: 28800000
ValidPCM :: (pcm: *PCM) -> bool {
if pcm == null || pcm.channels < 1 || pcm.channels > 2 || pcm.rate < 8000 || pcm.rate > 192000 { return false }
if pcm.samples.count <= 0 || pcm.samples.count % pcm.channels != 0 || pcm.samples.count / pcm.channels > MaxFrames { return false }
for i: 0..pcm.samples.count - 1 {
value := pcm.samples[i]
if value != value || value < -16.0 || value > 16.0 { return false }
}
return true
}
ErrorText :: (code: s32) -> string {
if code == OK { return "ok" }
if code == Invalid { return "invalid argument" }
if code == Malformed { return "malformed audio" }
if code == Unsupported { return "unsupported audio capability" }
if code == LimitExceeded { return "audio limit exceeded" }
if code == AllocationFailed { return "allocation failed" }
if code == IOFailure { return "input/output failed" }
return "native audio failure"
}
Little :: (input: []u8, at: s64, count: s64) -> u64 {
value: u64
for i: cast(s64)0..count - 1 { value |= cast(u64)input[at + i] << cast(u64)(8 * i) }
return value
}
PutLittle :: (output: []u8, at: s64, count: s64, value: u64) {
for i: cast(s64)0..count - 1 { output[at + i] = cast(u8)(value >> cast(u64)(8 * i)) }
}
Magic :: (input: []u8, at: s64, text: string) -> bool {
if at < 0 || at > input.count || input.count - at < text.count { return false }
for i: 0..text.count - 1 { if input[at + i] != text[i] { return false } }
return true
}
// The PCM16 boundary for finite samples: clip overshoot to
// [-1, 32767/32768], scale by 32768 and truncate, as WAV output does.
Pcm16 :: (value: float64) -> s16 {
if value < -1.0 { value = -1.0 }; if value > 32767.0 / 32768.0 { value = 32767.0 / 32768.0 }
return cast(s16)cast(s64)(value * 32768.0)
}
// Move ownership between caller vector and PCM without copying samples.
SwapSamples :: (pcm: *PCM, samples: *Vec(float32)) { VecSwap(pcm.samples, <<samples) }
+73
View File
@@ -0,0 +1,73 @@
#import "std/audio_types"
#import "std/vec"
#import "std/binary"
// Canonical RIFF WAVE PCM16 or IEEE float32 mono/stereo. Unknown chunks are
// skipped with padding, but duplicate fmt/data, RF64 and compressed WAV reject.
WavDecode :: (input: []u8, max_frames: s64, output: *PCM) -> s32 {
if input.count > MaxBytes { return LimitExceeded }
if input.count < 12 || !Magic(input, 0, "RIFF") || !Magic(input, 8, "WAVE") || Little(input, 4, 4) + 8 != cast(u64)input.count { return Malformed }
at: s64 = 12
channels: s32; rate: s32; bits: s32; format: s32
start: s64 = -1; length: s64
while at < input.count {
if input.count - at < 8 { return Malformed }
size := cast(s64)Little(input, at + 4, 4)
body := at + 8
if size > input.count - body { return Malformed }
if Magic(input, at, "fmt ") {
if channels != 0 || size < 16 { return Malformed }
format = cast(s32)Little(input, body, 2); channels = cast(s32)Little(input, body + 2, 2)
rate = cast(s32)Little(input, body + 4, 4); bits = cast(s32)Little(input, body + 14, 2)
if channels < 1 || channels > 2 || rate < 8000 || rate > 192000 { return Unsupported }
if (format != 1 || bits != 16) && (format != 3 || bits != 32) { return Unsupported }
if Little(input, body + 12, 2) != cast(u64)(channels * bits / 8) || Little(input, body + 8, 4) != cast(u64)rate * cast(u64)(channels * bits / 8) { return Malformed }
} else if Magic(input, at, "data") {
if start != -1 { return Malformed }; start = body; length = size
}
at = body + size + size % 2
}
if at != input.count || channels == 0 || start < 0 || length == 0 || length % (channels * bits / 8) != 0 { return Malformed }
frames := length / (channels * bits / 8)
if max_frames <= 0 || frames > max_frames || frames > MaxFrames { return LimitExceeded }
samples: Vec(float32)
if !VecResize(samples, frames * channels) { return AllocationFailed }
for i: cast(s64)0..samples.count - 1 {
value: float64
if format == 1 {
raw := cast(s32)Little(input, start + i * 2, 2)
if raw >= 32768 { raw -= 65536 }; value = cast(float64)raw / 32768.0
} else { value = Float32FromBits(cast(u32)Little(input, start + i * 4, 4)) }
if value != value || value < -1.0 || value > 1.0 { return Malformed }
samples[i] = cast(float32)value
}
output.rate = rate; output.channels = channels
SwapSamples(output, *samples)
return OK
}
// PCM16 output clips finite sinc/codec overshoots at the integer boundary.
WavEncode :: (pcm: *PCM, output: *Vec(u8)) -> s32 {
if pcm.channels < 1 || pcm.channels > 2 || pcm.rate < 8000 || pcm.rate > 192000 || pcm.samples.count <= 0 || pcm.samples.count % pcm.channels != 0 { return Invalid }
count := pcm.samples.count
if count / pcm.channels > MaxFrames || count * 2 + 44 > MaxBytes { return LimitExceeded }
bytes: Vec(u8)
if !VecResize(bytes, count * 2 + 44) { return AllocationFailed }
{
data := VecSlice(bytes, 0, bytes.count)
text := "RIFF"
for i: 0..3 { data[i] = text[i] }
PutLittle(data, 4, 4, cast(u64)(bytes.count - 8)); text = "WAVEfmt "
for i: 0..7 { data[8 + i] = text[i] }
PutLittle(data, 16, 4, 16); PutLittle(data, 20, 2, 1)
PutLittle(data, 22, 2, cast(u64)pcm.channels); PutLittle(data, 24, 4, cast(u64)pcm.rate)
PutLittle(data, 28, 4, cast(u64)(pcm.rate * pcm.channels * 2)); PutLittle(data, 32, 2, cast(u64)(pcm.channels * 2)); PutLittle(data, 34, 2, 16)
text = "data"
for i: 0..3 { data[36 + i] = text[i] }
PutLittle(data, 40, 4, cast(u64)(count * 2))
for i: cast(s64)0..count - 1 {
value := cast(float64)pcm.samples[i]
if value - value != 0.0 { return Invalid }
PutLittle(data, 44 + i * 2, 2, cast(u64)cast(s64)Pcm16(value))
}
}
VecSwap(bytes, <<output); return OK
}
+30
View File
@@ -0,0 +1,30 @@
# Native MP3 implementation for std/audio_mp3. No UI or audio package needed.
include_guard(GLOBAL)
function(ziran_audio_mp3)
if(TARGET ziran_mp3)
return()
endif()
set(dr_mp3_dir "${CMAKE_CURRENT_BINARY_DIR}/dr_mp3")
file(MAKE_DIRECTORY "${dr_mp3_dir}")
set(dr_mp3_ref f12e197fd462e4c22873fbd70d11b1d2f2c1dc3c)
foreach(file IN ITEMS dr_mp3.h LICENSE)
if(file STREQUAL "dr_mp3.h")
set(hash 7a6cc38b0afdb55cfc9eec991d9169d67beb8fd910be2995121510cdaa99c356)
else()
set(hash dd1c647e6f767f8ff4b2dfae0fed314726600a01e0cf1ef556afddd5fa96ff15)
endif()
if(EXISTS "${dr_mp3_dir}/${file}")
file(SHA256 "${dr_mp3_dir}/${file}" actual)
else()
set(actual "")
endif()
if(NOT actual STREQUAL hash)
file(DOWNLOAD "https://raw.githubusercontent.com/mackron/dr_libs/${dr_mp3_ref}/${file}"
"${dr_mp3_dir}/${file}" EXPECTED_HASH SHA256=${hash} TLS_VERIFY ON)
endif()
endforeach()
add_library(ziran_mp3 STATIC "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/ziran_mp3.c")
target_include_directories(ziran_mp3 PRIVATE "${dr_mp3_dir}")
target_compile_options(ziran_mp3 PRIVATE -ffunction-sections -fdata-sections)
set_target_properties(ziran_mp3 PROPERTIES POSITION_INDEPENDENT_CODE ON C_STANDARD 99)
endfunction()
+4
View File
@@ -0,0 +1,4 @@
cmake_minimum_required(VERSION 3.22)
project(ziran_audio_native C)
include("${CMAKE_CURRENT_LIST_DIR}/AudioCodecs.cmake")
ziran_audio_mp3()
+55
View File
@@ -0,0 +1,55 @@
/* The one translation unit for dr_mp3 (mackron/dr_libs, public domain or
* MIT-0; see LICENSE in the pinned `dr_libs` source dependency), plus the
* two calls Ziran cannot express itself: sizing and binding the decoder's
* native state. Everything else in std/audio_mp3 calls dr_mp3's API directly.
* Float output keeps the synthesis filter's full precision; s16 reads round
* and clip that float output. No stdio: callers pass whole-file bytes. */
#define DR_MP3_IMPLEMENTATION
#define DR_MP3_FLOAT_OUTPUT
#define DR_MP3_NO_STDIO
#include "dr_mp3.h"
#include <stdint.h>
#include <stdlib.h>
typedef struct {
drmp3 decoder;
drmp3_seek_point *seek_points;
} ziran_mp3;
/* Opens a decoder over borrowed, validated MPEG audio frames. With
* seek_points > 0 it also binds a seek table of up to that many points, so
* seeks start a few frames before their target instead of at the stream
* start; dr_mp3 still decodes forward to the exact frame. Returns NULL when
* the bytes hold no decodable frame or allocation fails. */
void *ziran_mp3_open(const void *data, size_t size, uint32_t seek_points) {
ziran_mp3 *state;
if (data == NULL || size == 0) return NULL;
state = (ziran_mp3 *)calloc(1, sizeof(ziran_mp3));
if (state == NULL) return NULL;
if (!drmp3_init_memory(&state->decoder, data, size, NULL)) {
free(state);
return NULL;
}
if (seek_points > 0) {
drmp3_uint32 count = seek_points;
state->seek_points = (drmp3_seek_point *)calloc(count, sizeof(drmp3_seek_point));
if (state->seek_points == NULL ||
!drmp3_calculate_seek_points(&state->decoder, &count, state->seek_points) ||
!drmp3_bind_seek_table(&state->decoder, count, state->seek_points)) {
drmp3_uninit(&state->decoder);
free(state->seek_points);
free(state);
return NULL;
}
}
return state;
}
void ziran_mp3_close(void *handle) {
ziran_mp3 *state = (ziran_mp3 *)handle;
if (state == NULL) return;
drmp3_uninit(&state->decoder);
free(state->seek_points);
free(state);
}
+145
View File
@@ -0,0 +1,145 @@
// Portable Ogg container validation and bounded packet/page construction.
#import "std/audio_types"
#import "std/vec"
// Ogg CRC-32 (non-reflected), with the checksum field treated as zero.
OggCRC :: (page: []u8) -> u32 {
crc: u32
for i: 0..page.count - 1 {
byte := ifx i >= 22 && i < 26 then cast(u8)0 else page[i]
crc ^= cast(u32)byte << cast(u32)24
for bit: 0..7 { crc = ifx (crc & cast(u32)0x80000000) != 0 then (crc << cast(u32)1) ^ cast(u32)0x04c11db7 else crc << cast(u32)1 }
}
return crc
}
// Bounded packet iterator. Borrowed input must outlive this record. A returned
// packet is valid until the next call; never retain a view over NextPacket.
OggReader :: struct {
input: []u8
at: s64
end: s64
body: s64
segment: s64
segments: s64
serial: u64
sequence: u64
granule: s64
flags: u8
packet: [65536]u8
packet_count: s64
done: bool
page_last: bool
last_complete: bool
}
NextPacket :: (reader: *OggReader) -> s32 {
reader.packet_count = 0
if reader.done { return OK }
while true {
if reader.segment == reader.segments {
if reader.at == reader.input.count {
if reader.packet_count != 0 { return Malformed }
reader.done = true; return OK
}
at := reader.at
input := reader.input
if input.count - at < 27 || !Magic(input, at, "OggS") || input[at + 4] != 0 { return Malformed }
flags := input[at + 5]
if (flags & 248) != 0 || ((flags & 1) != 0) != (reader.packet_count != 0) { return Malformed }
first := at == 0
if ((flags & 2) != 0) != first { return Malformed }
serial := Little(input, at + 14, 4)
sequence := Little(input, at + 18, 4)
if first { reader.serial = serial } else if serial != reader.serial { return Unsupported }
if sequence != reader.sequence { return Malformed }
reader.sequence += 1
segments := cast(s64)input[at + 26]
if segments == 0 || input.count - at - 27 < segments { return Malformed }
body := at + 27 + segments
size: s64
for i: cast(s64)0..segments - 1 { size += input[at + 27 + i] }
if input.count - body < size { return Malformed }
end := body + size
if cast(u64)OggCRC(input[at:end]) != Little(input, at + 22, 4) { return Malformed }
if ((flags & 4) != 0) != (end == input.count) { return Malformed }
reader.end = end; reader.body = body; reader.segment = 0; reader.segments = segments
reader.flags = flags; reader.granule = cast(s64)Little(input, at + 6, 8)
completed: s64
for i: cast(s64)0..segments - 1 { if input[at + 27 + i] < 255 { completed += 1 } }
if completed == 0 && reader.granule != -1 { return Malformed }
}
count := cast(s64)reader.input[reader.at + 27 + reader.segment]
if reader.packet_count + count > 65536 { return LimitExceeded }
start := reader.packet_count
reader.packet_count = start + count
for i: cast(s64)0..count - 1 { reader.packet[start + i] = reader.input[reader.body + i] }
reader.body += count; reader.segment += 1
reader.page_last = reader.segment == reader.segments
if reader.page_last {
reader.at = reader.end
if count == 255 && (reader.flags & 4) != 0 { return Malformed }
}
if count < 255 {
reader.last_complete = true
for i: reader.segment..reader.segments - 1 { if reader.input[reader.at + 27 + i] < 255 { reader.last_complete = false } }
return OK
}
}
}
// One complete packet per page. Output is staged by the whole-file encoder.
AppendPage :: (output: *Vec(u8), packet: []u8, flags: u8, granule: s64, serial: u32, sequence: u32) -> s32 {
if packet.count > 65024 { return LimitExceeded }
segments := packet.count / 255 + 1
start := output.count
end := start + 27 + segments + packet.count
if end > MaxBytes { return LimitExceeded }
if !VecReserve(<<output, end) { return AllocationFailed }
bytes: Vec(u8)
if !VecResize(bytes, end - start) { return AllocationFailed }
{
page := VecSlice(bytes, 0, bytes.count)
text := "OggS"
for i: 0..3 { page[i] = text[i] }
page[4] = 0; page[5] = flags
PutLittle(page, 6, 8, cast(u64)granule); PutLittle(page, 14, 4, serial)
PutLittle(page, 18, 4, sequence); PutLittle(page, 22, 4, 0)
page[26] = cast(u8)segments
for i: cast(s64)0..segments - 1 { page[27 + i] = ifx i == segments - 1 then cast(u8)(packet.count % 255) else cast(u8)255 }
for i: 0..packet.count - 1 { page[27 + segments + i] = packet[i] }
PutLittle(page, 22, 4, OggCRC(page))
}
for i: 0..bytes.count - 1 { unused VecPush(<<output, bytes[i]) }
return OK
}
// Efficient file muxing: accumulate up to 200 ms or 255 lacing entries in a
// page, amortizing the 27-byte header without changing Opus frame latency.
PageBuilder :: struct { body: [65025]u8; laces: [255]u8; count: s64; segments: s64; }
PageAdd :: (page: *PageBuilder, packet: []u8) -> s32 {
segments := packet.count / 255 + 1
if packet.count <= 0 || page.segments + segments > 255 || page.count + packet.count > 65025 { return LimitExceeded }
for i: cast(s64)0..segments - 1 { page.laces[page.segments + i] = ifx i == segments - 1 then cast(u8)(packet.count % 255) else cast(u8)255 }
for i: 0..packet.count - 1 { page.body[page.count + i] = packet[i] }
page.segments += segments; page.count += packet.count
return OK
}
PageFlush :: (page: *PageBuilder, output: *Vec(u8), final: bool, granule: s64, sequence: u32) -> s32 {
size := 27 + page.segments + page.count
if page.segments == 0 { return Invalid }
if output.count + size > MaxBytes { return LimitExceeded }
if !VecReserve(<<output, output.count + size) { return AllocationFailed }
bytes: Vec(u8)
if !VecResize(bytes, size) { return AllocationFailed }
{
data := VecSlice(bytes, 0, size)
text := "OggS"
for i: 0..3 { data[i] = text[i] }
data[4] = 0; data[5] = ifx final then cast(u8)4 else cast(u8)0
PutLittle(data, 6, 8, cast(u64)granule); PutLittle(data, 14, 4, 1); PutLittle(data, 18, 4, sequence)
data[26] = cast(u8)page.segments
for i: cast(s64)0..page.segments - 1 { data[27 + i] = page.laces[i] }
for i: cast(s64)0..page.count - 1 { data[27 + page.segments + i] = page.body[i] }
PutLittle(data, 22, 4, OggCRC(data))
}
for i: 0..bytes.count - 1 { unused VecPush(<<output, bytes[i]) }
page.count = 0; page.segments = 0
return OK
}
+279 -56
View File
@@ -1,69 +1,292 @@
// What an Ogg Vorbis stream held in memory declares, read from its pages
// alone: nothing is decoded or allocated, so a program can bound a stream
// before handing it to a decoder (std/vorbis_linux on Linux, or another
// platform's). Portable: no foreign library.
//
// audio: VorbisAudio
// if VorbisProbe(ogg_bytes, *audio) && audio.channels == 1 { ... }
// Portable Ogg Vorbis inspection (Vorbis I). std/ogg's
// OggReader checks the container (capture, CRC, one serial, page order,
// BOS/EOS, lacing); this module checks the identification, comment and setup
// headers and reads every audio packet's block size from the setup header's
// mode table, so the exact duration, the zero-based timeline and the end trim
// are known without a codec library. std/vorbis_linux decodes what it accepts.
#import "std/audio_types"
#import "std/vec"
#import "std/ogg"
// Interleaved CHANNELS at RATE, FRAMES long.
// `frames` is the exact PCM frame count a decoder returns: the final granule
// position, which trims the last packet(s). Bitrates are the header's hints,
// 0 when unset.
VorbisAudio :: struct {
channels: s32
rate: s32
frames: s64
nominal_bitrate: s32
maximum_bitrate: s32
minimum_bitrate: s32
short_block: s32 // blocksize_0
long_block: s32 // blocksize_1
modes: s32
packets: s64 // audio packets
comments: s64 // user comments in the comment header
end_trim: s64 // decodable frames past the final granule position
}
// An owned copy of the comment header: the vendor string, then each user
// comment ("FIELD=value", UTF-8 by the specification; not validated here).
// Free it with VorbisCommentsFree (or let the vectors go out of scope).
VorbisComments :: struct {
text: Vec(u8) // vendor bytes, then each comment's bytes
vendor: s64 // vendor length
spans: Vec(s64) // start and length of each comment in text
}
// 24 hours at 48 kHz, as for Opus and MP3 incremental decoding.
VorbisMaxStreamFrames :: 4147200000
#scope_file
Little :: (input: []u8, at: s64, count: s64) -> u64 {
value: u64 = 0
for index: cast(s64)0..count - 1 { value |= cast(u64)input[at + index] << cast(u64)(8 * index) }
Ilog :: (value: s64) -> s64 {
bits: s64
while value > 0 { bits += 1; value = value >> 1 }
return bits
}
// Chained or multiplexed streams: a beginning-of-stream page after the
// first. Pages are walked by their headers only; OggReader checks the rest.
Chained :: (input: []u8) -> bool {
at: s64
while input.count - at >= 27 && Magic(input, at, "OggS") {
segments := cast(s64)input[at + 26]
if input.count - at - 27 < segments { return false }
size: s64
for i: cast(s64)0..segments - 1 { size += input[at + 27 + i] }
if at > 0 && (input[at + 5] & 2) != 0 { return true }
at += 27 + segments + size
}
return false
}
Identification :: (packet: []u8, info: *VorbisAudio) -> s32 {
if packet.count != 30 || packet[0] != 1 || !Magic(packet, 1, "vorbis") { return Malformed }
if Little(packet, 7, 4) != 0 { return Unsupported }
channels := cast(s64)packet[11]
rate := cast(s64)Little(packet, 12, 4)
short := cast(s64)(packet[28] & 15); long := cast(s64)(packet[28] >> 4)
if channels == 0 || rate == 0 || short < 6 || long > 13 || short > long || (packet[29] & 1) == 0 { return Malformed }
if rate > 2147483647 { return Unsupported }
info.channels = cast(s32)channels; info.rate = cast(s32)rate
info.short_block = cast(s32)(1 << short); info.long_block = cast(s32)(1 << long)
rates: [3]s32
for i: 0..2 {
value := cast(s64)Little(packet, 16 + i * 4, 4)
if value >= 2147483648 { value -= 4294967296 }
rates[i] = ifx value > 0 then cast(s32)value else 0
}
info.maximum_bitrate = rates[0]; info.nominal_bitrate = rates[1]; info.minimum_bitrate = rates[2]
return OK
}
// Vendor, user comments and the framing bit; COMMENTS may be null.
CommentHeader :: (packet: []u8, comments: *VorbisComments, count: *s64) -> s32 {
if packet.count < 16 || packet[0] != 3 || !Magic(packet, 1, "vorbis") { return Malformed }
vendor := cast(s64)Little(packet, 7, 4)
if vendor > packet.count - 16 { return Malformed }
offset := 11 + vendor
total := cast(s64)Little(packet, offset, 4); offset += 4
if total > (packet.count - offset) / 4 { return Malformed }
copy: VorbisComments
if comments != null {
for i: cast(s64)11..offset - 5 { if !VecPush(copy.text, packet[i]) { return AllocationFailed } }
copy.vendor = vendor
}
index: s64
while index < total {
if packet.count - offset < 4 { return Malformed }
size := cast(s64)Little(packet, offset, 4); offset += 4
if size > packet.count - offset { return Malformed }
if comments != null {
if !VecPush(copy.spans, copy.text.count) || !VecPush(copy.spans, size) { return AllocationFailed }
for i: offset..offset + size - 1 { if !VecPush(copy.text, packet[i]) { return AllocationFailed } }
}
offset += size; index += 1
}
if offset >= packet.count || (packet[offset] & 1) == 0 { return Malformed }
if comments != null {
VecSwap(comments.text, copy.text); VecSwap(comments.spans, copy.spans)
comments.vendor = copy.vendor
}
<<count = total
return OK
}
// Bit INDEX counted backwards from the packet's last bit (Vorbis packs
// fields least significant bit first), and a WIDTH-bit field read the same
// way, which yields the field's value.
BackBit :: (packet: []u8, index: s64) -> s64 {
position := packet.count * 8 - 1 - index
return (cast(s64)packet[position >> 3] >> (position & 7)) & 1
}
BackBits :: (packet: []u8, index: s64, width: s64) -> s64 {
value: s64
for i: cast(s64)0..width - 1 { value = (value << 1) | BackBit(packet, index + i) }
return value
}
// The mode table closes the setup header, so it is read backwards from the
// framing bit, as FFmpeg's and liboggz's parsers do: each mode is a block
// flag, two zero 16-bit fields and an 8-bit mapping, and the largest count
// whose preceding 6-bit field agrees is the table. Codebooks, floors and
// residues are left to the decoder.
SetupModes :: (packet: []u8, long_blocks: []bool, modes: *s32) -> s32 {
if packet.count < 8 || packet[0] != 5 || !Magic(packet, 1, "vorbis") { return Malformed }
limit := packet.count * 8 - 56
at: s64
while at < limit && BackBit(packet, at) == 0 { at += 1 }
if at >= limit { return Malformed }
at += 1
start := at
count: s64; found: s64
while limit - at >= 47 && count < 64 {
if BackBits(packet, at, 8) > 63 || BackBits(packet, at + 8, 16) != 0 || BackBits(packet, at + 24, 16) != 0 { break }
at += 41; count += 1
if BackBits(packet, at, 6) + 1 == count { found = count }
}
if found == 0 { return Malformed }
for i: cast(s64)0..found - 1 { long_blocks[i] = BackBit(packet, start + (found - 1 - i) * 41 + 40) == 1 }
<<modes = cast(s32)found
return OK
}
// Validates the whole stream into INFO (and COMMENTS when not null).
Walk :: (input: []u8, info: *VorbisAudio, comments: *VorbisComments) -> s32 {
if input.count > MaxBytes { return LimitExceeded }
if !VorbisRecognizes(input) { return Malformed }
if Chained(input) { return Unsupported }
reader := OggReader.{.input = input}
metadata: VorbisAudio
long_blocks: [64]bool
mode_bits: s64; mode_mask: s64
index: s64
previous: s64 // the previous audio packet's block size; 0 before the first
total: s64
granule: s64
while !reader.done {
code := NextPacket(*reader)
if code != OK { return code }
if reader.done { break }
packet := reader.packet[0:reader.packet_count]
if index == 0 {
code = Identification(packet, *metadata)
if code == OK && (!reader.page_last || reader.flags != 2 || reader.granule != 0) { code = Malformed }
} else if index == 1 {
code = CommentHeader(packet, comments, *metadata.comments)
if code == OK && reader.granule != 0 { code = Malformed }
} else if index == 2 {
code = SetupModes(packet, long_blocks[:], *metadata.modes)
// The first audio packet begins a new page.
if code == OK && (!reader.page_last || reader.granule != 0) { code = Malformed }
mode_bits = Ilog(metadata.modes - 1); mode_mask = (1 << mode_bits) - 1
} else {
if packet.count == 0 || (packet[0] & 1) != 0 { return Malformed }
mode := (cast(s64)packet[0] >> 1) & mode_mask
if mode >= metadata.modes { return Malformed }
size := cast(s64)(ifx long_blocks[mode] then metadata.long_block else metadata.short_block)
// A packet returns the frames between its window's center and
// the previous window's; the first returns none.
if previous != 0 { total += (previous + size) / 4 }
previous = size; metadata.packets += 1
if total > VorbisMaxStreamFrames { return LimitExceeded }
if reader.last_complete {
position := reader.granule
if (reader.flags & 4) == 0 {
// A timeline not starting at zero, or a gap.
if position != total { return Unsupported }
} else if position < granule || position > total { return Malformed }
granule = position
}
}
if code != OK { return code }
index += 1
}
if index < 4 || granule <= 0 { return Malformed }
metadata.frames = granule; metadata.end_trim = total - granule
<<info = metadata
return OK
}
Lower :: (byte: u8) -> u8 { return ifx byte >= 65 && byte <= 90 then byte + 32 else byte }
// One labelled line with control bytes shown as '?', so a comment cannot
// break the line-based output.
PrintText :: (label: string, text: string) {
line: Vec(u8)
for i: cast(s64)0..text.count - 1 { unused VecPush(line, ifx text[i] < 32 || text[i] == 127 then cast(u8)63 else text[i]) }
print("%", label)
print("%\n", TextView(VecSlice(line, 0, line.count)))
}
#scope_export
// Whether INPUT is exactly one Ogg Vorbis stream: whole pages of a single
// logical stream and nothing else, beginning with its first page, ending
// with its last, and starting with a Vorbis identification header. AUDIO
// then holds its channels, rate and length, the last page's granule
// position (streams start at zero, as encoders write them). Page CRCs are
// left to the decoder. AUDIO is zero when the answer is false.
VorbisProbe :: (input: []u8, audio: *VorbisAudio) -> bool {
<<audio = VorbisAudio.{}
at: s64 = 0
serial: u64 = 0
granule: s64 = 0
channels: s32 = 0
rate: s64 = 0
while at < input.count {
if input.count - at < 27 { return false }
if input[at] != 79 || input[at + 1] != 103 || input[at + 2] != 103 || input[at + 3] != 83 { return false }
if input[at + 4] != 0 { return false }
flags := input[at + 5]
first := at == 0
page_serial := Little(input, at + 14, 4)
if first { serial = page_serial } else if page_serial != serial { return false }
if ((flags & 2) != 0) != first { return false }
segments := cast(s64)input[at + 26]
if input.count - at - 27 < segments { return false }
body := at + 27 + segments
size: s64 = 0
for segment: cast(s64)0..segments - 1 { size += cast(s64)input[at + 27 + segment] }
if input.count - body < size { return false }
if first {
// The identification header is the first page's only packet.
if segments != 1 || size != 30 { return false }
if input[body] != 1 || input[body + 1] != 118 || input[body + 2] != 111 || input[body + 3] != 114 ||
input[body + 4] != 98 || input[body + 5] != 105 || input[body + 6] != 115 { return false }
if Little(input, body + 7, 4) != 0 || (input[body + 29] & 1) == 0 { return false }
channels = cast(s32)input[body + 11]
rate = cast(s64)Little(input, body + 12, 4)
if channels < 1 || rate < 1 || rate > 2147483647 { return false }
}
granule = cast(s64)Little(input, at + 6, 8)
at = body + size
if ((flags & 4) != 0) != (at == input.count) { return false }
}
if at == 0 || granule <= 0 { return false }
<<audio = VorbisAudio.{.channels = channels, .rate = cast(s32)rate, .frames = granule}
return true
// True when the first Ogg packet is a Vorbis identification header; Ogg
// Opus and other Ogg codecs are not.
VorbisRecognizes :: (input: []u8) -> bool {
if input.count < 28 || !Magic(input, 0, "OggS") { return false }
body := 27 + cast(s64)input[26]
return body < input.count && input[body] == 1 && Magic(input, body + 1, "vorbis")
}
// Validates every page and header of a single logical Ogg Vorbis stream
// before any decoder sees it, clearing INFO on failure. Truncation, CRC
// errors, bad headers, packets that are not audio, granule positions that
// disagree with the packets' block sizes and non-Vorbis input are Malformed;
// chained or multiplexed streams and a timeline not starting at zero are Unsupported.
VorbisInspect :: (input: []u8, info: *VorbisAudio) -> s32 {
<<info = VorbisAudio.{}
return Walk(input, info, null)
}
// VorbisInspect that also copies the comment header into COMMENTS, which is
// unchanged on failure.
VorbisInspectComments :: (input: []u8, info: *VorbisAudio, comments: *VorbisComments) -> s32 {
<<info = VorbisAudio.{}
copy: VorbisComments
code := Walk(input, info, *copy)
if code == OK {
VecSwap(comments.text, copy.text); VecSwap(comments.spans, copy.spans)
comments.vendor = copy.vendor
}
return code
}
VorbisCommentsFree :: (comments: *VorbisComments) {
VecFree(comments.text); VecFree(comments.spans); comments.vendor = 0
}
VorbisCommentCount :: (comments: *VorbisComments) -> s64 { return comments.spans.count / 2 }
// The returned strings borrow COMMENTS until it is freed or refilled.
VorbisVendor :: (comments: *VorbisComments) -> string {
return TextView(VecSlice(comments.text, 0, comments.vendor))
}
// Comment INDEX (0..VorbisCommentCount-1) as stored, "" when out of range.
VorbisComment :: (comments: *VorbisComments, index: s64) -> string {
if index < 0 || index >= VorbisCommentCount(comments) { return "" }
start := comments.spans[index * 2]
return TextView(VecSlice(comments.text, start, start + comments.spans[index * 2 + 1]))
}
// The value of the first comment whose field name equals FIELD, ignoring
// ASCII case (Vorbis field names are case-insensitive), or "".
VorbisCommentValue :: (comments: *VorbisComments, field: string) -> string {
for index: cast(s64)0..VorbisCommentCount(comments) - 1 {
start := comments.spans[index * 2]; size := comments.spans[index * 2 + 1]
if size > field.count && comments.text[start + field.count] == 61 {
same := true
for i: cast(s64)0..field.count - 1 { if Lower(comments.text[start + i]) != Lower(field[i]) { same = false } }
if same { return TextView(VecSlice(comments.text, start + field.count + 1, start + size)) }
}
}
return ""
}
VorbisSeconds :: (info: *VorbisAudio) -> float64 {
if info.rate <= 0 { return 0.0 }
return cast(float64)info.frames / cast(float64)info.rate
}
// One summary line, shared by the CLI and the Windows decode check.
VorbisPrintInfo :: (info: *VorbisAudio) {
if info.rate <= 0 { print("Vorbis: no stream\n"); return }
milliseconds := (info.frames * 1000 + info.rate / 2) / info.rate
fraction := milliseconds % 1000
print("Vorbis: % channels, % Hz, % frames, %.", info.channels, info.rate, info.frames, milliseconds / 1000)
if fraction < 100 { print("0") }
if fraction < 10 { print("0") }
print("% s, % bps nominal, blocks %/%, % modes, end trim %, % packets, % comments\n", fraction, info.nominal_bitrate, info.short_block, info.long_block, info.modes, info.end_trim, info.packets, info.comments)
}
// The vendor and each comment on its own line.
VorbisPrintComments :: (comments: *VorbisComments) {
PrintText("Vorbis vendor: ", VorbisVendor(comments))
for index: cast(s64)0..VorbisCommentCount(comments) - 1 { PrintText("Vorbis comment: ", VorbisComment(comments, index)) }
}
// Full portable validation with the stream's channels, rate and exact length.
// Metadata is cleared on failure; no native decoder is needed.
VorbisProbe :: (input: []u8, audio: *VorbisAudio) -> bool {
return VorbisInspect(input, audio) == OK
}
+161 -1
View File
@@ -15,6 +15,8 @@
// mirror fails the decode instead of passing unnoticed.
using Vectors :: #import "vec"
using Vorbis :: #import "vorbis"
using AudioTypes :: #import "audio_types"
Files :: #import "file";
// ogg_sync_state.
OggSyncState :: struct {
@@ -169,6 +171,10 @@ Info :: (file: *VorbisFile, link: s32) -> *VorbisInfo #foreign vorbisfile "ov_in
PcmTotal :: (file: *VorbisFile, link: s32) -> s64 #foreign vorbisfile "ov_pcm_total";
Read :: (file: *VorbisFile, buffer: *u8, length: s32, big_endian: s32, word: s32, signed: s32,
stream: *s32) -> isize #foreign vorbisfile "ov_read";
ReadFloat :: (file: *VorbisFile, pcm: ***float32, samples: s32, stream: *s32) -> isize #foreign vorbisfile "ov_read_float";
SeekPCM :: (file: *VorbisFile, frame: s64) -> s32 #foreign vorbisfile "ov_pcm_seek";
Allocate :: (count: usize, size: usize) -> *void #foreign libc "calloc";
Free :: (value: *void) #foreign libc "free";
CopyBytes :: (destination: *void, source: *void, count: usize) -> *void #foreign libc "memcpy";
GUARD :: 64
@@ -262,7 +268,7 @@ Decode :: (file: *VorbisFile, output: *Vec(u8), declared: VorbisAudio, audio: *V
samples: Vec(u8)
for at: cast(s64)0..bytes - 1 { VecPush(samples, cast(u8)0) }
if !ReadAll(file, VecSlice(samples, 0, bytes)) { return false }
<<audio = VorbisAudio.{.channels = info.channels, .rate = cast(s32)info.rate, .frames = frames}
<<audio = declared
VecSwap(samples, <<output)
return true
}
@@ -281,3 +287,157 @@ ReadAll :: (file: *VorbisFile, pcm: []u8) -> bool {
extra: [4096]u8
return Read(file, *extra[0], 4096, 0, 2, 1, *stream) == 0
}
// Incremental state uses the same guarded libvorbisfile ABI and callbacks as
// whole-file decode. Borrowed input stays unchanged until close. Do not copy
// a live decoder or call it concurrently.
DecoderState :: struct { guarded: Guarded; memory: Memory }
#scope_export
// Single-owner state over borrowed input, or owned input opened from a file.
// Keep borrowed bytes alive and unchanged until close. No concurrent calls.
VorbisDecoder :: struct {
state: *void
info: VorbisAudio
comments: VorbisComments
position: s64
owned: Vec(u8)
}
VorbisDecoderClose :: (decoder: *VorbisDecoder) {
if decoder.state != null {
state := cast(*DecoderState)decoder.state
unused Clear(*state.guarded.file)
Free(decoder.state)
}
VorbisCommentsFree(*decoder.comments); VecFree(decoder.owned)
decoder.state = null; decoder.info = .{}; decoder.position = 0
}
VorbisDecoderOpen :: (decoder: *VorbisDecoder, input: []u8, max_frames: s64) -> s32 {
if decoder.state != null || max_frames <= 0 || max_frames > VorbisMaxStreamFrames { return Invalid }
audio: VorbisAudio
comments: VorbisComments
code := VorbisInspectComments(input, *audio, *comments)
if code != OK { return code }
if audio.frames > max_frames { return LimitExceeded }
state := cast(*DecoderState)Allocate(1, size_of(DecoderState))
if state == null { return AllocationFailed }
state.memory = .{.data = *input[0], .count = input.count}
for index: 0..GUARD - 1 { state.guarded.guard[index] = cast(u8)GUARD_BYTE }
callbacks: VorbisCallbacks
callbacks.read = MemoryRead; callbacks.seek = MemorySeek; callbacks.close = MemoryClose; callbacks.tell = MemoryTell
file := *state.guarded.file
if OpenCallbacks(cast(*void)*state.memory, file, null, 0, callbacks) != 0 { Free(cast(*void)state); return Malformed }
info := Info(file, -1)
if !GuardIntact(*state.guarded) || Streams(file) != 1 || info == null ||
info.channels != audio.channels || info.rate != cast(isize)audio.rate || PcmTotal(file, -1) != audio.frames {
unused Clear(file); Free(cast(*void)state); return Malformed
}
decoder.state = cast(*void)state; decoder.info = audio; decoder.position = 0
VecSwap(decoder.comments.text, comments.text); VecSwap(decoder.comments.spans, comments.spans)
decoder.comments.vendor = comments.vendor
return OK
}
VorbisDecoderOpenFile :: (decoder: *VorbisDecoder, path: string, max_frames: s64) -> s32 {
if decoder.state != null || max_frames <= 0 || max_frames > VorbisMaxStreamFrames { return Invalid }
VecFree(decoder.owned)
if !Files.ReadFileInto(path, *decoder.owned) { VecFree(decoder.owned); return IOFailure }
if decoder.owned.count > MaxBytes { VecFree(decoder.owned); return LimitExceeded }
code := VorbisDecoderOpen(decoder, decoder.owned[:], max_frames)
if code != OK { VecFree(decoder.owned) }
return code
}
// Fills whole interleaved frames; OK with zero frames denotes the logical end.
// Discard the output on error, then seek or close.
VorbisDecoderRead :: (decoder: *VorbisDecoder, output: []float32, frames: *s64) -> s32 {
<<frames = 0
if decoder.state == null || output.count <= 0 || output.count % decoder.info.channels != 0 { return Invalid }
state := cast(*DecoderState)decoder.state
if !GuardIntact(*state.guarded) { return Malformed }
channels := cast(s64)decoder.info.channels
wanted := output.count / channels
left := decoder.info.frames - decoder.position
if wanted > left { wanted = left }
done: s64
while done < wanted {
request := wanted - done
if request > 65536 { request = 65536 }
planes: **float32; link: s32
got := cast(s64)ReadFloat(*state.guarded.file, *planes, cast(s32)request, *link)
if got <= 0 || got > request || link != 0 || !GuardIntact(*state.guarded) { return Malformed }
for frame: 0..got - 1 {
for channel: 0..channels - 1 { output[(done + frame) * channels + channel] = planes[channel][frame] }
}
done += got
}
decoder.position += done
if decoder.position == decoder.info.frames {
planes: **float32; link: s32
if ReadFloat(*state.guarded.file, *planes, 1, *link) != 0 || !GuardIntact(*state.guarded) { return Malformed }
}
<<frames = done
return OK
}
VorbisDecoderReadS16 :: (decoder: *VorbisDecoder, output: []s16, frames: *s64) -> s32 {
<<frames = 0
if decoder.state == null || output.count <= 0 || output.count % decoder.info.channels != 0 { return Invalid }
channels := cast(s64)decoder.info.channels
wanted := output.count / channels
if wanted > decoder.info.frames - decoder.position { wanted = decoder.info.frames - decoder.position }
scratch: [4096]float32
done: s64
while done < wanted {
count := wanted - done
if count > 4096 / channels { count = 4096 / channels }
got: s64
code := VorbisDecoderRead(decoder, scratch[0:count * channels], *got)
if code != OK { return code }
if got != count { return Malformed }
for index: cast(s64)0..got * channels - 1 {
value := cast(float64)scratch[index]
output[done * channels + index] = ifx value != value then cast(s16)0 else Pcm16(value)
}
done += got
}
<<frames = done
return OK
}
VorbisDecoderSeek :: (decoder: *VorbisDecoder, frame: s64) -> s32 {
if decoder.state == null || frame < 0 || frame > decoder.info.frames { return Invalid }
state := cast(*DecoderState)decoder.state
if !GuardIntact(*state.guarded) || SeekPCM(*state.guarded.file, frame) != 0 || !GuardIntact(*state.guarded) { return Malformed }
decoder.position = frame
return OK
}
VorbisDecoderRewind :: (decoder: *VorbisDecoder) -> s32 { return VorbisDecoderSeek(decoder, 0) }
// Whole-file float output is unchanged on error.
VorbisDecodeFloat :: (input: []u8, max_frames: s64, output: *PCM) -> s32 {
decoder: VorbisDecoder
code := VorbisDecoderOpen(*decoder, input, max_frames)
if code != OK { return code }
defer VorbisDecoderClose(*decoder)
if decoder.info.frames > MaxFrames { return LimitExceeded }
samples: Vec(float32)
count := decoder.info.frames * decoder.info.channels
if !VecResize(samples, count) { return AllocationFailed }
frames: s64
code = VorbisDecoderRead(*decoder, samples[:], *frames)
if code != OK { return code }
output.rate = decoder.info.rate; output.channels = decoder.info.channels
SwapSamples(output, *samples)
return OK
}
VorbisDecodeS16 :: (input: []u8, max_frames: s64, output: *Vec(s16), info: *VorbisAudio) -> s32 {
decoder: VorbisDecoder
code := VorbisDecoderOpen(*decoder, input, max_frames)
if code != OK { return code }
defer VorbisDecoderClose(*decoder)
if decoder.info.frames > MaxFrames { return LimitExceeded }
samples: Vec(s16)
count := decoder.info.frames * decoder.info.channels
if !VecResize(samples, count) { return AllocationFailed }
frames: s64
code = VorbisDecoderReadS16(*decoder, samples[:], *frames)
if code != OK { return code }
<<info = decoder.info
VecSwap(samples, <<output)
return OK
}
+39
View File
@@ -0,0 +1,39 @@
// Device test for both Android PCM backends. Run through audio-android-test;
// serial is explicit so this never selects another phone.
#import "native_test"
#import "check_support"
#import "std/byte_text_linux"
using Vectors :: #import "std/vec"
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 5 { print("usage: audio_android_cases ZIRAN BUILD_FOLDER NDK SERIAL\n"); return 2 }
test := NativeStart(argc, argv, "audio-android-")
if test.failed { return 1 }
defer NativeCleanup(*test)
ndk := TextFromCString(argv[3]); serial := TextFromCString(argv[4])
if serial == "" { return 2 }
generated := CheckPath(test.work, "c")
generate := string.[test.ziran, "build", "--target=c", "--root", CheckPath(test.repo, "tests"),
"--define", "ANDROID_BUILD", "--define", "__arm__", "--target-os", "android", "--target-cpu", "none",
"-o", generated, CheckPath(test.repo, "tests/audio_sink_cases.zi")]
unused NativeRun(*test, generate[:])
client := CheckPath(test.work, "contract")
compile: Vec(string)
compiler := CheckPath(ndk, "toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi21-clang")
flags := string.[compiler, "-std=c11", "-O2", CheckConcat("-I", generated)]
for flag: flags { VecPush(compile, flag) }
files := NativeFiles(generated, ".c")
for file: files { VecPush(compile, file) }
options := string.["-ldl", "-lm", "-o", client]
for option: options { VecPush(compile, option) }
unused NativeRun(*test, compile[:])
state := string.["adb", "-s", serial, "get-state"]; unused NativeRun(*test, state[:])
destination := "/data/local/tmp/ziran-audio-contract"
push := string.["adb", "-s", serial, "push", client, destination]; unused NativeRun(*test, push[:])
mode := string.["adb", "-s", serial, "shell", "chmod", "700", destination]; unused NativeRun(*test, mode[:])
run := string.["adb", "-s", serial, "shell", destination]; unused NativeRun(*test, run[:])
if test.failed { return 1 }
print("armv7 Android PCM playback contract passed on %\n", serial)
return 0
}
+117
View File
@@ -0,0 +1,117 @@
// Audio stays independent of Kryon, windows and physical output devices.
#import "native_test"
#import "check_support"
#import "check_cache"
#import "std/file_tree_linux"
#import "std/environment_linux"
#import "std/text_tools"
#import "std/option"
using Vectors :: #import "std/vec"
Compile :: (test: *NativeTest, source: string, name: string, fake: bool, sdl: bool, codecs: bool = false) -> string {
generated := CheckPath(test.work, CheckConcat(name, "-c"))
arguments: Vec(string)
command := string.[test.ziran, "build", "--target=c", "--root", CheckPath(test.repo, "tests")]
for argument: command { VecPush(arguments, argument) }
if fake { VecPush(arguments, "--define"); VecPush(arguments, "ZIRAN_AUDIO_FAKE"); VecPush(arguments, "--define"); VecPush(arguments, "ANDROID_BUILD") }
VecPush(arguments, "-o"); VecPush(arguments, generated); VecPush(arguments, CheckPath(test.repo, source))
unused NativeRun(test, arguments[:])
client := CheckPath(test.work, name)
compile: Vec(string)
flags := string.[NativeCompiler(), "-std=c11", "-O1", CheckConcat("-I", generated)]
for flag: flags { VecPush(compile, flag) }
files := NativeFiles(generated, ".c", true)
for file: files { VecPush(compile, file) }
if fake { VecPush(compile, "-Wl,--export-dynamic"); VecPush(compile, "-Wl,--wrap=dlopen") }
if sdl { VecPush(compile, "-lSDL2"); VecPush(compile, "-Wl,--wrap=SDL_InitSubSystem") }
if codecs {
VecPush(compile, CheckPath(test.repo, "build/audio/native/libziran_mp3.a"))
VecPush(compile, "-l:libvorbisfile.so.3")
}
options := string.["-pthread", "-ldl", "-lm", "-o", client]
for option: options { VecPush(compile, option) }
unused NativeRun(test, compile[:])
return client
}
CodecTest :: (test: *NativeTest) {
archive := string.["make", "audio-mp3"]; unused NativeRun(test, archive[:])
client := Compile(test, "tests/audio_decode_cases.zi", "decode", false, false, true)
mp3 := CheckPath(test.work, "tone.mp3"); vorbis := CheckPath(test.work, "tone.ogg")
names := string.[mp3, vorbis]; codecs := string.["libmp3lame", "libvorbis"]
for index: 0..1 {
generate := string.["ffmpeg", "-v", "error", "-y", "-threads", "1", "-filter_threads", "1", "-f", "lavfi",
"-i", "sine=frequency=440:sample_rate=48000:duration=0.2", "-c:a", codecs[index], names[index]]
unused NativeRun(test, generate[:])
}
run := string.[client, mp3, vorbis]; unused NativeRun(test, run[:])
vorbis_client := Compile(test, "tests/audio_vorbis_cases.zi", "vorbis", false, false, true)
inspect := string.[vorbis_client]; unused NativeRun(test, inspect[:])
}
WebTest :: (test: *NativeTest) {
emcc := EnvironmentText("EMCC")
if emcc == "" { emcc = CheckExecutable("emcc") }
if emcc == "" { emcc = CheckPath(EnvironmentText("HOME"), "emsdk/upstream/emscripten/emcc") }
generated := CheckPath(test.work, "web-c")
generate := string.[test.ziran, "build", "--target=c", "--target-os", "web", "--target-cpu", "wasm32",
"--define", "PLATFORM_WEB", "--root", CheckPath(test.repo, "tests"), "-o", generated,
CheckPath(test.repo, "tests/audio_web_cases.zi")]
unused NativeRun(test, generate[:])
compile: Vec(string)
flags := string.[emcc, "-std=c11", "-O1", CheckConcat("-I", generated)]
for flag: flags { VecPush(compile, flag) }
files := NativeFiles(generated, ".c", true)
for file: files { VecPush(compile, file) }
options := string.["--js-library", CheckPath(test.repo, "web/ziran_web.js"), "-sASYNCIFY=1", "-sEXIT_RUNTIME=1",
"-sSTACK_SIZE=1048576", "-sALLOW_MEMORY_GROWTH=1", "-sENVIRONMENT=web", "-o", CheckPath(test.work, "audio-web.js")]
for option: options { VecPush(compile, option) }
unused NativeRun(test, compile[:])
html := CheckPath(test.work, "audio-web.html")
unused NativeWrite(test, html, "<!doctype html><html><body>pending<script src=audio-web.js></script></body></html>")
browser := EnvironmentText("CHROMIUM")
if browser == "" { browser = CheckExecutable("chromium") }
if browser == "" { browser = CheckExecutable("google-chrome") }
if browser == "" { browser = CheckExecutable("chromium-browser") }
if !NativeAssert(test, browser != "", "WebAudio tests require Chromium or Chrome") { return }
run := string.[browser, "--headless", "--no-sandbox", "--disable-gpu", "--autoplay-policy=no-user-gesture-required",
"--allow-file-access-from-files", "--virtual-time-budget=5000", "--dump-dom",
CheckConcat("--user-data-dir=", CheckPath(test.work, "browser")), CheckConcat("file://", html)]
browser_temp := CheckPath(test.repo, "build/audio/tmp")
if !NativeAssert(test, CreateDirectories(browser_temp), "create browser temporary directory") { return }
VecPush(test.environment, CheckConcat("TMPDIR=", browser_temp))
output := NativeRun(test, run[:])
unused VecPop(test.environment)
unused NativeAssert(test, TextContains(output.output, "<body>audio web sink contract passed</body>"), "WebAudio playback, lifecycle or handle cleanup failed")
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
test := NativeStart(argc, argv, "audio-")
if test.failed { return 1 }
defer NativeCleanup(*test)
mixer := Compile(*test, "tests/spec/audio_test.zi", "mixer", false, false)
mix := string.[mixer]; unused NativeRun(*test, mix[:])
if test.failed { return 1 }
android := Compile(*test, "tests/audio_sink_cases.zi", "android", true, false)
contract := string.[android]; unused NativeRun(*test, contract[:])
if test.failed { return 1 }
sdl := Compile(*test, "tests/audio_sink_sdl_cases.zi", "sdl", false, true)
VecPush(test.environment, "SDL_AUDIODRIVER=ziran-unavailable-audio-driver")
missing := string.["xvfb-run", "-a", sdl, "unavailable"]
unused NativeRun(*test, missing[:])
unused VecPop(test.environment)
VecPush(test.environment, "SDL_AUDIODRIVER=disk")
VecPush(test.environment, "SDL_DISKAUDIODELAY=10")
path := CheckPath(test.work, "sink.raw")
VecPush(test.environment, CheckConcat("SDL_DISKAUDIOFILE=", path))
disk := string.["xvfb-run", "-a", sdl, path]
unused NativeRun(*test, disk[:])
if test.failed { return 1 }
CodecTest(*test)
if test.failed { return 1 }
WebTest(*test)
if test.failed { return 1 }
print("audio mixer, Android, SDL and WebAudio sink local tests passed\n")
return 0
}
+49
View File
@@ -0,0 +1,49 @@
// The same mixer source contract for whole-file and incremental MP3/Vorbis.
#import "std/audio"
#import "std/audio_decode_mp3"
#import "std/audio_decode_vorbis"
#import "std/byte_text_linux"
Near :: (a: float32, b: float32) -> bool { return a - b < .0001 && a - b > -.0001 }
Check :: (path: string) -> s32 {
whole := AudioLoadFile(path, false)
music := AudioLoadFile(path, true)
if whole.slot < 0 || music.slot < 0 { return 1 }
defer { AudioUnload(whole); AudioUnload(music) }
if AudioLength(music) < .1 || AudioLength(music) != AudioLength(whole) { return 2 }
expected: [8192]float32
output: [1024]float32
if !AudioPlay(whole) { return 3 }
AudioRender(expected[:], 4096)
AudioStop(whole)
if !AudioPlay(music) { return 4 }
AudioRender(output[:], 512)
for index: 0..1023 { if !Near(output[index], expected[index]) { return 5 } }
if !AudioSeek(music, 1024.0 / 48000.0) { return 6 }
AudioRender(output[:], 512)
for index: 0..1023 { if !Near(output[index], expected[2048 + index]) { return 7 } }
AudioPause(music)
if !AudioSeek(music, .01) || AudioState(music) != .Paused { return 8 }
AudioRender(output[:], 512)
if output[0] != 0.0 || AudioPosition(music) < .00999 || AudioPosition(music) > .01001 { return 9 }
if AudioSeek(music, -.1) || AudioSeek(music, AudioLength(music) + 1.0) { return 10 }
if !AudioSeek(music, AudioLength(music)) { return 11 }
AudioResume(music)
AudioRender(output[:], 512)
if AudioState(music) != .Finished || output[0] != 0.0 { return 12 }
if !AudioSeek(music, 0.0) || AudioState(music) != .Paused { return 13 }
AudioResume(music)
AudioRender(output[:], 512)
for index: 0..1023 { if !Near(output[index], expected[index]) { return 14 } }
return 0
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 3 { return 1 }
for index: 1..2 {
result := Check(TextFromCString(argv[index]))
if result != 0 { print("audio decoder % failed: %\n", index, result); return result }
}
print("MP3 and Vorbis stream/seek contracts passed\n")
return 0
}
+104
View File
@@ -0,0 +1,104 @@
// Same sink contract with deterministic AAudio on the host and both real
// NDK backends on the armv7 Moto. No window, JNI, or raylib is involved.
Sink :: #import "std/audio_sink";
AAudio :: #import "std/audio_android_aaudio";
OpenSL :: #import "std/audio_android_opensl";
Buffer :: #import "std/audio_android_buffer";
Mixer :: #import "std/audio";
#import "std/timer_linux"
#if #defined(ZIRAN_AUDIO_FAKE) {
#import, file "audio_sink_fake.zi";
}
frames_seen: s64;
signal_seen: bool;
Tap :: (samples: []float32, frames: s64) {
frames_seen += frames
for index: 0..frames * 2 - 1 {
if samples[index] > .001 || samples[index] < -.001 { signal_seen = true }
}
}
Fail :: (code: s32) -> s32 { print("Android audio contract failed: %\n", code); return code }
Ready :: (opensl: bool) -> bool { return ifx opensl then OpenSL.Ready() else Sink.AudioSinkReady() }
Open :: (opensl: bool) -> bool {
if opensl { return OpenSL.Open() }
unused Sink.AudioSinkOpen()
deadline := MonotonicMilliseconds() + 3000
while Sink.AudioSinkPending() && MonotonicMilliseconds() < deadline { unused SleepMilliseconds(1) }
return Sink.AudioSinkReady()
}
Close :: () { Sink.AudioSinkClose(); OpenSL.Close() }
Run :: (opensl: bool) -> s32 {
if Ready(opensl) { return Fail(1) }
if !Open(opensl) { return Fail(3) }
if !Ready(opensl) { return Fail(4) }
// Reopening is idempotent, retains voices, and starts no second device.
if !opensl && !Sink.AudioSinkOpen() { return Fail(5) }
Mixer.AudioUseTap(Tap)
voice := Mixer.AudioOpenStream(48000, 2, 512)
if voice.slot < 0 || !Mixer.AudioPlay(voice) { return Fail(6) }
block: [1024]s16
for index: 0..511 { block[index * 2] = 1024; block[index * 2 + 1] = -1024 }
Mixer.AudioSetGain(voice, .25)
if !Mixer.AudioStreamSubmit(voice, block[:]) { return Fail(7) }
#if #defined(ZIRAN_AUDIO_FAKE) {
samples: [1024]float32
if fake_pull(null, null, cast(*void)*samples[0], 512) != 0 { return Fail(8) }
if samples[0] < .007 || samples[0] > .009 || samples[1] > -.007 { return Fail(9) }
// The PCM payload was copied; underruns produce silence.
unused fake_pull(null, null, cast(*void)*samples[0], 512)
if samples[0] != 0.0 || samples[1] != 0.0 { return Fail(10) }
Mixer.AudioPause(voice)
unused fake_pull(null, null, cast(*void)*samples[0], 512)
if samples[0] != 0.0 { return Fail(11) }
Mixer.AudioResume(voice)
} else {
unused SleepMilliseconds(250)
}
Buffer.Enter()
heard := frames_seen > 0 && signal_seen
Buffer.Leave()
if !heard || !Mixer.AudioStreamWritable(voice) { return Fail(12) }
Close()
Close()
if Ready(opensl) { return Fail(13) }
// No callback remains after close. Mixer operations still work, and a
// subsequent open retains the voice and its queued PCM.
before := frames_seen
unused SleepMilliseconds(30)
if frames_seen != before { return Fail(14) }
if !Mixer.AudioStreamSubmit(voice, block[:]) { return Fail(15) }
if !Open(opensl) { return Fail(17) }
Mixer.AudioUnload(voice)
Close()
return 0
}
#program_export
main :: () -> s32 {
Sink.AudioSinkClose()
#if #defined(ZIRAN_AUDIO_FAKE) {
for stage: 1..4 {
fake_stage = cast(s32)stage
if Open(false) || Sink.AudioSinkReady() { return Fail(20 + cast(s32)stage) }
Sink.AudioSinkClose()
}
fake_stage = 0
}
result := Run(false)
if result != 0 { return result }
#if #defined(ZIRAN_AUDIO_FAKE) {
if fake_creates != fake_deletes + 1 || fake_rate != 48000 || fake_channels != 2 || fake_format != 2 || fake_direction != 0 { return Fail(30) }
if !Open(false) { return Fail(31) }
fake_error(null, null, -899)
if Sink.AudioSinkReady() || !Open(false) { return Fail(35) }
Sink.AudioSinkClose()
} else {
frames_seen = 0; signal_seen = false
result = Run(true)
if result != 0 { return result }
}
print("Android audio sink contract passed\n")
return 0
}
+68
View File
@@ -0,0 +1,68 @@
// Deterministic AAudio ABI fixture. Only dlopen is wrapped; dlsym resolves
// these exported Ziran procedures exactly as it resolves the NDK library.
#import "std/byte_text_linux"
FakePull :: #type (*void, *void, *void, s32) -> s32 #c_call;
FakeError :: #type (*void, *void, s32) -> void #c_call;
fake_pull: FakePull;
fake_error: FakeError;
fake_rate: s32;
fake_channels: s32;
fake_format: s32;
fake_direction: s32;
fake_stage: s32;
fake_creates: s32;
fake_deletes: s32;
fake_closes: s32;
fake_starts: s32;
fake_token: u64;
c :: #system_library "c";
RealOpen :: (name: *u8, flags: s32) -> *void #foreign c "__real_dlopen";
#program_export
__wrap_dlopen :: (name: *u8, flags: s32) -> *void {
if TextFromCString(name) == "libaaudio.so" { return RealOpen(null, flags) }
return null
}
#program_export
AAudio_createStreamBuilder :: (output: **void) -> s32 {
fake_creates += 1
if fake_stage == 1 { return -1 }
output[0] = cast(*void)*fake_token
return 0
}
#program_export
AAudioStreamBuilder_delete :: (builder: *void) -> s32 { unused builder; fake_deletes += 1; return 0 }
#program_export
AAudioStreamBuilder_setSampleRate :: (builder: *void, value: s32) { unused builder; fake_rate = value }
#program_export
AAudioStreamBuilder_setChannelCount :: (builder: *void, value: s32) { unused builder; fake_channels = value }
#program_export
AAudioStreamBuilder_setFormat :: (builder: *void, value: s32) { unused builder; fake_format = value }
#program_export
AAudioStreamBuilder_setDirection :: (builder: *void, value: s32) { unused builder; fake_direction = value }
#program_export
AAudioStreamBuilder_setDataCallback :: (builder: *void, callback: FakePull, argument: *void) {
unused builder; unused argument; fake_pull = callback
}
#program_export
AAudioStreamBuilder_setErrorCallback :: (builder: *void, callback: FakeError, argument: *void) {
unused builder; unused argument; fake_error = callback
}
#program_export
AAudioStreamBuilder_openStream :: (builder: *void, output: **void) -> s32 {
unused builder
if fake_stage == 2 { return -1 }
output[0] = cast(*void)*fake_token
return 0
}
#program_export
AAudioStream_getSampleRate :: (stream: *void) -> s32 { unused stream; return ifx fake_stage == 3 then 44100 else fake_rate }
#program_export
AAudioStream_getChannelCount :: (stream: *void) -> s32 { unused stream; return fake_channels }
#program_export
AAudioStream_getFormat :: (stream: *void) -> s32 { unused stream; return fake_format }
#program_export
AAudioStream_requestStart :: (stream: *void) -> s32 { unused stream; fake_starts += 1; return ifx fake_stage == 4 then -1 else 0 }
#program_export
AAudioStream_requestStop :: (stream: *void) -> s32 { unused stream; return 0 }
#program_export
AAudioStream_close :: (stream: *void) -> s32 { unused stream; fake_closes += 1; return 0 }
+80
View File
@@ -0,0 +1,80 @@
// SDL lifecycle without a physical device. The driver selects an unavailable
// backend first, then SDL's disk backend on a private display.
#import "std/audio"
#import "std/audio_sink"
#import "std/byte_text_linux"
#import "std/file"
#import "std/timer_linux"
#import "std/vec"
captured: [262144]float32;
captured_count: s64;
Tap :: (samples: []float32, frames: s64) {
for index: 0..frames * 2 - 1 {
if captured_count < 262144 { captured[captured_count] = samples[index]; captured_count += 1 }
}
}
sdl :: #system_library "SDL2";
RealInit :: (flags: u32) -> s32 #foreign sdl "__real_SDL_InitSubSystem";
opens: s64;
#program_export
__wrap_SDL_InitSubSystem :: (flags: u32) -> s32 {
opens += 1
unused SleepMilliseconds(150) // A slow provider must never stall the caller.
return RealInit(flags)
}
Await :: () -> bool {
unused AudioSinkOpen()
deadline := MonotonicMilliseconds() + 3000
while AudioSinkPending() && MonotonicMilliseconds() < deadline { unused SleepMilliseconds(1) }
return AudioSinkReady()
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if argc != 2 { return 1 }
path := TextFromCString(argv[1])
if path == "unavailable" {
start := MonotonicNanoseconds()
if AudioSinkOpen() { return 2 }
if MonotonicNanoseconds() - start > 50000000 { return 13 }
for attempt: 0..99 { if AudioSinkOpen() { return 2 } }
deadline := MonotonicMilliseconds() + 3000
while AudioSinkPending() && MonotonicMilliseconds() < deadline { unused SleepMilliseconds(1) }
if AudioSinkPending() || AudioSinkReady() || !AudioSinkUnavailable() { return 14 }
start = MonotonicNanoseconds()
for attempt: 0..99 { if AudioSinkOpen() { return 2 } }
if MonotonicNanoseconds() - start > 50000000 || opens != 1 { return 15 }
AudioSinkClose(); AudioSinkClose()
print("unavailable SDL device failed cleanly\n")
return 0
}
AudioUseTap(Tap)
stream := AudioOpenStream(48000, 2, 512)
if stream.slot < 0 || !AudioPlay(stream) { return 3 }
block: [1024]s16
for frame: 0..511 { block[frame * 2] = 8192; block[frame * 2 + 1] = -8192 }
if !AudioStreamSubmit(stream, block[:]) { return 4 }
if !Await() || !AudioSinkOpen() || !AudioSinkReady() { return 5 }
unused SleepMilliseconds(150)
AudioSinkClose(); AudioSinkClose()
if AudioSinkReady() { return 6 }
before := captured_count
unused SleepMilliseconds(30)
if captured_count != before { return 7 }
bytes: Vec(u8)
defer VecFree(bytes)
if !ReadFileInto(path, *bytes) || bytes.count % 4 != 0 { return 8 }
disk := cast(*float32)*bytes[0]
count := bytes.count / 4
first: s64
while first < count && disk[first] == 0.0 { first += 1 }
if first >= count || captured_count < 1024 || disk[first] != .25 || disk[first + 1] != -.25 { return 9 }
compared := count - first
if compared > captured_count { compared = captured_count }
if compared < 1024 { return 10 }
for index: 0..compared - 1 { if disk[first + index] != captured[index] { return 11 } }
if !AudioStreamSubmit(stream, block[:]) || !Await() { return 12 }
AudioSinkClose(); AudioUnload(stream)
print("SDL sink contract passed\n")
return 0
}
+365
View File
@@ -0,0 +1,365 @@
// Native Ogg Vorbis contracts over tests/fixtures/vorbis (see its README for
// the FFmpeg commands that made them): decode against FFmpeg's reference PCM,
// exact durations from the final granule position, streaming = whole-file
// output, exact seeks, comments, the Opus path left to Opus, and errors
// (never crashes) for truncated, corrupted, garbage, chained, synthetic and
// non-Vorbis input. Run from the package root.
#import "std/audio_types"
#import "std/vec"
#import "std/file"
#import "std/math"
#import "std/byte_text_linux"
#import "std/audio_wav"
#import "std/ogg"
#import "std/vorbis"
#import "std/vorbis_linux"
#import "audio_vorbis_fixture"
#scope_file
// Largest decoder difference against FFmpeg's PCM16 reference, in PCM16
// steps, and the largest RMS difference. The reference itself is rounded to
// 16 bits (0.5 steps); measured: at most 0.501 steps, RMS 0.29.
ToleranceSteps :: 1.0
ToleranceRms :: 0.35
Fail :: (code: s32, name: string) -> s32 { print("vorbis contract % failed: %\n", code, name); return code }
// Fixture paths are built in caller-owned bytes, so sanitizer runs see no
// retained strings.
PathInto :: (path: *Vec(u8), name: string, extension: string) {
parts: [4]string = .["tests/fixtures/vorbis/", name, ".", extension]
for part: parts { for i: cast(s64)0..part.count - 1 { unused VecPush(<<path, part[i]) } }
}
Load :: (name: string, extension: string, bytes: *Vec(u8)) -> bool {
path: Vec(u8)
PathInto(*path, name, extension)
return ReadFileInto(TextFromBytes(VecSlice(path, 0, path.count)), bytes)
}
Copy :: (from: []u8, to: *Vec(u8)) -> bool {
for byte: from { if !VecPush(<<to, byte) { return false } }
return true
}
Same :: (a: []float32, b: []float32) -> bool {
if a.count != b.count { return false }
for i: cast(s64)0..a.count - 1 { if a[i] != b[i] { return false } }
return true
}
// Reads the rest of the stream in irregular chunks into OUTPUT.
Stream :: (decoder: *VorbisDecoder, output: *Vec(float32)) -> s32 {
sizes: [6]s64 = .[997, 1, 1024, 4093, 7, 128]
scratch: [8186]float32
channels := cast(s64)decoder.info.channels
turn: s64
while true {
frames: s64
code := VorbisDecoderRead(decoder, scratch[0:sizes[turn % 6] * channels], *frames)
if code != OK { return code }
if frames == 0 { return OK }
for i: cast(s64)0..frames * channels - 1 { if !VecPush(<<output, scratch[i]) { return AllocationFailed } }
turn += 1
}
return OK
}
Random :: (state: *u64) -> u8 {
<<state = <<state * 6364136223846793005 + 1442695040888963407
return cast(u8)(<<state >> 56)
}
// Page bodies [start, end) after the first SKIP pages, and a CRC refresh, so
// corrupted payloads pass the container checks and reach libvorbisfile.
Bodies :: (bytes: []u8, skip: s64, ranges: *Vec(s64)) {
at: s64; page: s64
while bytes.count - at >= 27 {
segments := cast(s64)bytes[at + 26]
size: s64
for i: cast(s64)0..segments - 1 { size += bytes[at + 27 + i] }
if page >= skip && size > 0 { unused VecPush(<<ranges, at + 27 + segments); unused VecPush(<<ranges, at + 27 + segments + size) }
at += 27 + segments + size; page += 1
}
}
Recrc :: (bytes: []u8) {
at: s64
while bytes.count - at >= 27 {
segments := cast(s64)bytes[at + 26]
size: s64
for i: cast(s64)0..segments - 1 { size += bytes[at + 27 + i] }
end := at + 27 + segments + size
PutLittle(bytes, at + 22, 4, OggCRC(bytes[at:end]))
at = end
}
}
Fixtures :: () -> s32 {
names: [5]string = .["stereo", "mono", "rate22", "rate48", "comments"]
rates: [5]s32 = .[44100, 44100, 22050, 48000, 32000]
channels: [5]s32 = .[2, 1, 2, 2, 1]
// The final granule positions; ffprobe's duration_ts and libvorbisfile's
// ov_pcm_total report the same.
lengths: [5]s64 = .[13230, 13230, 6615, 14400, 9600]
for index: 0..4 {
name := names[index]
bytes: Vec(u8)
reference_bytes: Vec(u8)
if !Load(name, "ogg", *bytes) || !Load(name, "wav", *reference_bytes) { return Fail(100, name) }
input := VecSlice(bytes, 0, bytes.count)
reference: PCM
if WavDecode(VecSlice(reference_bytes, 0, reference_bytes.count), MaxFrames, *reference) != OK { return Fail(101, name) }
if !VorbisRecognizes(input) { return Fail(102, name) }
info: VorbisAudio
if VorbisInspect(input, *info) != OK { return Fail(103, name) }
if info.rate != rates[index] || info.channels != channels[index] || info.frames != lengths[index] || reference.rate != info.rate || reference.channels != info.channels { print("% frames % rate %\n", name, info.frames, info.rate); return Fail(104, name) }
if info.packets < 2 || info.modes < 1 || info.short_block < 64 || info.long_block < info.short_block || info.end_trim < 0 || info.end_trim >= info.long_block || info.nominal_bitrate <= 0 { return Fail(105, name) }
// FFmpeg's Ogg demuxer counts the discarded first packet, so its
// decode ends up to one long block away from the granule length.
reference_frames := reference.samples.count / reference.channels
if reference_frames - info.frames > info.long_block || info.frames - reference_frames > info.long_block { return Fail(106, name) }
// Whole-file float decode against the reference within tolerance,
// over the frames both decodes hold.
decoded: PCM
if VorbisDecodeFloat(input, info.frames - 1, *decoded) != LimitExceeded || decoded.samples.count != 0 { return Fail(107, name) }
if VorbisDecodeFloat(input, MaxFrames, *decoded) != OK || decoded.rate != info.rate || decoded.channels != info.channels || decoded.samples.count != info.frames * info.channels { return Fail(108, name) }
shared := ifx reference_frames < info.frames then reference_frames else info.frames
worst: float64; squares: float64
for i: cast(s64)0..shared * info.channels - 1 {
difference := (cast(float64)decoded.samples[i] - cast(float64)reference.samples[i]) * 32768.0
if difference < 0.0 { difference = -difference }
if difference > worst { worst = difference }
squares += difference * difference
}
mean_square := squares / cast(float64)(shared * info.channels)
if worst > ToleranceSteps || mean_square > ToleranceRms * ToleranceRms { print("% worst % mean square %\n", name, worst, mean_square); return Fail(109, name) }
print("vorbis %: % frames at % Hz x%, % packets, end trim %, max difference % PCM16 steps, mean square % against FFmpeg over % frames\n", name, info.frames, info.rate, info.channels, info.packets, info.end_trim, worst, mean_square, shared)
// Streaming in irregular chunks matches the whole-file samples, and
// so does a rewind followed by a second pass.
decoder: VorbisDecoder
if VorbisDecoderOpen(*decoder, input, MaxFrames) != OK { return Fail(110, name) }
streamed: Vec(float32)
if Stream(*decoder, *streamed) != OK || !Same(VecSlice(streamed, 0, streamed.count), VecSlice(decoded.samples, 0, decoded.samples.count)) { VorbisDecoderClose(*decoder); return Fail(111, name) }
if VorbisDecoderRewind(*decoder) != OK { VorbisDecoderClose(*decoder); return Fail(112, name) }
again: Vec(float32)
if Stream(*decoder, *again) != OK || !Same(VecSlice(again, 0, again.count), VecSlice(streamed, 0, streamed.count)) { VorbisDecoderClose(*decoder); return Fail(113, name) }
// Interleaved s16 is the float output through the PCM16 boundary.
if VorbisDecoderRewind(*decoder) != OK { VorbisDecoderClose(*decoder); return Fail(114, name) }
shorts: [666]s16
at: s64
while true {
frames: s64
if VorbisDecoderReadS16(*decoder, shorts[0:333 * cast(s64)info.channels], *frames) != OK { VorbisDecoderClose(*decoder); return Fail(115, name) }
if frames == 0 { break }
for i: cast(s64)0..frames * info.channels - 1 {
if shorts[i] != Pcm16(cast(float64)decoded.samples[at + i]) { VorbisDecoderClose(*decoder); return Fail(116, name) }
}
at += frames * info.channels
}
VorbisDecoderClose(*decoder); VorbisDecoderClose(*decoder)
if at != decoded.samples.count { return Fail(117, name) }
whole: Vec(s16)
whole_info: VorbisAudio
if VorbisDecodeS16(input, MaxFrames, *whole, *whole_info) != OK || whole.count != at || whole_info.frames != info.frames { return Fail(118, name) }
// Any truncation, even of one byte, is an error before decoding.
cuts: [6]s64 = .[1, 2, 57, bytes.count / 2 + 3, bytes.count - 4, bytes.count - 1]
for cut: cuts {
code := VorbisDecodeFloat(VecSlice(bytes, 0, bytes.count - cut), MaxFrames, *decoded)
if code != Malformed { print("% cut % returned %\n", name, cut, code); return Fail(119, name) }
}
}
return OK
}
// Comments: the comment header is copied verbatim (FFmpeg writes its
// `comment` metadata as DESCRIPTION), field names match without
// regard to ASCII case, and the decoder holds the same copy while open.
Comments :: () -> s32 {
bytes: Vec(u8)
if !Load("comments", "ogg", *bytes) { return Fail(150, "comments") }
input := VecSlice(bytes, 0, bytes.count)
info: VorbisAudio
comments: VorbisComments
if VorbisInspectComments(input, *info, *comments) != OK || info.comments != VorbisCommentCount(*comments) || info.comments < 3 { return Fail(151, "comments") }
if VorbisVendor(*comments).count == 0 || VorbisComment(*comments, -1) != "" || VorbisComment(*comments, info.comments) != "" { return Fail(152, "vendor") }
if VorbisCommentValue(*comments, "TITLE") != "Ziran fixture" || VorbisCommentValue(*comments, "artist") != "Ziran audio" { return Fail(153, "fields") }
if VorbisCommentValue(*comments, "Description") != "Vorbis comments, ünïcödé" || VorbisCommentValue(*comments, "missing") != "" || VorbisCommentValue(*comments, "TITL") != "" { return Fail(154, "fields") }
decoder: VorbisDecoder
if VorbisDecoderOpen(*decoder, input, MaxFrames) != OK { return Fail(155, "decoder") }
same := VorbisVendor(*decoder.comments) == VorbisVendor(*comments) && VorbisCommentCount(*decoder.comments) == info.comments && VorbisCommentValue(*decoder.comments, "title") == "Ziran fixture"
VorbisDecoderClose(*decoder)
if !same || VorbisCommentCount(*decoder.comments) != 0 { return Fail(156, "decoder") }
if VorbisInspectComments(input[0:input.count - 1], *info, *comments) != Malformed || info.frames != 0 ||
VorbisCommentValue(*comments, "title") != "Ziran fixture" { return Fail(158, "failed inspection preserves comments") }
VorbisCommentsFree(*comments)
if VorbisCommentCount(*comments) != 0 { return Fail(157, "free") }
return OK
}
// Exact seeks: after a seek the decoder returns the very samples a linear
// decode has at that frame, forward and backward, on an 8-second stream and
// on a short one, including the end-trimmed tail.
Seeks :: (name: string, expected_frames: s64) -> s32 {
bytes: Vec(u8)
if !Load(name, "ogg", *bytes) { return Fail(200, name) }
input := VecSlice(bytes, 0, bytes.count)
linear: PCM
if VorbisDecodeFloat(input, MaxFrames, *linear) != OK { return Fail(201, name) }
channels := cast(s64)linear.channels
frames := linear.samples.count / channels
if frames != expected_frames { print("% decoded % frames\n", name, frames); return Fail(202, name) }
decoder: VorbisDecoder
if VorbisDecoderOpen(*decoder, input, MaxFrames) != OK { return Fail(203, name) }
defer { VorbisDecoderClose(*decoder) }
if decoder.info.frames != frames { return Fail(204, name) }
targets: [20]s64 = .[frames / 2, 1, 127, 128, 129, 255, 256, 1023, 1024, 1025, 12345, frames - 1000, frames - 1, 17, 0, frames / 3, frames, frames - 50, 4095, frames / 2 + 1]
scratch: [1024]float32
for target: targets {
if target < 0 || target > frames { continue }
if VorbisDecoderSeek(*decoder, target) != OK || decoder.position != target { print("% seek % failed\n", name, target); return Fail(205, name) }
got: s64
if VorbisDecoderRead(*decoder, scratch[0:512 * channels], *got) != OK { return Fail(206, name) }
wanted := frames - target
if wanted > 512 { wanted = 512 }
if got != wanted { return Fail(207, name) }
for i: cast(s64)0..got * channels - 1 {
if scratch[i] != linear.samples[target * channels + i] { print("% seek % differs at sample %\n", name, target, i); return Fail(208, name) }
}
}
if VorbisDecoderSeek(*decoder, frames + 1) != Invalid || VorbisDecoderSeek(*decoder, -1) != Invalid { return Fail(209, name) }
// Reading on from a seek to the middle reaches the end exactly.
if VorbisDecoderSeek(*decoder, frames / 2) != OK { return Fail(210, name) }
rest: Vec(float32)
if Stream(*decoder, *rest) != OK || !Same(VecSlice(rest, 0, rest.count), VecSlice(linear.samples, frames / 2 * channels, linear.samples.count)) { return Fail(211, name) }
return OK
}
// Synthetic streams: block-size arithmetic, end trim and timeline checks.
Synthetic :: () -> s32 {
modes: [9]u8 = .[0, 0, 1, 1, 0, 1, 0, 0, 1]
stream: Vec(u8)
if !VorbisSynthetic(*stream, 2, 44100, modes[:], 0, 100) { return Fail(250, "synthetic") }
info: VorbisAudio
total := VorbisSyntheticFrames(modes[:])
if VorbisInspect(VecSlice(stream, 0, stream.count), *info) != OK || info.frames != total - 100 || info.end_trim != 100 || info.modes != 2 || info.packets != 9 || info.long_block != VorbisSyntheticLong { return Fail(251, "synthetic") }
// The setup header is filler, so libvorbisfile must refuse it cleanly.
pcm: PCM
if VorbisDecodeFloat(VecSlice(stream, 0, stream.count), MaxFrames, *pcm) != Malformed { return Fail(252, "synthetic decode") }
// A timeline offset, multichannel and low-rate metadata, a final
// granule past the decodable frames and a header-only stream.
offset: Vec(u8)
if !VorbisSynthetic(*offset, 1, 44100, modes[:], 4410, 0) || VorbisInspect(VecSlice(offset, 0, offset.count), *info) != Unsupported { return Fail(253, "offset") }
surround: Vec(u8)
if !VorbisSynthetic(*surround, 6, 44100, modes[:], 0, 0) || VorbisInspect(VecSlice(surround, 0, surround.count), *info) != OK { return Fail(254, "channels") }
slow: Vec(u8)
if !VorbisSynthetic(*slow, 1, 4000, modes[:], 0, 0) || VorbisInspect(VecSlice(slow, 0, slow.count), *info) != OK { return Fail(255, "rate") }
long: Vec(u8)
if !VorbisSynthetic(*long, 1, 44100, modes[:], 0, -64) || VorbisInspect(VecSlice(long, 0, long.count), *info) != Malformed { return Fail(256, "granule") }
single: [1]u8 = .[0]
empty: Vec(u8)
if !VorbisSynthetic(*empty, 1, 44100, single[:], 0, 0) || VorbisInspect(VecSlice(empty, 0, empty.count), *info) != Malformed { return Fail(257, "no audio") }
return OK
}
Errors :: () -> s32 {
decoder: VorbisDecoder
scratch: [4]float32
frames: s64
if VorbisDecoderRead(*decoder, scratch[:], *frames) != Invalid || VorbisDecoderSeek(*decoder, 0) != Invalid { return Fail(300, "closed decoder") }
VorbisDecoderClose(*decoder)
// Garbage, silence and text are not Ogg Vorbis.
state: u64 = 54321
sizes: [8]s64 = .[0, 1, 3, 4, 10, 417, 4096, 65536]
for size: sizes {
noise: Vec(u8)
for i: cast(s64)0..size - 1 { if !VecPush(noise, Random(*state)) { return Fail(301, "noise") } }
pcm: PCM
if VorbisDecodeFloat(VecSlice(noise, 0, noise.count), MaxFrames, *pcm) != Malformed { return Fail(302, "noise") }
zeros: Vec(u8)
if !VecResize(zeros, size) { return Fail(303, "zeros") }
if VorbisDecodeFloat(VecSlice(zeros, 0, zeros.count), MaxFrames, *pcm) != Malformed { return Fail(304, "zeros") }
}
info: VorbisAudio
text := "OggS is not enough to make this an Ogg Vorbis stream."
prose: Vec(u8)
for i: 0..text.count - 1 { if !VecPush(prose, text[i]) { return Fail(305, "text") } }
if VorbisRecognizes(VecSlice(prose, 0, prose.count)) || VorbisInspect(VecSlice(prose, 0, prose.count), *info) != Malformed { return Fail(306, "text") }
wav: Vec(u8)
if !Load("mono", "wav", *wav) || VorbisInspect(VecSlice(wav, 0, wav.count), *info) != Malformed { return Fail(307, "wav") }
// Chained streams (one stream after another) are rejected as
// unsupported, as is a stream followed by trailing bytes as malformed.
first: Vec(u8)
second: Vec(u8)
if !Load("stereo", "ogg", *first) || !Load("mono", "ogg", *second) { return Fail(311, "chained") }
chained: Vec(u8)
if !Copy(VecSlice(first, 0, first.count), *chained) || !Copy(VecSlice(second, 0, second.count), *chained) { return Fail(312, "chained") }
pcm: PCM
if VorbisInspect(VecSlice(chained, 0, chained.count), *info) != Unsupported || VorbisDecodeFloat(VecSlice(chained, 0, chained.count), MaxFrames, *pcm) != Unsupported { return Fail(313, "chained") }
trailing: Vec(u8)
if !Copy(VecSlice(first, 0, first.count), *trailing) || !Copy(VecSlice(prose, 0, prose.count), *trailing) { return Fail(314, "trailing") }
if VorbisInspect(VecSlice(trailing, 0, trailing.count), *info) != Malformed { return Fail(315, "trailing") }
// A flipped byte without a CRC refresh fails the container check.
flipped: Vec(u8)
if !Copy(VecSlice(first, 0, first.count), *flipped) { return Fail(316, "crc") }
flipped[flipped.count / 2] ^= 1
if VorbisInspect(VecSlice(flipped, 0, flipped.count), *info) != Malformed { return Fail(317, "crc") }
// Corrupted payload bytes behind refreshed CRCs reach libvorbisfile: in the
// setup header (codebooks) and in the audio packets. Every decode must
// return a status without crashing, and an OK decode keeps the declared
// length.
names: [3]string = .["stereo", "rate48", "comments"]
trials: s64; decoded_ok: s64
for name: names {
bytes: Vec(u8)
if !Load(name, "ogg", *bytes) || VorbisInspect(VecSlice(bytes, 0, bytes.count), *info) != OK { return Fail(318, name) }
skips: [2]s64 = .[1, 2]
for skip: skips {
ranges: Vec(s64)
Bodies(VecSlice(bytes, 0, bytes.count), skip, *ranges)
if ranges.count < 2 { return Fail(319, name) }
for trial: cast(s64)0..99 {
corrupt: Vec(u8)
if !Copy(VecSlice(bytes, 0, bytes.count), *corrupt) { return Fail(320, name) }
for flip: cast(s64)0..3 {
range := ((trial * 7919 + flip * 104729) % (ranges.count / 2)) * 2
start := ranges[range]; width := ranges[range + 1] - start
corrupt[start + (trial * 31 + flip * 977) % width] ^= Random(*state) | 1
}
Recrc(VecSlice(corrupt, 0, corrupt.count))
output: PCM
corrupt_info: VorbisAudio
code := VorbisDecodeFloat(VecSlice(corrupt, 0, corrupt.count), MaxFrames, *output)
if code == OK {
decoded_ok += 1
if VorbisInspect(VecSlice(corrupt, 0, corrupt.count), *corrupt_info) != OK || output.samples.count != corrupt_info.frames * corrupt_info.channels { return Fail(321, name) }
shorts: Vec(s16)
if VorbisDecodeS16(VecSlice(corrupt, 0, corrupt.count), MaxFrames, *shorts, *corrupt_info) != OK || shorts.count != output.samples.count { return Fail(323, name) }
} else if code != Malformed && code != Unsupported && code != LimitExceeded { print("% corrupt returned %\n", name, code); return Fail(322, name) }
trials += 1
}
}
}
print("vorbis corruption: % decodes of corrupted payloads returned a status (% decoded to the declared length)\n", trials, decoded_ok)
return OK
}
Files :: () -> s32 {
decoder: VorbisDecoder
if VorbisDecoderOpenFile(*decoder, "tests/fixtures/vorbis/missing.ogg", MaxFrames) != IOFailure || decoder.state != null { return Fail(400, "missing file") }
path: Vec(u8)
PathInto(*path, "stereo", "ogg")
stereo_path := TextFromBytes(VecSlice(path, 0, path.count))
if VorbisDecoderOpenFile(*decoder, stereo_path, MaxFrames) != OK { return Fail(401, "stereo file") }
if VorbisDecoderOpenFile(*decoder, stereo_path, MaxFrames) != Invalid { VorbisDecoderClose(*decoder); return Fail(402, "reopen") }
streamed: Vec(float32)
code := Stream(*decoder, *streamed)
VorbisDecoderClose(*decoder)
bytes: Vec(u8)
pcm: PCM
if code != OK || !Load("stereo", "ogg", *bytes) || VorbisDecodeFloat(VecSlice(bytes, 0, bytes.count), MaxFrames, *pcm) != OK { return Fail(403, "stereo file") }
if !Same(VecSlice(streamed, 0, streamed.count), VecSlice(pcm.samples, 0, pcm.samples.count)) { return Fail(404, "stereo file") }
return OK
}
#scope_export
VorbisContracts :: () -> s32 {
code := Fixtures()
if code == OK { code = Comments() }
if code == OK { code = Seeks("long", 176400) }
if code == OK { code = Seeks("stereo", 13230) }
if code == OK { code = Seeks("rate22", 6615) }
if code == OK { code = Synthetic() }
if code == OK { code = Errors() }
if code == OK { code = Files() }
if code == OK { print("native Vorbis contracts passed: 5 fixtures within % PCM16 steps (RMS %), exact granule lengths and seeks, comments, malformed input rejected\n", ToleranceSteps, ToleranceRms) }
return code
}
#program_export
main :: () -> s32 { return VorbisContracts() }
+76
View File
@@ -0,0 +1,76 @@
// Synthetic Ogg Vorbis streams for portable inspection tests: real
// identification and comment headers, a setup header holding filler bits and
// a two-mode table (mode 0 short blocks, mode 1 long), and one-byte audio
// packets that name a mode, one packet per page. No decoder accepts the
// setup header; the streams exercise std/vorbis's container, header,
// block-size and granule checks.
#import "std/audio_types"
#import "std/vec"
#import "std/ogg"
#scope_file
Bits :: struct { bytes: Vec(u8); count: s64; }
Put :: (bits: *Bits, value: s64, width: s64) -> bool {
for i: cast(s64)0..width - 1 {
if bits.count % 8 == 0 && !VecPush(bits.bytes, 0) { return false }
if ((value >> i) & 1) != 0 { bits.bytes[bits.count / 8] |= cast(u8)(1 << (bits.count % 8)) }
bits.count += 1
}
return true
}
PutText :: (bits: *Bits, text: string) -> bool {
for i: 0..text.count - 1 { if !Put(bits, cast(s64)text[i], 8) { return false } }
return true
}
#scope_export
// Short and long block sizes of the synthetic streams.
VorbisSyntheticShort :: 256
VorbisSyntheticLong :: 2048
// Frames returned by packet I of MODES (0 short, 1 long): none for the
// first, then half of each neighbouring block.
VorbisSyntheticFrames :: (modes: []u8) -> s64 {
total: s64
for i: cast(s64)1..modes.count - 1 {
previous := ifx modes[i - 1] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
current := ifx modes[i] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
total += (previous + current) / 4
}
return total
}
// Appends a stream with CHANNELS at RATE whose audio packets use MODES. Page
// granules count from START; the last one trims TRIM frames.
VorbisSynthetic :: (output: *Vec(u8), channels: s32, rate: s32, modes: []u8, start: s64, trim: s64) -> bool {
identification: [30]u8
identification[0] = 1
text := "vorbis"
for i: 0..5 { identification[1 + i] = text[i] }
identification[11] = cast(u8)channels
PutLittle(identification[:], 12, 4, cast(u64)rate)
PutLittle(identification[:], 20, 4, 96000)
identification[28] = cast(u8)(8 | (11 << 4)); identification[29] = 1
if AppendPage(output, identification[:], 2, 0, 9, 0) != OK { return false }
comment: Bits
if !Put(*comment, 3, 8) || !PutText(*comment, "vorbis") || !Put(*comment, 5, 32) || !PutText(*comment, "ziran") ||
!Put(*comment, 1, 32) || !Put(*comment, 15, 32) || !PutText(*comment, "TITLE=synthetic") || !Put(*comment, 1, 8) { return false }
if AppendPage(output, VecSlice(comment.bytes, 0, comment.bytes.count), 0, 0, 9, 1) != OK { return false }
// Filler stands for the codebooks, floors, residues and mappings.
setup: Bits
if !Put(*setup, 5, 8) || !PutText(*setup, "vorbis") || !Put(*setup, 65535, 24) || !Put(*setup, 1, 6) { return false }
for mode: 0..1 { if !Put(*setup, mode, 1) || !Put(*setup, 0, 16) || !Put(*setup, 0, 16) || !Put(*setup, 0, 8) { return false } }
if !Put(*setup, 1, 1) { return false }
if AppendPage(output, VecSlice(setup.bytes, 0, setup.bytes.count), 0, 0, 9, 2) != OK { return false }
total: s64
for i: cast(s64)0..modes.count - 1 {
if i > 0 {
previous := ifx modes[i - 1] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
current := ifx modes[i] == 1 then VorbisSyntheticLong else VorbisSyntheticShort
total += (previous + current) / 4
}
last := i == modes.count - 1
packet: [1]u8 = .[cast(u8)((cast(s32)modes[i] << 1) | (ifx modes[i] == 1 then 12 else 0))]
granule := start + total - (ifx last then trim else 0)
if AppendPage(output, packet[:], ifx last then cast(u8)4 else cast(u8)0, granule, 9, cast(u32)(3 + i)) != OK { return false }
}
return true
}
+42
View File
@@ -0,0 +1,42 @@
// Browser-only sink contract; the native driver runs this in headless Chromium.
#import "std/audio"
#import "std/audio_sink"
#import "std/web"
frames_seen: s64;
signal_seen: bool;
Tap :: (samples: []float32, frames: s64) {
frames_seen += frames
for sample: samples { if sample > .1 || sample < -.1 { signal_seen = true } }
}
#program_export
main :: () -> s32 {
if AudioSinkReady() || AudioSinkPending() || AudioSinkUnavailable() { return 9 }
baseline := WebLiveHandles()
AudioUseTap(Tap)
voice := AudioOpenStream(48000, 2, 512)
if voice.slot < 0 || !AudioPlay(voice) { return 1 }
block: [1024]s16
for index: 0..1023 { block[index] = 8192 }
if !AudioStreamSubmit(voice, block[:]) { return 2 }
if !AudioSinkOpen() || !AudioSinkOpen() || !AudioSinkReady() || !AudioSinkResume() { return 3 }
WebSleep(250)
if !AudioSinkRunning() || frames_seen <= 0 || !signal_seen { return 4 }
AudioSinkClose(); AudioSinkClose()
if AudioSinkReady() || AudioSinkPending() || AudioSinkUnavailable() { return 5 }
before := frames_seen
WebSleep(50)
if frames_seen != before { return 6 }
for attempt: 0..3 {
if !AudioSinkOpen() || !AudioSinkResume() { return 7 }
WebSleep(30)
AudioSinkClose()
}
AudioUnload(voice)
if WebLiveHandles() != baseline { return 8 }
scope := WebScope(); defer WebEnd(scope)
document := WebGetObject(WebGlobal, WebName("document"))
body := WebGetObject(document, WebName("body"))
WebSet(body, WebName("textContent"), WebText("audio web sink contract passed"))
return 0
}
+2 -2
View File
@@ -66,7 +66,7 @@ PlanChecks :: (checks: []CheckCase) -> Vec(s64) {
// Ziran case files that drive the compiler named by their first argument.
CheckCompilerCase :: (name: string) -> bool {
return name == "module_parameters_cases.zi" || name == "insert_source_cases.zi" ||
name == "std_environment_cases.zi" || name == "std_input_cases.zi" || name == "c_teacher_cases.zi"
name == "std_environment_cases.zi" || name == "std_input_cases.zi" || name == "c_teacher_cases.zi" || name == "audio_checks.zi"
}
CheckArguments :: (name: string, bin: string, repo: string) -> Vec(string) {
@@ -151,7 +151,7 @@ DiscoverChecks :: (repo: string, bin: string, filter: string) -> Vec(CheckCase)
checks: Vec(CheckCase)
tests := CheckPath(repo, "tests")
compiler_cases := string.["module_parameters_cases.zi", "insert_source_cases.zi",
"std_environment_cases.zi", "std_input_cases.zi", "c_teacher_cases.zi"]
"std_environment_cases.zi", "std_input_cases.zi", "c_teacher_cases.zi", "audio_checks.zi"]
for name: compiler_cases {
if TextContains(name, filter) { VecPush(checks, CheckCase.{.name = name, .cost = 2}) }
}
+43
View File
@@ -0,0 +1,43 @@
# Ogg Vorbis test fixtures
Generated on 2026-11-16 with FFmpeg 7.1.5 (Debian 7.1.5-0+deb13u1) and its
libvorbis encoder (Debian libvorbis 1.3.7). Each `NAME.wav` is FFmpeg's own
decode of `NAME.ogg` (PCM16, its native `vorbis` decoder), the independent
reference that `tests/vorbis_contracts.zi` compares sample values against.
`long.ogg` has no reference: its seeks are checked against this package's
own linear decode.
FFmpeg's Ogg demuxer counts the first packet's discarded half block, so its
decode does not end at the final granule position: it runs a few dozen
frames long (no end trim) or, for `comments.ogg`, 128 frames short. The
contracts compare the frames both decodes hold. The exact length is the
final granule position, which `ffprobe -show_entries stream=duration_ts`
reports and which the system libvorbisfile 1.3.7 (`ov_pcm_total`, and the
frame count `ov_read_float` returns) confirmed when these fixtures were
made; its samples matched FFmpeg's within 0.5 PCM16 steps.
The 0.3 s source is a 440 Hz left / 660 Hz right tone plus seeded noise, as
for the MP3 fixtures:
```sh
SRC='sine=f=440:d=0.3:sample_rate=44100[a];sine=f=660:d=0.3:sample_rate=44100[b];anoisesrc=d=0.3:a=0.05:r=44100:seed=7[n];[a][b]amerge=inputs=2[s];[s][n]amix=inputs=2:normalize=0,volume=0.8'
ff() { ffmpeg -hide_banner -loglevel error -y -bitexact "$@"; }
ff -filter_complex "$SRC" -ac 2 -ar 44100 -c:a libvorbis -q:a 4 stereo.ogg
ff -filter_complex "$SRC" -ac 1 -ar 44100 -c:a libvorbis -q:a 2 mono.ogg
ff -filter_complex "$SRC" -ac 2 -ar 22050 -c:a libvorbis -q:a 3 rate22.ogg
ff -filter_complex "$SRC" -ac 2 -ar 48000 -c:a libvorbis -q:a 5 rate48.ogg
ff -filter_complex "$SRC" -ac 1 -ar 32000 -c:a libvorbis -q:a 1 -metadata title="Ziran fixture" \
-metadata artist="Ziran audio" -metadata comment="Vorbis comments, ünïcödé" comments.ogg
ff -f lavfi -i "sine=f=330:d=8:sample_rate=22050,volume=0.5" -f lavfi -i "anoisesrc=d=8:a=0.08:r=22050:seed=3" \
-filter_complex amix=inputs=2:normalize=0 -ac 1 -ar 22050 -c:a libvorbis -q:a 0 long.ogg
for f in stereo mono rate22 rate48 comments; do ff -i "$f.ogg" -map_metadata -1 -c:a pcm_s16le "$f.wav"; done
```
| File | Stream | Granule frames | FFmpeg frames |
| --- | --- | --- | --- |
| `stereo.ogg` | 44.1 kHz stereo, `-q:a 4` | 13230 | 13312 |
| `mono.ogg` | 44.1 kHz mono, `-q:a 2` | 13230 | 13312 |
| `rate22.ogg` | 22.05 kHz stereo, `-q:a 3` | 6615 | 6656 |
| `rate48.ogg` | 48 kHz stereo, `-q:a 5` | 14400 | 14464 |
| `comments.ogg` | 32 kHz mono, `-q:a 1`; vendor `ffmpeg`, `encoder`, `title`, `artist` and a UTF-8 `DESCRIPTION` (FFmpeg's name for `comment`) | 9600 | 9472 |
| `long.ogg` | 22.05 kHz mono, `-q:a 0`, 8 s | 176400 | — |
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+163
View File
@@ -0,0 +1,163 @@
// Migrated mixer contract: WAV, voices, gain, pitch, loops, pause and PCM streams.
#import "std/audio"
#import "std/audio_decode_wav"
#import "std/byte_text_linux"
#import "std/math"
#import "std/vec"
Types :: #import "std/audio_types";
Wav :: #import "std/audio_wav";
PI :: 3.14159265358979
// RATE Hz audio of SECONDS: a LEFT and a RIGHT sine (0 Hz for silence) at
// AMPLITUDE, as WAV or Ogg Opus bytes.
Tone :: (rate: s32, seconds: float64, left: float64, right: float64, channels: s32, amplitude: float64) -> Types.PCM {
pcm: Types.PCM
pcm.rate = rate
pcm.channels = channels
frames := cast(s64)(seconds * cast(float64)rate)
for frame: 0..frames - 1 {
for channel: 0..channels - 1 {
hertz := ifx channel == 0 then left else right
value := amplitude * Sin(2.0 * PI * hertz * cast(float64)frame / cast(float64)rate)
VecPush(pcm.samples, cast(float32)value)
}
}
return pcm
}
WavBytes :: (pcm: *Types.PCM, output: *Vec(u8)) -> bool { return Wav.WavEncode(pcm, output) == Types.OK }
TAPPED :: 262144
tapped: [TAPPED]float32;
tapped_count: s64;
Tap :: (samples: []float32, frames: s64) {
for index: 0..frames * 2 - 1 {
if tapped_count < TAPPED { tapped[tapped_count] = samples[index]; tapped_count += 1 }
}
}
Near :: (a: float32, b: float32, tolerance: float32 = 0.002) -> bool {
difference := a - b
return difference < tolerance && difference > -tolerance
}
Fail :: (code: s32, message: string) -> s32 {
print("desktop audio: %\n", message)
return code
}
#program_export
main :: () -> s32 {
output: [8192]float32
// A sound decoded whole: a 440 Hz mono sine at half scale, played at half gain.
low := Tone(48000, 0.25, 440.0, 0.0, 1, 0.5)
wav: Vec(u8)
if !WavBytes(*low, *wav) { return Fail(10, "the test WAV was not encoded") }
low_wav := TextView(wav[:])
sound := AudioLoad(low_wav, false)
if sound.slot < 0 { return Fail(11, "the WAV did not load") }
if !Near(cast(float32)AudioLength(sound), 0.25) { return Fail(12, "the WAV's length is wrong") }
AudioUseTap(Tap)
AudioSetGain(sound, 0.5)
if !AudioPlay(sound) || !AudioPlaying(sound) { return Fail(13, "the sound did not play") }
AudioRender(output[:], 1024)
for frame: 0..1023 {
expected := 0.5 * low.samples[frame]
if !Near(output[frame * 2], expected) || output[frame * 2 + 1] != output[frame * 2] {
print("frame %: % % expected %\n", frame, output[frame * 2], output[frame * 2 + 1], expected)
return Fail(14, "the mixed sound is wrong")
}
}
if tapped_count != 2048 { return Fail(15, "the tap did not see the block") }
for index: 0..2047 { if tapped[index] != output[index] { return Fail(16, "the tap saw other samples") } }
// Two voices mix: an 880 Hz sine on the left only joins the first.
pair := Tone(48000, 0.25, 880.0, 0.0, 2, 0.25)
pair_wav: Vec(u8)
if !WavBytes(*pair, *pair_wav) { return Fail(17, "the stereo WAV was not encoded") }
left := AudioLoad(TextView(pair_wav[:]), false)
if left.slot < 0 || !AudioPlay(left) || !AudioPlay(sound) { return Fail(18, "the stereo WAV did not play") }
AudioRender(output[:], 1024)
for frame: 0..1023 {
mono := 0.5 * low.samples[frame]
if !Near(output[frame * 2], mono + pair.samples[frame * 2]) || !Near(output[frame * 2 + 1], mono) {
return Fail(19, "two voices did not mix")
}
}
AudioStop(left)
// Pitch 2 plays every other frame, so the sound ends in half its time.
AudioSetPitch(sound, 2.0)
unused AudioPlay(sound)
AudioRender(output[:], 512)
for frame: 0..511 {
if !Near(output[frame * 2], 0.5 * low.samples[frame * 2]) { return Fail(20, "pitch 2 did not skip frames") }
}
for block: 0..12 { AudioRender(output[:], 512) }
if AudioState(sound) != .Finished { return Fail(21, "the sound did not finish at pitch 2") }
AudioRender(output[:], 512)
for index: 0..1023 { if output[index] != 0.0 { return Fail(22, "a finished sound still plays") } }
// A loop starts over; a paused voice is silent and resumes where it was.
AudioSetPitch(sound, 1.0)
AudioSetLooping(sound, true)
unused AudioPlay(sound)
for block: 0..30 { AudioRender(output[:], 1000) }
if AudioState(sound) != .Playing || AudioPosition(sound) >= 0.25 { return Fail(23, "the loop did not start over") }
AudioPause(sound)
position := AudioPosition(sound)
AudioRender(output[:], 1024)
for index: 0..2047 { if output[index] != 0.0 { return Fail(24, "a paused voice still plays") } }
AudioResume(sound)
AudioRender(output[:], 480)
if AudioState(sound) != .Playing || !Near(cast(float32)(AudioPosition(sound) - position), 0.01, 0.0005) {
return Fail(25, "the voice did not resume where it paused")
}
AudioSetLooping(sound, false)
if !AudioSeek(sound, .1) || !Near(cast(float32)AudioPosition(sound), .1) { return Fail(34, "seek position is wrong") }
AudioRender(output[:], 128)
if !Near(output[0], .5 * low.samples[4800]) { return Fail(35, "seek played another frame") }
AudioPause(sound)
if !AudioSeek(sound, .05) || AudioState(sound) != .Paused || AudioSeek(sound, -.1) || AudioSeek(sound, .3) { return Fail(36, "seek state or bounds failed") }
AudioRender(output[:], 128)
if output[0] != 0.0 || !Near(cast(float32)AudioPosition(sound), .05) { return Fail(37, "paused seek advanced") }
AudioStop(sound)
// A PCM stream plays the blocks submitted, then silence, and never ends.
stream := AudioOpenStream(24000, 2, 256)
if stream.slot < 0 || !AudioStreamWritable(stream) { return Fail(26, "the PCM stream did not open") }
block: [512]s16
for index: 0..511 { block[index] = cast(s16)((index % 2) * 16384 - 8192) }
if AudioStreamSubmit(stream, block[0:511]) { return Fail(27, "a short block was accepted") }
// Play starts a stream afresh, so blocks follow it.
if !AudioPlay(stream) || !AudioStreamSubmit(stream, block[:]) || !AudioStreamSubmit(stream, block[:]) {
return Fail(28, "the PCM blocks were not taken")
}
// At half the mixer's rate each of the 512 submitted frames plays twice,
// then the stream waits in silence.
AudioRender(output[:], 1024)
for frame: 0..1021 {
if !Near(output[frame * 2], -0.25) || !Near(output[frame * 2 + 1], 0.25) {
print("stream frame %: % %\n", frame, output[frame * 2], output[frame * 2 + 1])
return Fail(29, "the PCM stream's samples are wrong")
}
}
if output[2046] != 0.0 || output[2047] != 0.0 { return Fail(30, "an empty stream did not wait in silence") }
if !AudioStreamSubmit(stream, block[:]) { return Fail(31, "the stream took no block after waiting") }
AudioRender(output[:], 256)
if !Near(output[100], -0.25) { return Fail(31, "a block after waiting did not play at once") }
for round: 0..3 { AudioRender(output[:], 1024) }
if AudioState(stream) != .Playing { return Fail(30, "an empty stream finished") }
for round: 0..3 { unused AudioStreamSubmit(stream, block[:]) }
if AudioStreamWritable(stream) || AudioStreamSubmit(stream, block[:]) { return Fail(31, "a full stream took another block") }
if AudioSeek(stream, .01) { return Fail(38, "a live PCM stream was seekable") }
AudioUnload(stream)
if AudioState(stream) != .Unloaded || AudioPlay(stream) { return Fail(32, "an unloaded stream still answers") }
AudioUnload(sound); AudioUnload(left)
VecFree(low.samples); VecFree(pair.samples); VecFree(wav); VecFree(pair_wav)
if AudioLoad("not audio", false).slot >= 0 { return Fail(33, "text loaded as audio") }
print("audio mixer contract passed\n")
return 0
}
-52
View File
@@ -21,59 +21,7 @@ Moved :: (point: Point, by: s64) -> Point { point.x += by; return point }
Mover :: #type (point: Point, by: s64) -> Point;
Holder :: struct { move: Mover; point: Point }
// Signed interval checks may use one unsigned comparison, including narrow
// signed values and either order of the original short-circuit expression.
Outside8 :: (value: s8) -> bool { return value > 100 || value < 0 }
Outside16 :: (value: s16) -> bool { return value < 0 || value > 1000 }
Outside32 :: (value: s32) -> bool { return value > 1000 || value < 0 }
Outside64 :: (value: s64) -> bool { return value > 1000 || value < 0 }
OutsideMax :: (value: s64) -> bool { return value > 9223372036854775807 || value < 0 }
OutsideNarrow :: (value: s8) -> bool { return value > cast(s64)1000 || value < 0 }
OutsideOther :: (left: s64, right: s64) -> bool { return left > 1000 || right < 0 }
OutsideUnsigned :: (value: u64) -> bool { return value > 1000 || value < 0 }
OutsideFloat :: (value: float64) -> bool { return value > 1000.0 || value < 0.0 }
BoundsCalls: s32;
BoundsNext :: (value: s64) -> s64 { BoundsCalls += 1; return value }
BoundsCases :: () -> bool {
for number: -128..127 {
expected := number < 0
if number > 100 { expected = true }
if Outside8(cast(s8)number) != expected { return false }
if OutsideNarrow(cast(s8)number) != (number < 0) { return false }
}
numbers := s64.[-9223372036854775808, -32768, -1, 0, 1, 999, 1000, 1001,
32767, 2147483647, 9223372036854775807]
records: [11]Point
for number, index: numbers {
records[index] = Point.{x = number, y = number}
expected := number < 0
if number > 1000 { expected = true }
if Outside64(number) != expected || OutsideMax(number) != (number < 0) { return false }
member := records[index].x > 1000 || records[index].x < 0
reversed := records[index].y < 0 || records[index].y > 1000
if member != expected || reversed != expected { return false }
if number >= -32768 && number <= 32767 {
if Outside16(cast(s16)number) != expected { return false }
}
if number >= -2147483648 && number <= 2147483647 {
if Outside32(cast(s32)number) != expected { return false }
}
}
if !OutsideOther(1, -1) || OutsideOther(1, 0) { return false }
if !OutsideUnsigned(18446744073709551615) || OutsideUnsigned(1000) { return false }
if !OutsideFloat(-0.5) || OutsideFloat(1000.0) { return false }
BoundsCalls = 0
// Distinct calls must run twice when the first predicate is false.
if !(BoundsNext(1) > 1000 || BoundsNext(-1) < 0) || BoundsCalls != 2 { return false }
// The right call must still be skipped when the first predicate is true.
if !(BoundsNext(1001) > 1000 || BoundsNext(-1) < 0) || BoundsCalls != 3 { return false }
print("bounds % %\n", Outside64(1001), BoundsCalls)
return true
}
main :: () -> s32 {
if !BoundsCases() { return 1 }
points: [4]Point
for i: 0..3 { points[i] = Point.{x = i, y = 10 * i} }