Skip to content
Merged
38 changes: 34 additions & 4 deletions Packages/App/Src/Audio.rux
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
/// `docs/dev/phases/phase-05-apu.md`「スコープの調整」によりフェーズ8へ持ち越されていた分)。

import Core::MutableSlice;
import Core::Slice;
import GbCore::{ Apu, ApuDrainSamples };
import Core::{ Slice, #target };
import GbCore::{ Apu, ApuDrainSamples, ApuSampleRate };
import Sdl3::{
SdlAudioS16Le, SdlAudioDeviceDefaultPlayback, SdlAudioSpec,
SDL_GetCurrentAudioDriver, SDL_GetAudioDeviceFormat,
SDL_OpenAudioDeviceStream, SDL_GetAudioStreamFormat,
SDL_PutAudioStreamData, SDL_ResumeAudioStreamDevice,
SDL_GetAudioStreamQueued, SDL_DestroyAudioStream, SDL_Delay, SDL_GetError,
SDL_SetHint,
};

/// 診断ログ用の1行バッファ。実機でしか再現しない音声不具合を、現地で1回
Expand Down Expand Up @@ -50,12 +51,13 @@ func AudioLogSpec(prefix: Slice<char8>, spec: *SdlAudioSpec) {
AudioLogLine(@buf);
}

const SampleRate: int32 = 48000;
const SampleRate: int32 = ApuSampleRate;
const Channels: int32 = 2;
const BytesPerSample: int32 = 2;
/// ペーシングの目標: キューに積まれたバイト数がこれを超える間は新フレームの
/// 生成を待つ(=オーディオの消費速度で実行速度が決まる)。約4フレーム分。
const TargetQueuedBytes: int32 = (SampleRate / 60) * Channels * BytesPerSample * 4;
const LowQueuedBytes: int32 = (SampleRate / 60) * Channels * BytesPerSample * 2;
/// 実行時ステータスをログに出す間隔(フレーム数、約1秒)。毎フレーム出すと
/// 標準出力がスクロールして読めなくなるうえ処理も遅くなるため。
const StatsLogIntervalFrames: int32 = 60;
Expand All @@ -65,6 +67,7 @@ pub struct Audio {
pub frameCount: int32;
pub everNonZeroSample: bool;
pub putFailedLogged: bool;
pub skippedVideoFrames: int32;
/// Ruxコンパイラのmacos-x86_64ターゲット向けコード生成バグの回避用ダミー
/// フィールド。削除禁止。詳細は docs/dev/PLAN.md 1.2「Ruxコンパイラの
/// 既知バグ」を参照。
Expand All @@ -76,6 +79,7 @@ pub func AudioInit() -> Audio {
a.frameCount = 0;
a.everNonZeroSample = false;
a.putFailedLogged = false;
a.skippedVideoFrames = 0;
a.reserved = 0;

var driverBuf: PathBuf;
Expand All @@ -97,7 +101,15 @@ pub func AudioInit() -> Audio {
spec.channels = Channels;
spec.freq = SampleRate;

a.stream = SDL_OpenAudioDeviceStream(SdlAudioDeviceDefaultPlayback, @spec, null, null);
// macOSの既定(1024サンプルフレーム、約23ms)だとキューが約2KBずつ段階的に
// 減り、ペーシング目標との差が画面提示の待ちで食い潰されて描画スキップが
// 起きる。512にするとM4実機でフレーム開始時のキュー最小値が約1KB増えた。
// 他OSは未検証のため既定のまま。
when #target.os == .macOS {
SDL_SetHint("SDL_AUDIO_DEVICE_SAMPLE_FRAMES\0".data, "512\0".data);
}

a.stream =SDL_OpenAudioDeviceStream(SdlAudioDeviceDefaultPlayback, @spec, null, null);
if a.stream == null {
AudioLogError("audio: SDL_OpenAudioDeviceStream に失敗: ");
return a;
Expand All @@ -113,6 +125,17 @@ pub func AudioInit() -> Audio {
if !SDL_ResumeAudioStreamDevice(a.stream) {
AudioLogError("audio: SDL_ResumeAudioStreamDevice に失敗: ");
}

// 空のキューから始めると最初の数フレームで描画スキップが起きるため、
// ペーシング目標まで無音を積んでおく。定常時のキュー量は変わらない。
// 8192バイトの配列はTargetQueuedBytes(5872)を収める。
var silence: int16[4096];
var i: uint = 0;
while i < 4096 {
silence[i] = 0;
i += 1;
}
SDL_PutAudioStreamData(a.stream, @silence[0] as *opaque, TargetQueuedBytes);
return a;
}

Expand Down Expand Up @@ -170,6 +193,8 @@ pub func AudioPushFrame(a: *var Audio, apu: *var Apu, volume: int32) {
PathBufAppendInt(@statsBuf, volume);
PathBufAppend(@statsBuf, " everNonZeroSample=");
PathBufAppend(@statsBuf, a.everNonZeroSample ? "true" : "false");
PathBufAppend(@statsBuf, " skippedVideoFrames=");
PathBufAppendInt(@statsBuf, a.skippedVideoFrames);
AudioLogLine(@statsBuf);
}
}
Expand All @@ -182,6 +207,11 @@ pub func AudioPace(a: *Audio) {
}
}

/// 音声キューが約2フレームを切ったら、次の画面描画を省いて補充を優先する。
pub func AudioNeedsVideoSkip(a: *Audio) -> bool {
return a.stream != null && SDL_GetAudioStreamQueued(a.stream) < LowQueuedBytes;
}

pub func AudioDestroy(a: *var Audio) {
if a.stream != null {
SDL_DestroyAudioStream(a.stream);
Expand Down
24 changes: 19 additions & 5 deletions Packages/App/Src/Main.rux
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import Core::Slice;
import GbCore::{
Cpu, Bus, GbMode,
CpuReset, BusInit, BusLoadRom, BusPowerOn, CpuStep,
CpuReset, BusInit, BusLoadRom, BusPowerOn, CpuRun, BusFlushApu,
MbcSyncWallClock,
};
import Sdl3::{
Expand All @@ -17,6 +17,10 @@ import Sdl3::{
const AppTitle: Slice<char8> = "RuxBoy\0";
const FrameTCycles: uint64 = 70224;
const MaxArgs: uint = 32;
/// 音声開始前の空提示回数。Windows(D3D11)ではウィンドウ表示直後の4〜5回目の
/// 提示が合計約75msかかり、無音プリフィル(約66ms)を使い切って描画スキップが
/// 起きていた。
const WarmUpPresents: int32 = 10;

func Print(text: Slice<char8>) {
PlatformWrite(1, text.data as *opaque, text.length as uint);
Expand Down Expand Up @@ -124,6 +128,9 @@ func Main() -> int {
return 1;
}

// 提示の初回の待ちを音声の再生開始より前に済ませる(WarmUpPresents参照)。
if !opts.headless { VideoWarmUp(@video, WarmUpPresents); }

var audio = AudioInit();
if !AudioIsValid(@audio) {
PrintLine("オーディオデバイスのオープンに失敗しました。音声なしで続行します。");
Expand All @@ -139,10 +146,17 @@ func Main() -> int {
const SaveIdleFrames: int32 = 60;
var savePending = false;
var saveIdleFrames: int32 = 0;
var skippedLastFrame = false;

while running {
if opts.headless && frameCount >= opts.frames { break; }

// 音声が不足した時だけ描画負荷を減らす。連続スキップは避ける。
let skipRender = !opts.headless && frameCount > 0 && !skippedLastFrame && AudioNeedsVideoSkip(@audio);
bus.ppu.renderEnabled = !skipRender;
skippedLastFrame = skipRender;
if skipRender { audio.skippedVideoFrames += 1; }

var event: SdlEvent;
while SDL_PollEvent(@event) {
if event.kind == SdlEventQuit {
Expand All @@ -168,16 +182,16 @@ func Main() -> int {
// 1回のループが実ハードウェア半フレーム分しか進めず、映像更新も
// オーディオ生成量も本来の半分になってしまう)。
let frameStart = bus.hwCycles;
while bus.hwCycles - frameStart < FrameTCycles {
CpuStep(@cpu, @bus);
}
cpu.haltBatchEndHwCycles = frameStart + FrameTCycles;
CpuRun(@cpu, @bus, frameStart + FrameTCycles);

// MBC3のRTCは呼び出し間の経過秒しか進めない(`MbcSyncWallClock`参照)ため、
// 起動時の1回だけでは止まったままになる。毎フレーム供給し続ける。
MbcSyncWallClock(@bus.cart, WallClockNow() as uint64);

VideoPresent(@video, @bus.ppu.framebuffer[0]);
if !skipRender { VideoPresent(@video, @bus.ppu.framebuffer[0]); }

BusFlushApu(@bus);
AudioPushFrame(@audio, @bus.apu, config.volume);

if bus.cart.ramDirty {
Expand Down
2 changes: 1 addition & 1 deletion Packages/App/Src/StateFile.rux
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func StatePath(romPath: Slice<char8>, buf: *var PathBuf) {
PathBufAppend(buf, ".state");
}

pub func SaveStateToFile(cpu: *Cpu, bus: *Bus, romPath: Slice<char8>) -> bool {
pub func SaveStateToFile(cpu: *Cpu, bus: *var Bus, romPath: Slice<char8>) -> bool {
let size = SaveStateExpectedSize(bus);
let block = malloc(size) as *var uint8;
if block == null { return false; }
Expand Down
12 changes: 12 additions & 0 deletions Packages/App/Src/Video.rux
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ pub func VideoPresent(v: *Video, framebuffer: *uint32) {
SDL_RenderPresent(v.renderer);
}

/// 黒画面を`count`回提示する。音声の再生開始前に呼び、ウィンドウを初めて
/// 表示するときの提示の待ちを先に済ませる。
pub func VideoWarmUp(v: *Video, count: int32) {
var i: int32 = 0;
while i < count {
SDL_SetRenderDrawColor(v.renderer, 0, 0, 0, 255);
SDL_RenderClear(v.renderer);
SDL_RenderPresent(v.renderer);
i += 1;
}
}

/// 現在の描画内容をBMPへ保存する(`--screenshot`用の検証手段)。`captureTexture`
/// (ウィンドウの可視性に依存しないオフスクリーンターゲット)へ描き直してから読み戻す。
pub func VideoScreenshot(v: *Video, path: *char8) -> bool {
Expand Down
Loading
Loading