From 45a4f6af8038ca241bad0dcc1860e3341ae87891 Mon Sep 17 00:00:00 2001 From: leroy ketelaars Date: Sun, 15 Nov 2026 14:48:58 +0000 Subject: [PATCH] Use IPL audio sessions for VideoMode navigation cues --- VideoMode/Design/ui-sounds/action-index.md | 31 +++++++----- VideoMode/Design/ui-sounds/budget-audit.md | 4 ++ VideoMode/IplUiAudio.cs | 56 ++++++++++++++++------ VideoMode/Program.cs | 9 +++- VideoMode/README.md | 6 ++- ci/verify_aot.py | 10 ++++ tests/VideoModeAudioTests/FakeSdk.cs | 35 +++++++++++++- tests/VideoModeAudioTests/Program.cs | 30 +++++++++++- 8 files changed, 149 insertions(+), 32 deletions(-) diff --git a/VideoMode/Design/ui-sounds/action-index.md b/VideoMode/Design/ui-sounds/action-index.md index e9ca23b..5a0040b 100644 --- a/VideoMode/Design/ui-sounds/action-index.md +++ b/VideoMode/Design/ui-sounds/action-index.md @@ -1,7 +1,7 @@ # System menu sound actions -The glass-cube demo uses ten finite IPL effects exposed by published -`DolphinDotNet.GameCube` / SDK `0.1.0-preview.347.1`. The mappings apply to Video, +The glass-cube demo uses ten IPL navigation effects exposed by published +`DolphinDotNet.GameCube` / SDK `0.1.0-preview.361.1`. The mappings apply to Video, Calendar, Options and Storage. They describe accepted logical actions, rather than button presses or rendered frames. @@ -45,14 +45,22 @@ the independent console SRAM preference and does not imply AESND downmixing. Off stops active voices and defers the initial firmware read until sound is enabled. Otherwise preparation runs once on `Task.Run`: read the console IPL, -select its qualified profile and prepare the ten effects. The firmware image -and catalog are disposed before interactive playback; prepared native clips -remain resident. Shutdown cancels pending preparation, awaits it, and disposes -voices before clips. No ROM, PCM, replacement tone or recording is bundled or -written to storage. +select its qualified profile and prepare the same owned `SystemAudioSession` +used by IplResources when `SupportsAudioSession` is true. Navigation dispatches +`PlayCue(SystemMenuSound)` directly; ambience is disabled before each cue, +including when restarting after mute. Six owned cue handles bound overlap. +Off releases the handles and stops the session, clearing its remaining tails. +Older qualified profiles retain the ten finite effects as a fallback. +The firmware image and catalog are disposed before interactive playback; +the owned session or native clips remain resident. The audio-enabled frame loop +awaits a short SDK delay after each frame, matching the IPL explorer's scheduler +yield. Shutdown cancels pending preparation, awaits it, and disposes playback +handles before their session or clips. No ROM, PCM, replacement tone or recording +is bundled or written to storage. -Each effect has a 2 MiB native preparation-scratch budget and the retained bank -is capped at 6 MiB of native audio memory. The [budget audit](budget-audit.md) +The session has a 6 MiB native budget. In the legacy fallback, each effect has a +2 MiB native preparation-scratch budget and the retained bank is capped at +6 MiB of native audio memory. The legacy [budget audit](budget-audit.md) bounds every SDK-accepted recipe's scratch charge below 2 MiB; the actual sum of all ten clips on a supported ROM remains unqualified here. The retained-bank limit is an intentional MEM1 ceiling, with partial clips disposed if exceeded. @@ -60,7 +68,7 @@ These limits are separate from the 2 MiB firmware image and SDK-managed extraction data. Reaching `FirmwareImage` makes the SDK select an 8 MiB managed heap, replacing this demo's earlier 256 KiB assumption in audio-enabled builds. Playback performs no firmware reads or effect -preparation in the frame loop; the SDK creates a small channel wrapper per +preparation in the frame loop; the SDK creates a small playback wrapper per played effect. Audio-disabled instrumentation retains its separate baseline. Profiles are qualified for early NTSC 1.0, NTSC 1.2 and PAL 1.2. A missing IPL, @@ -68,7 +76,8 @@ unsupported profile or failed preparation leaves navigation working and reports unavailable audio in the UI Sounds editor. The Cloud environment has no original IPL configured, so native validation there covers graceful unavailability and normal interaction; it does not establish audible playback on physical hardware. -Host tests verify routing, repeat/no-op behavior, voice policy and settings +Host tests verify routing, repeat/no-op behavior, both playback backends, voice +policy, session ambience suppression, mute/restart, disposal and settings migration. Physical listening and supported-ROM playback remain separate checks. The SDK [firmware resource guide](https://github.com/capz/DolphinDotNet/blob/8f5870f68ec7f5eb1e8103c13af42ce082a3516f/docs/system-firmware-resources.md) diff --git a/VideoMode/Design/ui-sounds/budget-audit.md b/VideoMode/Design/ui-sounds/budget-audit.md index 09cc04a..62659cc 100644 --- a/VideoMode/Design/ui-sounds/budget-audit.md +++ b/VideoMode/Design/ui-sounds/budget-audit.md @@ -1,5 +1,9 @@ # IPL UI audio preparation budget audit +This audit applies to the finite-clip fallback. Current VideoMode builds prefer +the owned sequenced session used by IplResources when the profile supports it; +that path does not retain this ten-clip PCM bank. + SDK: published `0.1.0-preview.347.1`, source `8f5870f68ec7f5eb1e8103c13af42ce082a3516f`. diff --git a/VideoMode/IplUiAudio.cs b/VideoMode/IplUiAudio.cs index 97ba8d4..af13843 100644 --- a/VideoMode/IplUiAudio.cs +++ b/VideoMode/IplUiAudio.cs @@ -9,9 +9,9 @@ internal enum IplUiAudioState { NotStarted,Loading,Ready,Unavailable,Closed } -// Extract/pre-render the console's qualified finite effects once, off the app -// executor. The rendering loop only publishes completed work and uses resident -// native clips. No firmware bytes or prepared audio are written to storage. +// Prepare the console's qualified audio once, off the app executor. Prefer the +// IPL explorer's sequenced session; older profiles use resident finite clips. +// No firmware bytes or prepared audio are written to storage. internal sealed class IplUiAudio { // The SDK's maximum accepted recipe, decoded sources, PCM and delay lines @@ -21,6 +21,8 @@ internal sealed class IplUiAudio private readonly CancellationTokenSource cancellation=new CancellationTokenSource(); private readonly IplUiAudioPolicy policy=new IplUiAudioPolicy(); private readonly SoundChannel?[] voices=new SoundChannel?[IplUiAudioPolicy.VoiceLimit]; + private readonly SystemAudioPlayback?[] cues=new SystemAudioPlayback?[IplUiAudioPolicy.VoiceLimit]; + private SystemAudioSession? session; private Task? loading; private Task? closing; private Sound?[]? clips; @@ -38,10 +40,12 @@ internal sealed class IplUiAudio private sealed class Prepared { internal readonly Sound?[]? Clips; + internal readonly SystemAudioSession? Session; internal readonly int Count,Bytes; internal readonly string Failure; internal Prepared(Sound?[]? clips,int count,int bytes,string failure) {Clips=clips;Count=count;Bytes=bytes;Failure=failure;} + internal Prepared(SystemAudioSession session){Session=session;Count=EffectCount;Failure="";} } internal void Start() { @@ -57,8 +61,16 @@ private Prepared Prepare() { var token=cancellation.Token;int count=0,bytes=0; using(var image=SystemFirmware.ReadConsole(token)) - using(var catalog=image.CreateCatalog(FirmwareCatalogOptions.IncludeMenuAudio,token)) + using(var catalog=image.CreateCatalog(FirmwareCatalogOptions.IncludeSystemAudio|FirmwareCatalogOptions.IncludeMenuAudio,token)) { + // Use the same owned, sequenced session as the working IPL + // explorer. Do not render and retain ten separate PCM copies. + if(catalog.SupportsAudioSession) + { + var prepared=SystemResources.CreateAudioSession(catalog,token,BankBudget); + try{token.ThrowIfCancellationRequested();return new Prepared(prepared);} + catch{prepared.Dispose();throw;} + } for(int i=0;i Main() { var audio=new IplUiAudio();int result=0;System.Exception? failure=null; - try{result=RunFrames(audio);}catch(System.Exception error){failure=error;} + try{result=await RunFrames(audio);}catch(System.Exception error){failure=error;} // Await cancellation outside finally: the GameCube AOT subset does not // implement ExceptionDispatchInfo used by an awaited finally block. await audio.Close(); if(failure!=null)throw failure; return result; } - private static int RunFrames(IplUiAudio uiAudio) + private static async System.Threading.Tasks.Task RunFrames(IplUiAudio uiAudio) #else private static int Main() #endif @@ -272,6 +272,11 @@ private static int Main() #endif phaseStart=timing?Clock.Timestamp:0; device.EndFrame(); +#if IPL_SYSTEM_AUDIO + // Match the IPL explorer: let the application/service scheduler + // advance preparation and native audio between completed frames. + await System.Threading.Tasks.Task.Delay(1); +#endif int end=timing?IplFrameProfiler.Since(phaseStart):0; IplPerformanceOverlay.CompleteFrame(frameStart,prepare,submit,end); if(IplFrameProfiler.Active) diff --git a/VideoMode/README.md b/VideoMode/README.md index fd86aac..a3685d4 100644 --- a/VideoMode/README.md +++ b/VideoMode/README.md @@ -145,8 +145,10 @@ Hardware/TV acceptance and visual comparison inside Dolphin remain separate from successful compilation; do not treat host visual proofs as emulator captures. Normal builds enable system menu audio. Preparation reads the console IPL once -in the background and retains the resulting native clips; it does not read -firmware or synthesize effects on each input. Without a supported IPL the demo +in the background and uses the same sequenced audio session as IplResources. +Older qualified profiles fall back to retained finite clips. The audio-enabled +frame loop yields to the SDK scheduler after each frame. Input plays resident +cues without rereading firmware or preparing effects. Without a supported IPL the demo remains usable and the UI Sounds editor reports audio unavailable. In Dolphin, an original IPL must already be configured for successful playback. No ROM or prepared PCM is bundled. `-p:IplSystemAudio=false` excludes this backend; diff --git a/ci/verify_aot.py b/ci/verify_aot.py index dfab24b..68b1f5c 100644 --- a/ci/verify_aot.py +++ b/ci/verify_aot.py @@ -27,6 +27,16 @@ def check(name: str, configuration: str, generated_c: Path) -> None: if api not in c: raise RuntimeError(f"IplResources: published firmware API is not reachable: {api}") if name == "VideoMode": + # Audio-disabled measurement builds deliberately omit this backend. + if "IplUiAudio" in c: + for api in ("FirmwareCatalog_get_SupportsAudioSession", "SystemResources_CreateAudioSession", + "SystemAudioSession_PlayCue", "SystemAudioSession_SetControl", + "SystemAudioSession_set_Volume", "SystemAudioPlayback_Dispose"): + if api not in c: + raise RuntimeError(f"VideoMode: IPL session API is not reachable: {api}") + frames = re.search(r"intptr_t dnd_value_VideoMode_Program__RunFrames[^(]*MoveNext[^(]*\([^;]+?\) \{(.*?)\n\}", c, re.S) + if frames is None or "Time_DelayAsync" not in frames.group(1): + raise RuntimeError("VideoMode: audio-enabled frame loop must yield to the SDK scheduler") def glass_body(method): match=re.search(r"intptr_t dnd_value_VideoMode_SealedGlassShell_"+method+r"_[^(]+\([^;]+?\) \{(.*?)\n\}",c,re.S) return match.group(1) if match else None diff --git a/tests/VideoModeAudioTests/FakeSdk.cs b/tests/VideoModeAudioTests/FakeSdk.cs index 5df4d83..e2c389b 100644 --- a/tests/VideoModeAudioTests/FakeSdk.cs +++ b/tests/VideoModeAudioTests/FakeSdk.cs @@ -11,12 +11,17 @@ internal static class AudioFixture { internal static int Initialized,Read,ImagesDisposed,CatalogsDisposed,Created,Disposed,FailAt=-1,RequiredPreparationBytes; internal static bool Unsupported; + internal static bool SupportsSession,SessionFaulted; + internal static int SessionsCreated,SessionsDisposed,SessionStops; + internal static float SessionVolume; + internal static List Cues=new(); internal static ManualResetEventSlim Entered=new(false),Continue=new(true); internal static List Voices=new(); internal static List DisposalOrder=new(); internal static void Reset() { Initialized=Read=ImagesDisposed=CatalogsDisposed=Created=Disposed=RequiredPreparationBytes=0;FailAt=-1;Unsupported=false; + SupportsSession=SessionFaulted=false;SessionsCreated=SessionsDisposed=SessionStops=0;SessionVolume=1;Cues=new(); Entered.Dispose();Continue.Dispose();Entered=new(false);Continue=new(true); Voices=new();DisposalOrder=new();Dolphin.Timing.Clock.Timestamp=0; } @@ -79,7 +84,7 @@ public static class Clock {public static long Timestamp {get;set;}} namespace Dolphin.System { [Flags] - public enum FirmwareCatalogOptions {None=0,IncludeMenuAudio=1} + public enum FirmwareCatalogOptions {None=0,IncludeMenuAudio=1,IncludeSystemAudio=2} public enum SystemMenuSound {TurnSide,TurnCenter,Select,Back,OptionCancel,OptionConfirm,OptionMove1,OptionMove2,OptionMove3,OptionSelect,PressStart} public sealed class SystemMenuSoundInfo {} @@ -90,6 +95,7 @@ public sealed class FirmwareImage : IDisposable } public sealed class FirmwareCatalog : IDisposable { + public bool SupportsAudioSession=>AudioFixture.SupportsSession; public bool TryGetMenuSoundInfo(SystemMenuSound id,out SystemMenuSoundInfo? info) {info=AudioFixture.Unsupported?null:new();return info!=null;} public void Dispose(){AudioFixture.CatalogsDisposed++;} @@ -104,6 +110,8 @@ public static FirmwareImage ReadConsole(CancellationToken token=default) } public static class SystemResources { + public static SystemAudioSession CreateAudioSession(FirmwareCatalog catalog,CancellationToken token=default,int nativeBudgetBytes=8*1024*1024) + {token.ThrowIfCancellationRequested();return new();} public static Dolphin.Audio.Sound CreateMenuSound(FirmwareCatalog catalog,SystemMenuSound id, CancellationToken token=default,int nativeBudgetBytes=8*1024*1024) { @@ -113,4 +121,29 @@ public static Dolphin.Audio.Sound CreateMenuSound(FirmwareCatalog catalog,System return new((int)id); } } + public enum SystemAudioControl {AmbienceEnabled=0} + public enum SystemAudioSessionState {Stopped,Playing,Faulted,Disposed} + public sealed class SystemAudioStatistics {public int NativeBytes=>900000;} + public sealed class SystemAudioPlayback : IDisposable + { + public readonly SystemMenuSound Cue; + public bool IsPlaying {get;private set;}=true; + public SystemAudioPlayback(SystemMenuSound cue){Cue=cue;AudioFixture.Cues.Add(this);} + public void Dispose(){if(!IsPlaying)return;IsPlaying=false;AudioFixture.DisposalOrder.Add("cue");} + } + public sealed class SystemAudioSession : IDisposable + { + private bool disposed; + private bool ambienceDisabled; + public SystemAudioSession(){AudioFixture.SessionsCreated++;} + public SystemAudioSessionState State=>disposed?SystemAudioSessionState.Disposed:AudioFixture.SessionFaulted?SystemAudioSessionState.Faulted:SystemAudioSessionState.Playing; + public float Volume {get=>AudioFixture.SessionVolume;set=>AudioFixture.SessionVolume=value;} + public SystemAudioStatistics GetStatistics()=>new(); + public void SetControl(SystemAudioControl control,float value) + {if(disposed)throw new ObjectDisposedException(nameof(SystemAudioSession));if(value!=0)throw new Exception("Navigation enables unwanted ambience");ambienceDisabled=true;} + public SystemAudioPlayback PlayCue(SystemMenuSound cue) + {if(!ambienceDisabled||disposed)throw new Exception("Session cue started without disabling ambience");return new(cue);} + public void Stop(){AudioFixture.SessionStops++;ambienceDisabled=false;foreach(var cue in AudioFixture.Cues)if(cue.IsPlaying)throw new Exception("Stop before disposing cue handles");} + public void Dispose(){if(disposed)return;disposed=true;AudioFixture.SessionsDisposed++;if(AudioFixture.Cues.Exists(c=>c.IsPlaying))throw new Exception("Session disposed before active cues");AudioFixture.DisposalOrder.Add("session");} + } } diff --git a/tests/VideoModeAudioTests/Program.cs b/tests/VideoModeAudioTests/Program.cs index c078efd..597f5c2 100644 --- a/tests/VideoModeAudioTests/Program.cs +++ b/tests/VideoModeAudioTests/Program.cs @@ -70,7 +70,33 @@ private static async Task CancelPreparation() } private static async Task Main() { - await ResidentPlayback();await PreparationFailures();await CancelPreparation(); - Console.WriteLine("UI audio lifecycle: saved Off, one-time loading, native ownership, bounded voices, live volume/mute, partial failures, unsupported profiles and cancellation passed."); + await ResidentPlayback();await PreparationFailures();await CancelPreparation();await SessionPlayback(); + Console.WriteLine("UI audio lifecycle: sequenced cues and legacy clips, saved Off, one-time loading, native ownership, bounded voices, live volume/mute, partial failures, unsupported profiles and cancellation passed."); + } + private static async Task SessionPlayback() + { + AudioFixture.Reset();AudioFixture.SupportsSession=true; + var audio=new IplUiAudio();audio.Tick(2);await WaitForPreparation(audio); + Check(audio.State==IplUiAudioState.Ready&&audio.LoadedCount==10&&audio.NativeBytes==900000,"complete profile publishes one owned sequenced session"); + Check(AudioFixture.SessionsCreated==1&&AudioFixture.Created==0&&AudioFixture.ImagesDisposed==1&&AudioFixture.CatalogsDisposed==1,"complete session uses no legacy PCM bank and survives catalog disposal"); + for(int i=0;i<10;i++){Dolphin.Timing.Clock.Timestamp=i*50000;audio.Play((IplUiSound)(i+1));Check((int)AudioFixture.Cues[i].Cue==i,"all ten semantic actions reach their original sequenced cue");} + Check(audio.PlayedCount==10&&audio.StolenCount==4&&AudioFixture.Cues.FindAll(c=>c.IsPlaying).Count==6,"session overlap obeys the six-cue policy"); + audio.Tick(1);Check(AudioFixture.SessionVolume==.25f,"volume applies to the complete sequenced output"); + audio.Tick(0);Check(AudioFixture.Cues.TrueForAll(c=>!c.IsPlaying)&&AudioFixture.SessionStops==1,"mute releases handles and clears sequenced delay tails"); + audio.Tick(2);audio.Play(IplUiSound.ConfirmEdit);Check(audio.PlayedCount==11&&AudioFixture.SessionsCreated==1,"unmute reuses the session and suppresses ambience before restarting"); + await audio.Close();Check(AudioFixture.SessionsDisposed==1&&AudioFixture.DisposalOrder[^1]=="session","shutdown releases cues before their session"); + AudioFixture.Reset();AudioFixture.SupportsSession=true;AudioFixture.Continue.Reset();audio=new();audio.Tick(2); + Check(AudioFixture.Entered.Wait(2000),"session preparation reaches firmware cancellation point");await audio.Close(); + Check(AudioFixture.SessionsCreated==0&&audio.State==IplUiAudioState.Closed,"cancellation never leaks a prepared session"); + + AudioFixture.Reset();AudioFixture.SupportsSession=true;audio=new();audio.Tick(2);await WaitForPreparation(audio); + audio.Play(IplUiSound.ConfirmEdit);AudioFixture.SessionFaulted=true;audio.Tick(2); + Check(audio.State==IplUiAudioState.Unavailable&&AudioFixture.SessionsDisposed==1&&AudioFixture.Cues.TrueForAll(c=>!c.IsPlaying),"sequencer faults release cues before the session and keep navigation usable"); + await audio.Close();Check(AudioFixture.SessionsDisposed==1,"fault cleanup is not repeated at shutdown"); + + AudioFixture.Reset();AudioFixture.SupportsSession=true;audio=new();audio.Tick(2); + for(int i=0;i<2000&&AudioFixture.CatalogsDisposed==0;i++)await Task.Delay(1); + Check(AudioFixture.SessionsCreated==1,"background session prepared without being published to a frame"); + await audio.Close();Check(AudioFixture.SessionsDisposed==1,"shutdown disposes a completed session even before Tick adopts it"); } }