Host packed asset audio through Apps node permissions and lifetime

This commit is contained in:
waozi committed 2026-10-30 20:40:01 -03:00
1 parent 0c26d33c22
commit 7e8890d39d
10 files changed
+620 -11

No files matched your search

+1
View File
@@ -2,3 +2,4 @@
/backup/
/ziran.local.toml
__pycache__/
/work/
+41
View File
@@ -74,6 +74,38 @@ A portable node/2 app may request `kryon/frame_snapshot` and call
to Kryon's widget-host boundary, which returns only the snapshot published for
the active frame session; inactive and foreign-session calls fail closed.
Portable node/2 and app/1 apps can use `kryon/Media`'s `MediaAudio` for packed
asset effects and looping music. Apps recognizes the actual
`media_audio.MediaAudioHost` capability, including its package-qualified name,
through Kryon's existing widget dispatcher. Every operation requires the
platform's existing `AppSoundHost` audio permission for that verified node;
widget access or permission for legacy Media/video services grants no asset
audio. Denied calls return `Denied` with no capability bits. Legacy Media
services retain their existing dispatch and permission policy.
The native consumer installs its provider once on its owning thread with
`MediaAudioUseRaylib()` from `kryon/media_audio_raylib`. Without a provider,
authorized calls return `Unsupported`; device/browser results retain Kryon's
`Unavailable`/`Suspended` semantics. Apps supplies each actual `HostedApp.audio`
owner and `AppHostAudioRead` to `WidgetHostAudioCall`, using the active node's
verified bundle and explicit catalog resource links. Inherited code-library
assets alone grant no audio reads. Paths cannot name host files or network
URLs; Kryon bounds each asset to 8 MiB and each owner to 16 independent voices.
The packed borrow lasts until `AppHostCollect`; providers own decoded/copied
bytes before later reuse. Nodes sharing an outer Session keep separate voices
and readers. No PCM interface is exposed.
`WidgetHostEnd` only ends dispatch; music survives frames. Node retirement
revokes audio immediately, before renderer/preparation storage is collected.
`HostedAppClose` and successful `HostedAppRestart` also release voices; failed
restart preserves the working instance. Account replacement uses the existing
save/`AppHostStop`/`AppHostStart` lifecycle. If a native consumer changes an
account, resource policy, or audio authority in place, it must first call
`AppHostAudioReset(host)` on the owning thread, while owner storage is still
alive. That hook resets all live instances/controllers and revokes a decoder
already in flight; Apps cannot infer changes hidden inside platform context.
Each run also revokes voices when `AppSoundHost` permission is withdrawn.
Inbe and Werkzeug use this same exported launcher and portable controller.
App-specific title/account bars and navigation docks remain with their hosts.
Build the controller with the host's compiler and Kryon graph, review its
@@ -83,3 +115,12 @@ fail validation; never substitute another screen silently.
`scripts/build-ui.py` builds the standalone package controller. The native
fixture exercises real card/menu/dialog behavior; the external-consumer test
verifies public package imports and launcher search/grouping.
## Unreleased
- Pin published Kryon asset audio and host it through Apps' existing audio
permission, verified resources and per-instance lifetime.
- `RAYLIB_A=/path/to/libraylib.a python3 tests/audio_host_test.py /path/to/libziran.a`
exercises real hosted guests with dummy/no-provider and private null-device
Raylib hosts. Run `tests/native_fixture.py`, `tests/consumer_test.py` and
`tests/tree_test.sh` with the same resolved compiler/runtime graph too.
+50
View File
@@ -0,0 +1,50 @@
#import "kryon/session"
using Audio :: #import "kryon/Media";
AudioFixture :: (session: Session, scenario: s32, expected: MediaAudioCode) -> bool {
command := MediaAudioCommand.{.voice = 1}
if scenario == 0 { command.operation = .Capabilities }
if scenario == 1 || scenario == 5 {
command.operation = .Load
command.asset = "assets/audio/tone.wav"
command.music = true
command.gain = .4
if scenario == 5 { command.voice = 2 }
}
if scenario == 2 { command.operation = .Status }
if scenario == 4 {
command.operation = .Load
command.voice = 2
command.asset = "assets/audio/shared.wav"
command.gain = .3
}
if scenario == 3 {
command.operation = .Load
command.voice = 3
command.gain = .3
command.asset = "assets/other/tone.wav"
if MediaAudio(session, command).code != .Missing { return false }
command.asset = "assets/audio/../tone.wav"
if MediaAudio(session, command).code != .Denied { return false }
command.asset = "https://waozi.xyz/tone.wav"
if MediaAudio(session, command).code != .Denied { return false }
command.asset = "assets/audio/large.wav"
if MediaAudio(session, command).code != .Limit { return false }
command.asset = "assets/audio/missing.wav"
return MediaAudio(session, command).code == .Missing
}
#if !#defined(APPS_AUDIO_CONTEXT_FIXTURE) {
if scenario == 7 { return MediaState() == 42 }
}
answer := MediaAudio(session, command)
if answer.code != expected { return false }
if scenario == 0 {
return answer.capabilities == (ifx expected == .Ok then cast(u32)7 else cast(u32)0)
}
if expected != .Ok { return true }
if scenario == 1 {
answer = MediaAudio(session, MediaAudioCommand.{.operation = .Play, .voice = 1, .looping = true})
return answer.code == .Ok && answer.state == .Playing
}
return scenario != 2 || answer.state == .Playing
}
+17
View File
@@ -0,0 +1,17 @@
#import "kryon/app_context"
#import "kryon/app_protocol"
#import, file "audio_commands.zi";
#program_export
Main :: () -> s32 {
if AppMode() == APP_IDENTIFY {
AppIdentity("audio")
AppDescribe("Audio fixture", "")
return APP_PROTOCOL
}
if AppMode() == APP_FRAME {
bounds := AppBounds()
if !AudioFixture(AppSession(), cast(s32)bounds.width - 100, cast(MediaAudioCode)(cast(s32)bounds.height - 100)) { return -1 }
}
return 0
}
+19
View File
@@ -0,0 +1,19 @@
#import "node_types"
#import, file "audio_commands.zi";
host_api :: #system_library "host_api";
ReadAppHost :: () -> AppMessage #foreign host_api;
WriteAppHost :: (message: AppMessage) #foreign host_api;
ReadAppUiHost :: () -> AppUiFrame #foreign host_api;
#program_export
Main :: () -> s32 {
message := ReadAppHost()
if message.abi != MODULE_ABI { return -1 }
if message.action == MODULE_IDENTIFY { return MODULE_NODE_APP }
if message.action == APP_FRAME {
frame := ReadAppUiHost()
message.succeeded = AudioFixture(frame.session, frame.width - 100, cast(MediaAudioCode)(frame.height - 100))
}
WriteAppHost(message)
return 0
}
+86 -6
View File
@@ -17,6 +17,9 @@
#import "kryon/tree"
#import "kryon/widget_host"
#import "kryon/widget_kind"
#import "kryon/bundle_names"
#import "kryon/media_audio_host"
#import "kryon/media_audio"
Rules :: #import "protocol";
Node :: #import "node_types";
#import, file "node_host.zi";
@@ -409,11 +412,73 @@ AppHostWidgets :: (context: *void, module: *u8, function: *u8, arguments: *HostV
count: s32, result: *HostValue) -> s32 {
runtime := cast(*AppRuntime)context
if runtime.retired { return 0 }
if ModuleName(TextFromCString(module), "media_audio") && TextFromCString(function) == "MediaAudioHost" {
return AppHostAudioCall(runtime, arguments, count, result)
}
platform := runtime.host.platform
if platform.widgets == null { return 0 }
return platform.widgets(platform.context, runtime.node, module, function, arguments, count, result)
}
// Audio is optional, like AppSoundHost. Importing it grants no authority.
// app/1's default dispatcher owns packed audio itself; intercept that exact
// function here so both portable protocols use Apps' resource/permission gate.
AppHostContextCall :: (context: *void, module: *u8, function: *u8, arguments: *HostValue,
count: s32, result: *HostValue) -> s32 {
app := cast(*AppContext)context
if ModuleName(TextFromCString(module), "media_audio") && TextFromCString(function) == "MediaAudioHost" {
if app.mode != APP_FRAME || !app.identified || !app.described { return 0 }
return AppHostWidgets(app.context, module, function, arguments, count, result)
}
return AppContextCall(context, module, function, arguments, count, result)
}
AppHostAudioActive :: (runtime: *AppRuntime) -> bool {
return runtime != null && !runtime.retired && runtime.node != null && runtime.busy &&
AppTreeNode(*runtime.host.tree, runtime.host.tree.running) == runtime.node
}
AppHostAudioRead :: (context: *void, path: string) -> string {
runtime := cast(*AppRuntime)context
if !AppHostAudioActive(runtime) || !AppHostAllows(context, "AppSoundHost") ||
!MediaAudioAssetValid(path) { return "" }
// Same verified bundle/dependency links as images, without downloaded art
// or host filenames. Packed bytes remain immutable until AppHostCollect;
// Kryon's provider copies/owns them before this borrow can be reused.
asset := AppHostResource(runtime, *runtime.node.entry, path, 0, true)
// Kryon bounds this borrowed view to 8 MiB before decoding/copying it.
return ifx asset.found then asset.data else ""
}
AppHostAudioCall :: (runtime: *AppRuntime, arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
if !AppHostAudioActive(runtime) { return 0 }
// Reuse Kryon's typed arguments and active/foreign-session validation even
// for a denied caller. Never advertise a provider before authorization.
if WidgetHostAudioCall(null, WidgetHostAudioReadNone, null, arguments, count, result) != 1 { return 0 }
if !AppHostAllows(cast(*void)runtime, "AppSoundHost") {
AppContextAudioReset(*runtime.app)
zero: HostValue
HostFieldValue(result, 0, "code", *zero).* = HostScalar("MediaAudioCode", cast(s64)MediaAudioCode.Denied)
HostFieldValue(result, 3, "message", *zero).* = AppHostText("This app has no audio permission")
return 1
}
return WidgetHostAudioCall(*AppContextRuntime(*runtime.app).audio, AppHostAudioRead,
cast(*void)runtime, arguments, count, result)
}
// Call before the native provider changes account/resource/audio authority in
// place. Normal account replacement uses Stop/Start; Close revokes immediately
// even while retired packed bytes are retained for the renderer/preparer.
AppHostAudioReset :: (host: *AppHost) {
for index: cast(s64)0..host.tree.nodes.count - 1 {
node := host.tree.nodes[index].node
if node == null || node.runtime == null { continue }
runtime := cast(*AppRuntime)node.runtime
AppContextAudioReset(*runtime.app)
if runtime.frontend != null { AppContextAudioReset(*runtime.frontend.app) }
}
}
AppHostRuntime :: (host: *AppHost, node: *AppNode, bytes: string, expected_id: string,
controller: bool = false, protocol: s32 = APPS_CONTEXT_PROTOCOL,
preparation: *AppPreparation = null) -> *AppRuntime {
@@ -474,10 +539,10 @@ AppHostRuntime :: (host: *AppHost, node: *AppNode, bytes: string, expected_id: s
} else {
ready = NodeOpen(*runtime.legacy, bytes, TextUntilNul(node.identity.id[:]), expected_id)
}
} else if preparation != null {
ready = AppContextRestart(*runtime.app)
} else {
ready = AppContextOpen(*runtime.app, bytes)
ready = (preparation != null || HostedAppOpen(opened, bytes)) &&
HostedAppStart(opened, AppContextAllows, AppHostContextCall, cast(*void)(*runtime.app)) &&
AppContextIdentify(cast(*void)(*runtime.app))
}
if !ready {
HostedAppClose(AppContextRuntime(*runtime.app))
@@ -1111,6 +1176,8 @@ AppHostRun :: (host: *AppHost, mode: s32) -> bool {
}
if runtime.busy || !AppTreeBegin(*host.tree, host.tree.active) { return false }
runtime.busy = true
if !AppHostAllows(cast(*void)runtime, "AppSoundHost") { AppContextAudioReset(*runtime.app) }
if runtime.protocol == APPS_NODE_PROTOCOL { MediaAudioOwnerTick(*AppContextRuntime(*runtime.app).audio) }
handle := host.tree.active
frame_session := runtime.app.session
if runtime.protocol == APPS_NODE_PROTOCOL { frame_session = runtime.legacy.frame.session }
@@ -1211,6 +1278,8 @@ AppHostSave :: (context: *void, node: *AppNode) -> bool {
AppHostClose :: (context: *void, node: *AppNode) {
runtime := cast(*AppRuntime)node.runtime
if runtime == null { return }
AppContextAudioReset(*runtime.app)
if runtime.frontend != null { AppContextAudioReset(*runtime.frontend.app) }
host := cast(*AppHost)context
runtime.retired = true
runtime.byte_charge = node.bytes
@@ -1534,7 +1603,8 @@ AppHostDependenciesOpen :: (runtime: *AppRuntime, parent: *AppNode, entry: *AppE
return true
}
AppHostResource :: (runtime: *AppRuntime, entry: *AppEntry, path: string, depth: s32) -> HostedAsset {
AppHostResource :: (runtime: *AppRuntime, entry: *AppEntry, path: string, depth: s32,
own_only: bool = false) -> HostedAsset {
if depth > 32 { return HostedAsset.{} }
app: *HostedApp
if entry == *runtime.node.entry { app = AppContextRuntime(*runtime.app) }
@@ -1544,7 +1614,17 @@ AppHostResource :: (runtime: *AppRuntime, entry: *AppEntry, path: string, depth:
}
}
if app == null { return HostedAsset.{} }
resource := HostedAppAsset(app, path)
// Audio must not turn a code library's inherited table into a resource
// grant. Preserve the indexed image/legacy reader's existing behavior.
own := !own_only || BundleOwnAssets(app.bundle) == BundleAssets(app.bundle)
if !own {
index: u64 = 0
while index < BundleOwnAssets(app.bundle) {
own = own || TextFromCString(BundleAssetPath(app.bundle, index)) == path
index += 1
}
}
resource := ifx own then HostedAppAsset(app, path) else HostedAsset.{}
if resource.found {
if entry != *runtime.node.entry && resource.data.count > 16777216 { return HostedAsset.{} }
return resource
@@ -1563,7 +1643,7 @@ AppHostResource :: (runtime: *AppRuntime, entry: *AppEntry, path: string, depth:
BuilderPrint(*target, "%", TextUntilNul(link.source[:]))
BuilderPrint(*target, "%", path[prefix.count:])
resolved := BuilderFinish(target)
result := AppHostResource(runtime, dependency, resolved, depth + 1)
result := AppHostResource(runtime, dependency, resolved, depth + 1, own_only)
AppFileFree(resolved)
return result
}
+286
View File
@@ -0,0 +1,286 @@
// Reuse the native suite's headless drawing/storage fixtures and real loader.
#import, file "native_behavior.zi";
#import "std/bundle_host"
#import "std/byte_text_linux"
#import "std/c_string"
#import "std/file"
#import "std/text_buffer"
#import "std/vec"
#import "host"
#import "protocol"
#import "tree"
#import "node_host"
Node :: #import "node_types";
#import "kryon/app_context_host"
#import "kryon/app_files"
#import "kryon/app_protocol"
#import "kryon/hosted_app"
#import "kryon/hosted_values"
#import "kryon/session"
#import "kryon/Frame"
#import "kryon/tree"
#import "kryon/geometry"
#import "kryon/drawing_props"
#import "kryon/widget_host"
#import "kryon/widget_codec"
#import "kryon/bundle_names"
#import "kryon/media_audio"
#import "kryon/media_audio_host"
#if #defined(APPS_AUDIO_NATIVE_TEST) {
#import "kryon/media_audio_raylib"
}
using HostValueKind;
using FrameStatus;
audio_permission: bool = true;
legacy_media_permission: bool;
audio_resources: s32;
audio_loads: s32;
audio_revoke: *AppHost;
audio_no_provider: MediaAudioProvider;
audio_libc :: #system_library "libc";
AudioTestBegin :: () #foreign audio_libc "PreparationTestBegin";
AudioAllows :: (context: *void, node: *AppNode, function: string) -> bool {
return (function == "AppSoundHost" && audio_permission) || function == "MediaStateHost"
}
AudioServices :: (context: *void, node: *AppNode, module: *u8, function: *u8,
arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
if legacy_media_permission && TextFromCString(function) == "MediaStateHost" && count == 0 {
result.* = HostScalar("s32", 42)
return 1
}
return 0
}
AudioWidgets :: (context: *void, node: *AppNode, module: *u8, function: *u8,
arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
// Deliberately permissive widget callback: it cannot grant audio.
return WidgetHostCall(context, module, function, arguments, count, result)
}
AudioDummy :: (voice: *MediaAudioVoice, command: MediaAudioCommand, bytes: string) -> MediaAudioResult {
if command.operation == .Capabilities { return .{.code = .Ok, .capabilities = cast(u32)7} }
if command.operation == .Load {
if bytes.count < 4 || bytes[:4] != "RIFF" { return .{.code = .Failed} }
voice.resource = cast(*void)New(s32)
voice.state = .Ready
voice.music = command.music
voice.gain = command.gain
audio_resources += 1
audio_loads += 1
if audio_revoke != null { AppHostAudioReset(audio_revoke) }
}
if command.operation == .Unload && voice.resource != null {
free(cast(*s32)voice.resource)
voice.resource = null
voice.state = .Unloaded
audio_resources -= 1
}
if command.operation == .Play { voice.state = .Playing }
if command.operation == .Stop { voice.state = .Stopped }
if command.operation == .Gain { voice.gain = command.gain }
return .{.code = .Ok, .state = voice.state, .capabilities = cast(u32)7}
}
AudioInstall :: () {
#if #defined(APPS_AUDIO_NATIVE_TEST) {
MediaAudioUseRaylib()
} else {
MediaAudioUseProvider(AudioDummy)
}
}
AudioDraw :: (host: *AppHost, scenario: s32, code: MediaAudioCode) -> bool {
runtime := AppHostActiveRuntime(host)
runtime.app.session = ui_session
runtime.app.bounds = Rectangle.{0.0, 0.0, cast(float32)(100 + scenario), cast(float32)(100 + cast(s32)code)}
runtime.legacy.frame.session = ui_session
runtime.legacy.frame.width = 100 + scenario
runtime.legacy.frame.height = 100 + cast(s32)code
BeginFrame(ui_session, cast(u64)1, runtime.app.bounds)
WidgetHostBegin(ui_session, MediaAudioAssetValid)
ran := AppHostRun(host, APP_FRAME)
WidgetHostEnd()
ended := EndFrame(ui_session) == cast(FrameStatus)FrameOk
return ran && ended
}
AudioOpen :: (host: *AppHost, kind: string, protocol: s32, id: string, expected: string) -> bool {
path: Vec(u8); hash: Vec(u8)
BuilderPrint(*path, "APPS_AUDIO_%_BUNDLE", kind)
BuilderPrint(*hash, "APPS_AUDIO_%_SHA256", kind)
key := BuilderFinish(path); digest_key := BuilderFinish(hash)
bytes, found := ReadEntireFile(FixtureEnvironment(key))
AppFileFree(key)
digest := FixtureEnvironment(digest_key)
AppFileFree(digest_key)
if !found { return false }
// BundleOpen owns its payload; never retain this read's temporary bytes.
defer { AppFileFree(bytes) }
platform := AppPlatform.{.host_api = TEST_HOST_API, .allows = AudioAllows,
.call = AudioServices, .widgets = AudioWidgets}
return AppHostStart(host, bytes, "fixture.audio", id, expected, digest, "account-a", platform,
FixtureEnvironment("APPS_FIXTURE_HARNESS_SHA256"), "en", protocol)
}
AudioAccept :: (context: *void) -> bool {
node := cast(*NodeContext)context
node.identifying = true
answer: s64
accepted := HostedAppRun(node.app, *answer) && answer == Node.MODULE_NODE_APP
node.identifying = false
return accepted
}
AudioReject :: (context: *void) -> bool { return false }
AudioInheritedCheck :: () -> bool {
library_bytes, library_found := ReadEntireFile(FixtureEnvironment("APPS_AUDIO_LIBRARY_BUNDLE"))
thin_bytes, thin_found := ReadEntireFile(FixtureEnvironment("APPS_AUDIO_THIN_BUNDLE"))
if !library_found || !thin_found { return false }
defer { AppFileFree(library_bytes); AppFileFree(thin_bytes) }
library: HostedApp
if !HostedAppOpen(*library, library_bytes) { return false }
defer { HostedAppClose(*library) }
libraries: [1]*void = .[library.bundle]
descriptor := cast(*TextDescriptor)(*thin_bytes)
runtime: AppRuntime
runtime.app.app.bundle = OpenBundleBytesWithLibraries(descriptor.data, cast(u64)thin_bytes.count, *libraries[0], cast(u64)1)
defer { HostedAppClose(*runtime.app.app) }
node: AppNode
runtime.node = *node
// A real thin program with zero own assets must finish the ownership
// scan and cannot turn inherited library bytes into an audio grant.
return runtime.app.app.bundle != null && BundleOwnAssets(runtime.app.app.bundle) == cast(u64)0 &&
HostedAppAsset(*runtime.app.app, "assets/audio/tone.wav").found &&
!AppHostResource(*runtime, *node.entry, "assets/audio/tone.wav", 0, true).found
}
// Use the module the real source bundle actually imports, including package
// identity. Exercise inactive/foreign/unknown/malformed calls without a VM trap.
AudioBoundary :: (runtime: *AppRuntime) -> s32 {
node := *runtime.legacy
module := ""
for index: cast(u64)0..BundleCapabilities(node.app.bundle) - 1 {
if TextFromCString(BundleCapabilityFunctionName(node.app.bundle, index)) == "MediaAudioHost" {
module = TextFromCString(BundleCapabilityModuleName(node.app.bundle, index))
}
}
if module == "" || !ModuleName(module, "media_audio") ||
!NodeAllows(cast(*void)node, module, "MediaAudioHost") ||
NodeAllows(cast(*void)node, "other_media_audio", "MediaAudioHost") ||
!WidgetHostSupports(module, "MediaAudioHost") { return 1 }
fields: [6]HostField
fields[0] = HostField.{.name = HostTextData("operation"), .value = HostScalar("MediaAudioOperation", 0)}
fields[1] = HostField.{.name = HostTextData("voice"), .value = HostScalar("s32", 1)}
fields[2] = HostField.{.name = HostTextData("asset"), .value = AppHostText("")}
fields[3] = HostField.{.name = HostTextData("music"), .value = HostScalar("bool", 0)}
fields[4] = HostField.{.name = HostTextData("looping"), .value = HostScalar("bool", 0)}
fields[5] = HostField.{.name = HostTextData("gain"), .value = HostValue.{.kind = cast(s32)HostReal,
.type_name = HostTextData("float32"), .real = 0.0}}
args: [2]HostValue
args[0] = WidgetEncodeSession(ui_session, *session_codec)
args[1] = HostRecordValue("MediaAudioCommand", fields[:])
result: HostValue
WidgetHostBegin(ui_session, MediaAudioAssetValid)
// A valid outer frame alone is insufficient; the actual node must run.
if NodeCall(cast(*void)node, HostTextData(module), HostTextData("MediaAudioHost"), *args[0], 2, *result) != 0 { return 2 }
if !AppTreeBegin(*runtime.host.tree, runtime.host.tree.active) { return 3 }
runtime.busy = true
foreign := SessionOpen()
args[0] = WidgetEncodeSession(foreign, *session_codec)
if NodeCall(cast(*void)node, HostTextData(module), HostTextData("MediaAudioHost"), *args[0], 2, *result) != 0 { return 4 }
args[0] = WidgetEncodeSession(ui_session, *session_codec)
if NodeCall(cast(*void)node, HostTextData("other_media_audio"), HostTextData("MediaAudioHost"), *args[0], 2, *result) != 0 { return 5 }
args[1].kind = cast(s32)HostPointer
if NodeCall(cast(*void)node, HostTextData(module), HostTextData("MediaAudioHost"), *args[0], 2, *result) != 0 { return 6 }
args[1] = HostRecordValue("MediaAudioCommand", fields[:])
WidgetHostEnd()
if NodeCall(cast(*void)node, HostTextData(module), HostTextData("MediaAudioHost"), *args[0], 2, *result) != 0 { return 7 }
runtime.busy = false
unused AppTreeEnd(*runtime.host.tree, runtime.host.tree.active)
unused SessionClose(foreign)
return 0
}
#program_export
AudioCheck :: () -> s32 {
AudioTestBegin()
if !AudioInheritedCheck() { return 700 }
ui_session = SessionOpen()
first: AppHost
if !AudioOpen(*first, "NODE", APPS_NODE_PROTOCOL, "fixture.audio", "audio") { return 701 }
// Missing provider is truthful. No host API/platform name claims success.
MediaAudioUseProvider(audio_no_provider)
if !AudioDraw(*first, 0, .Unsupported) { return 702 }
AppHostAudioReset(*first)
AudioInstall()
// widgets-only, media/video-only, and fully denied hosts cannot acquire
// audio. Legacy Media continues through the original service policy.
audio_permission = false
if !AudioDraw(*first, 0, .Denied) || !AudioDraw(*first, 1, .Denied) { return 703 }
legacy_media_permission = true
if !AudioDraw(*first, 0, .Denied) || !AudioDraw(*first, 7, .Ok) { return 704 }
legacy_media_permission = false
empty_platform: AppPlatform
first.platform.widgets = empty_platform.widgets
if !AudioDraw(*first, 0, .Denied) { return 705 }
first.platform.widgets = AudioWidgets
audio_permission = true
if !AudioDraw(*first, 0, .Ok) || !AudioDraw(*first, 1, .Ok) ||
!AudioDraw(*first, 2, .Ok) || !AudioDraw(*first, 3, .Ok) { return 706 }
runtime := AppHostActiveRuntime(*first)
boundary := AudioBoundary(runtime)
if boundary != 0 { return 710 + boundary }
audio_permission = false
if !AudioDraw(*first, 0, .Denied) || AppContextRuntime(*runtime.app).audio.voices[0].resource != null { return 718 }
audio_permission = true
if !AudioDraw(*first, 2, .Missing) || !AudioDraw(*first, 1, .Ok) { return 719 }
// A real nested child shares the outer session, never its voices/reader.
nested: AppHost
if !AudioOpen(*nested, "ROOT", APPS_COLLECTION_PROTOCOL, "fixture.audio.root", "collection") ||
!Command(*nested, "{\"v\":1,\"op\":\"open\",\"id\":\"fixture.audio.child\"}") { return 720 }
if !AudioDraw(*nested, 1, .Ok) || !AudioDraw(*nested, 4, .Ok) { return 721 }
child := AppHostActiveRuntime(*nested)
if AppContextRuntime(*runtime.app).audio.voices[0].resource == AppContextRuntime(*child.app).audio.voices[0].resource ||
!AudioDraw(*first, 2, .Ok) { return 722 }
// Reset before an in-place resource-policy update, including old grants.
AppHostAudioReset(*nested)
child.node.entry.resource_count = 0
if AppContextRuntime(*child.app).audio.voices[0].resource != null ||
!AudioDraw(*nested, 2, .Missing) || !AudioDraw(*nested, 4, .Missing) ||
!AudioDraw(*first, 2, .Ok) { return 723 }
if !AudioDraw(*nested, 1, .Ok) { return 724 }
// Retirement revokes immediately, before AppHostCollect releases bytes.
if AppHostBack(*nested) != 1 || AppContextRuntime(*child.app).audio.voices[0].resource != null { return 725 }
AppHostCollect(*nested)
if !AppHostStop(*nested) || !AudioDraw(*first, 2, .Ok) { return 726 }
if HostedAppRestart(runtime.legacy.app, NodeAllows, NodeCall, cast(*void)(*runtime.legacy), AudioReject) {
// Failed restart must retain the playing instance/voices.
return 727
}
if !AudioDraw(*first, 2, .Ok) { return 728 }
if !HostedAppRestart(runtime.legacy.app, NodeAllows, NodeCall, cast(*void)(*runtime.legacy), AudioAccept) ||
AppContextRuntime(*runtime.app).audio.voices[0].resource != null || !AudioDraw(*first, 2, .Missing) { return 729 }
// Simulate a yielding decoder whose verified host revokes the context.
AppHostAudioReset(*first)
MediaAudioUseProvider(AudioDummy)
audio_revoke = *first
if !AudioDraw(*first, 5, .Denied) || audio_resources != 0 { return 730 }
audio_revoke = null
AppHostAudioReset(*first)
AudioInstall()
if !AudioDraw(*first, 1, .Ok) { return 731 }
// The actual account switch hook saves/closes the whole tree first.
if !AppHostStop(*first) || audio_resources != 0 ||
!AudioOpen(*first, "NODE", APPS_NODE_PROTOCOL, "fixture.audio", "audio") ||
!AudioDraw(*first, 2, .Missing) { return 732 }
AppHostAudioReset(*first)
unused CopyCString("account-b", first.tree.account[:])
if !AudioDraw(*first, 2, .Missing) || !AppHostStop(*first) { return 733 }
// app/1 must not bypass the same gate in Kryon's default context dispatch.
context: AppHost
if !AudioOpen(*context, "CONTEXT", APPS_CONTEXT_PROTOCOL, "fixture.context", "audio") { return 734 }
audio_permission = false
if !AudioDraw(*context, 0, .Denied) { return 735 }
audio_permission = true
if !AudioDraw(*context, 1, .Ok) || !AudioDraw(*context, 2, .Ok) || !AppHostStop(*context) { return 736 }
if audio_resources != 0 { return 737 }
unused SessionClose(ui_session)
MediaAudioUseProvider(audio_no_provider)
return 0
}
+115
View File
@@ -0,0 +1,115 @@
"""Apps' real node/2 + app/1 audio boundary, dummy and actual null-device hosts."""
import json
import os
from pathlib import Path
import subprocess
import sys
import wave
import native_fixture as native
ROOT = native.ROOT
WORK = ROOT / 'work/audio-host-adoption'
ZIRAN = native.ZIRAN
def run(*args, env=None):
subprocess.run(list(map(str, args)), cwd=ROOT, env=env, check=True)
def main():
if len(sys.argv) != 2:
raise SystemExit('Pass exact libziran.a')
for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS',
'SESSION_MANAGER', 'DESKTOP_SESSION', 'XDG_SESSION_ID', 'XDG_SESSION_TYPE',
'PIPEWIRE_REMOTE', 'PIPEWIRE_RUNTIME_DIR'):
os.environ.pop(key, None)
run('git', 'check-ignore', 'work/audio-host-adoption/tone.wav')
WORK.mkdir(parents=True, exist_ok=True)
native.WORK = WORK
controller = ROOT / 'build/ui/apps.zx'
run(sys.executable, ROOT / 'scripts/build-ui.py')
os.environ['APPS_FIXTURE_HARNESS_SHA256'] = native.digest(controller)
paths = {}
for kind, identifier in [('NODE', 'fixture.audio'), ('CHILD', 'fixture.audio.child'),
('DONOR', 'fixture.audio.donor'), ('CONTEXT', 'fixture.context')]:
assets = WORK / kind.lower() / 'assets/audio'
assets.mkdir(parents=True, exist_ok=True)
(assets / 'catalog.json').write_text(json.dumps(dict(id=identifier, name='audio',
contract_version=1, module_api=2, host_api=12, save_schema=1)))
with wave.open(str(assets / 'tone.wav'), 'wb') as output:
output.setnchannels(1); output.setsampwidth(2); output.setframerate(8000)
output.writeframes(bytes(16000))
if kind == 'NODE':
with (assets / 'large.wav').open('wb') as output:
output.truncate(8388609)
path = WORK / (kind.lower() + '.zx')
source = 'audio_context' if kind == 'CONTEXT' else 'audio_node'
args = [ZIRAN, 'bundle', '--project', '--offline', '--root', ROOT / 'fixtures',
'--entry', source + ':Main', '--define', 'KRYON_HOSTED_UI',
'--asset-dir', 'assets=' + str(assets.parent), '-o', path]
if kind == 'CONTEXT':
args += ['--define', 'APPS_AUDIO_CONTEXT_FIXTURE']
run(*args, ROOT / 'fixtures' / (source + '.zi'))
paths[kind] = path
paths['LIBRARY'] = WORK / 'library.zx'
native.bundle('counter', paths['LIBRARY'], WORK / 'node/assets')
paths['THIN'] = WORK / 'thin.zx'
native.bundle('counter_addon', paths['THIN'], library=paths['LIBRARY'])
donor = native.child('fixture.audio.donor', paths['DONOR'], 'node/2', 'audio', 'assets/donor.zx')
child = native.child('fixture.audio.child', paths['CHILD'], 'node/2', 'audio', 'assets/child.zx')
child.update(dependencies=['fixture.audio.donor'], resources=[dict(dependency='fixture.audio.donor',
path='assets/audio/shared.wav', source='assets/audio/tone.wav')])
paths['ROOT'] = WORK / 'root.zx'
native.bundle('collection', paths['ROOT'], native.stage('root-stage', 'fixture.audio.root',
[donor, child], {'assets/donor.zx': paths['DONOR'], 'assets/child.zx': paths['CHILD']}, controller))
for kind, path in paths.items():
os.environ['APPS_AUDIO_' + kind + '_BUNDLE'] = str(path)
os.environ['APPS_AUDIO_' + kind + '_SHA256'] = native.digest(path)
toolchain = Path(subprocess.check_output([ZIRAN, 'pkg', 'path', 'ziran'], cwd=ROOT, text=True).strip())
kryon = Path(subprocess.check_output([ZIRAN, 'pkg', 'path', 'kryon'], cwd=ROOT, text=True).strip())
raylib = Path(os.environ['RAYLIB_A'])
# Like consumer_test.py, extend the actual resolved package map only for
# test entry modules outside the package's published module roots.
mapping = WORK / 'module-map.tsv'
lines = (ROOT / 'build/.ziran/module-map.tsv').read_text().splitlines()
lines += ['M\troot\t' + name + '\t' + str(ROOT / 'tests' / (name + '.zi'))
for name in ('audio_host_behavior', 'native_behavior')]
mapping.write_text('\n'.join(lines) + '\n')
os.environ['ZIRAN_PACKAGE_MAP'] = str(mapping)
for actual in (False, True):
output = WORK / 'c'
defines = ['--define', 'APPS_AUDIO_NATIVE_TEST'] if actual else []
run(toolchain / 'build/bin/zi2c', '--prune-stale', '--no-main',
'--module-path', toolchain / 'std',
'--entry', 'audio_host_behavior:AudioCheck', *defines,
'--root', ROOT / 'tests', '-o', output, ROOT / 'tests/audio_host_behavior.zi', ROOT / 'tests/native_behavior.zi')
(output / 'entry.c').write_text('#include <stdio.h>\n#include "audio_host_behavior.h"\n'
'int main(void) { int r=AudioCheck(); if(r) fprintf(stderr,"Apps audio test %d failed\\n",r); return r?1:0; }\n')
includes = [arg for p in [output, *sorted(output.rglob('*'))] if p.is_dir() for arg in ('-iquote', str(p))]
libs = []
if actual:
libs = [str(raylib), *subprocess.check_output(['pkg-config', '--libs', 'sdl2', 'libdrm', 'gbm', 'egl', 'glesv2'], text=True).split(), '-ldl']
executable = WORK / 'test'
run(os.environ.get('CC', 'cc'), '-std=c11', '-O1', '-ffunction-sections', '-fdata-sections',
'-I' + str(toolchain / 'include'), *includes, *sorted(output.rglob('*.c')),
ROOT / 'tests/preparation_host.c', sys.argv[1], *libs,
'-Wl,--gc-sections', '-Wl,--wrap=BundleOpenBytes', '-Wl,--wrap=BundleOpenBytesWithLibraries',
'-Wl,--wrap=BundleInstantiate', '-Wl,--wrap=BundleInstanceRun', '-Wl,--wrap=BundleClose',
'-lm', '-lpthread', '-o', executable)
config = WORK / 'alsa.conf'
config.write_text('pcm.!default { type null }\nctl.!default { type null }\n')
env = dict(os.environ, ALSA_CONFIG_PATH=str(config), SDL_AUDIODRIVER='dummy',
PULSE_SERVER='unix:' + str(WORK / 'no-pulse'), JACK_DEFAULT_SERVER='apps-test-no-server',
JACK_NO_START_SERVER='1', YUE_DESKTOP_RECOVERY='0')
result = subprocess.run([str(executable)], cwd=ROOT, env=env, text=True, capture_output=True, timeout=90)
(WORK / ('native.log' if actual else 'dummy.log')).write_text(result.stdout + result.stderr)
if result.returncode:
print((result.stdout + result.stderr)[-6000:])
result.check_returncode()
print('Apps audio: ' + ('actual Raylib/null device' if actual else 'dummy/no provider') + ' passed')
print('Apps audio package: ' + str(kryon))
if __name__ == '__main__':
main()
+4 -4
View File
@@ -11,11 +11,11 @@
"url": "https://github.com/raysan5/raylib.git"
},
{
"commit": "cdf4dffb07792497f61d1e89e72604f35942e90f",
"commit": "14cfc37bcc65787dea2cd7cd55a07e94637b819d",
"dependencies": {"raylib": "p5a77c9c35110e925"},
"id": "pa10c40b5b88247f4",
"id": "p92c11c32e84f265d",
"name": "kryon",
"ref": "master",
"ref": "14cfc37bcc65787dea2cd7cd55a07e94637b819d",
"url": "https://github.com/kryonlabs/kryon.git"
},
{
@@ -28,7 +28,7 @@
}
],
"root": {
"dependencies": {"crypto": "pf039d7a776333200", "kryon": "pa10c40b5b88247f4"},
"dependencies": {"crypto": "pf039d7a776333200", "kryon": "p92c11c32e84f265d"},
"name": "Apps"
},
"toolchain": {
+1 -1
View File
@@ -21,7 +21,7 @@ node_codec = "src/node_codec.zi"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
ref = "14cfc37bcc65787dea2cd7cd55a07e94637b819d"
[dependencies.crypto]
git = "https://github.com/ziranlang/crypto.git"