Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 42 additions & 7 deletions Packages/App/Src/Audio.rux
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,28 @@ const LowQueuedBytes: int32 = (SampleRate / 60) * Channels * BytesPerSample * 2;
/// 標準出力がスクロールして読めなくなるうえ処理も遅くなるため。
const StatsLogIntervalFrames: int32 = 60;

/// 実機の出力段にあるカップリングコンデンサ相当のハイパスフィルタ係数
/// (Q16固定小数点)。APUのミキサーはDAC出力をそのまま足すため、DAC onで
/// 鳴っていないch(典型的には出力レベル25%のch3)が大きな直流成分を残す。
/// それが鳴っている音のヘッドルームを食い、ON/OFFのたびにプチノイズになる。
/// 値は SameBoy の 0.999958^(4194304/22050) ≒ 0.992 に合わせた。
const HighPassCoeffQ16: int64 = 65012;
/// 出力段のゲイン(%)。ミキサーは4ch最大・NR50最大でちょうどフルスケールに
/// なる設計のため、そのままだと音が大きすぎ、SDLの22050→デバイス周波数の
/// リサンプリングで生じるオーバーシュートが飽和して音が割れる。
const OutputGainPercent: int64 = 50;

pub struct Audio {
pub stream: *opaque;
pub frameCount: int32;
pub everNonZeroSample: bool;
pub putFailedLogged: bool;
pub skippedVideoFrames: int32;
/// ハイパスフィルタの状態(左右それぞれ直前の入力と出力)。
hpPrevInLeft: int64;
hpPrevInRight: int64;
hpPrevOutLeft: int64;
hpPrevOutRight: int64;
/// Ruxコンパイラのmacos-x86_64ターゲット向けコード生成バグの回避用ダミー
/// フィールド。削除禁止。詳細は docs/dev/PLAN.md 1.2「Ruxコンパイラの
/// 既知バグ」を参照。
Expand All @@ -80,6 +96,10 @@ pub func AudioInit() -> Audio {
a.everNonZeroSample = false;
a.putFailedLogged = false;
a.skippedVideoFrames = 0;
a.hpPrevInLeft = 0;
a.hpPrevInRight = 0;
a.hpPrevOutLeft = 0;
a.hpPrevOutRight = 0;
a.reserved = 0;

var driverBuf: PathBuf;
Expand Down Expand Up @@ -143,6 +163,13 @@ pub func AudioIsValid(a: *Audio) -> bool {
return a.stream != null;
}

func ScaleOutput(v: int64, volume: int32) -> int16 {
let scaled = v * OutputGainPercent * (volume as int64) / 10000;
if scaled > 32767 { return 32767; }
if scaled < -32768 { return -32768; }
return scaled as int16;
}

/// `volume`(0-100)を適用しつつ、APUに溜まっているサンプルをオーディオストリームへ
/// 送る。あわせて、実機でしか再現しない不具合を1回の実行で追えるよう、
/// 定期的に稼働状況(キュー滞留量・生成サンプル数・無音判定)をログへ残す。
Expand All @@ -152,13 +179,21 @@ pub func AudioPushFrame(a: *var Audio, apu: *var Apu, volume: int32) {
var buf: int16[4096];
let drained = ApuDrainSamples(apu, MutableSlice::From<int16>(@buf[0], 4096));

if volume != 100 {
var i: uint = 0;
while i < drained {
let scaled = (buf[i] as int32) * volume / 100;
buf[i] = scaled as int16;
i += 1;
}
// 直流除去 → 出力ゲイン・ユーザー音量の順に適用する。ハイパス後の振幅は
// 入力の最大2倍(-最大→+最大の跳躍時)になりうるので、最後にクランプする。
var i: uint = 0;
while i + 1 < drained {
let inL = buf[i] as int64;
let inR = buf[i + 1] as int64;
let outL = inL - a.hpPrevInLeft + (a.hpPrevOutLeft * HighPassCoeffQ16) / 65536;
let outR = inR - a.hpPrevInRight + (a.hpPrevOutRight * HighPassCoeffQ16) / 65536;
a.hpPrevInLeft = inL;
a.hpPrevInRight = inR;
a.hpPrevOutLeft = outL;
a.hpPrevOutRight = outR;
buf[i] = ScaleOutput(outL, volume);
buf[i + 1] = ScaleOutput(outR, volume);
i += 2;
}

if !a.everNonZeroSample {
Expand Down
82 changes: 70 additions & 12 deletions Packages/Core/Src/Apu.rux
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ pub struct PulseChannel {
pub envelope: Envelope;
/// ch2(スイープなし)では未使用(has_sweepは呼び出し側が指定)。
pub sweep: Sweep;
/// 区間平均(ボックスフィルタ)用アキュムレータ。分母はwave.sampleCyclesと
/// 共有する(全経路で同じだけ進むため)。セーブステートには含めず、ロード時に
/// 0へ戻す(失うのは書き出し途中のPCMサンプル1個分だけ)。
pub sampleArea: int32;
}

pub struct WaveChannel {
Expand Down Expand Up @@ -212,6 +216,7 @@ func PulseChannelReset(ch: *var PulseChannel) {
ch.timer = 0;
EnvelopeReset(@ch.envelope);
SweepReset(@ch.sweep);
ch.sampleArea = 0;
}

func WaveChannelReset(ch: *var WaveChannel) {
Expand Down Expand Up @@ -537,6 +542,10 @@ func PulseDutyHigh(duty: uint8, step: uint8) -> bool {
return step == 1 || step == 2 || step == 3 || step == 4 || step == 5 || step == 6;
}

/// PulseDutyHigh をビットマスクにしたもの(bit n = step n が high)。ApuTickの
/// 熱いパスで関数呼び出しを避けて出力を求めるために使う。
const PulseDutyMasks: uint8[4] = [0x80, 0x81, 0xE1, 0x7E];

/// 矩形波chの現在の出力を「量子化された生の単位」(-15..15)で返す。ch無効/
/// DAC offなら0。
func PulseOutputUnits(ch: *PulseChannel) -> int32 {
Expand Down Expand Up @@ -691,12 +700,13 @@ func WaveCycleAverageUnits(apu: *Apu) -> int32 {
return units / 32;
}

/// t_cycles ぶんAPUを進める。bus_tick から呼ばれる。wave/noiseチャンネルは
/// t_cycles ぶんAPUを進める。bus_tick から呼ばれる。全チャンネルとも
/// 1 T-cycleごとの出力値をsampleArea/sampleCyclesへ蓄積し
/// (区間平均=ボックスフィルタ)、PCMサンプル1個を出力する瞬間にarea/cycles
/// の平均値を使う(点サンプリングによるエイリアシングノイズ対策)。
/// 出力とタイマーが変わらない区間は同じ値をサイクル数ぶんまとめて加算する。
/// Pulseチャンネルは瞬時値のまま(区間平均を行わない)。
/// Pulseも区間平均する(瞬時値の間引きは22050Hzでは高調波の折り返しが
/// 元の音にない周波数として聞こえるため)。
///
/// 落とし穴(性能): CPU全メモリアクセスごとに呼ばれる最も熱いパスであり、
/// Rux Releaseパイプラインは関数インライン化を行わない(external/Rux/Docs/
Expand Down Expand Up @@ -735,6 +745,13 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
}

apu.frameSequencerCycles += span;
// spanはパルスの周期境界を越えないので、区間内の出力は一定。
if apu.pulse1.enabled {
apu.pulse1.sampleArea += PulseOutputUnits(@apu.pulse1) * (span as int32);
}
if apu.pulse2.enabled {
apu.pulse2.sampleArea += PulseOutputUnits(@apu.pulse2) * (span as int32);
}
if apu.pulse1.enabled {
apu.pulse1.timer -= span;
if apu.pulse1.timer <= 0 {
Expand Down Expand Up @@ -786,6 +803,14 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
apu.sampleCounter += span * ApuSampleRate;
if apu.sampleCounter >= 4194304 {
apu.sampleCounter -= 4194304;
var pulse1Units: int32 = 0;
var pulse2Units: int32 = 0;
if apu.wave.sampleCycles > 0 {
pulse1Units = apu.pulse1.sampleArea / apu.wave.sampleCycles;
pulse2Units = apu.pulse2.sampleArea / apu.wave.sampleCycles;
}
apu.pulse1.sampleArea = 0;
apu.pulse2.sampleArea = 0;
var waveUnits: int32 = 0;
if apu.wave.sampleCycles > 0 {
if WaveAboveNyquist(apu.wave.frequency) {
Expand All @@ -804,7 +829,7 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
apu.noise.sampleCycles = 0;
var left: int16 = 0;
var right: int16 = 0;
MixSample(apu, waveUnits, noiseUnits, @left, @right);
MixSample(apu, pulse1Units, pulse2Units, waveUnits, noiseUnits, @left, @right);
PushSample(apu, left, right);
}
remaining -= span;
Expand Down Expand Up @@ -836,8 +861,22 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
(!apu.pulse2.enabled || apu.pulse2.timer > tCycles) &&
(!apu.wave.enabled || apu.wave.timer > tCycles) {
apu.frameSequencerCycles += tCycles;
if apu.pulse1.enabled { apu.pulse1.timer -= tCycles; }
if apu.pulse2.enabled { apu.pulse2.timer -= tCycles; }
if apu.pulse1.enabled {
apu.pulse1.timer -= tCycles;
if apu.pulse1.dacEnabled {
var units = apu.pulse1.envelope.volume * (tCycles as int32);
if ((PulseDutyMasks[apu.pulse1.duty as uint] >> apu.pulse1.dutyStep) & 1) == 0 { units = -units; }
apu.pulse1.sampleArea += units;
}
}
if apu.pulse2.enabled {
apu.pulse2.timer -= tCycles;
if apu.pulse2.dacEnabled {
var units = apu.pulse2.envelope.volume * (tCycles as int32);
if ((PulseDutyMasks[apu.pulse2.duty as uint] >> apu.pulse2.dutyStep) & 1) == 0 { units = -units; }
apu.pulse2.sampleArea += units;
}
}

var waveUnit: int32 = 0;
if apu.wave.enabled && apu.wave.dacEnabled && apu.wave.outputLevel != 0 {
Expand Down Expand Up @@ -894,8 +933,14 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
ClockFrameSequencer(apu);
}

// ch1(矩形波+スイープ)
// ch1(矩形波+スイープ)。区間平均への蓄積は周期タイマー前進の前
// (一括更新の経路と同じく「そのcycle開始時点の出力」を積む)。
if apu.pulse1.enabled {
if apu.pulse1.dacEnabled {
var units = apu.pulse1.envelope.volume;
if ((PulseDutyMasks[apu.pulse1.duty as uint] >> apu.pulse1.dutyStep) & 1) == 0 { units = -units; }
apu.pulse1.sampleArea += units;
}
apu.pulse1.timer -= 1;
if apu.pulse1.timer <= 0 {
apu.pulse1.timer += PulsePeriod(apu.pulse1.frequency);
Expand All @@ -904,6 +949,11 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
}
// ch2(矩形波)
if apu.pulse2.enabled {
if apu.pulse2.dacEnabled {
var units = apu.pulse2.envelope.volume;
if ((PulseDutyMasks[apu.pulse2.duty as uint] >> apu.pulse2.dutyStep) & 1) == 0 { units = -units; }
apu.pulse2.sampleArea += units;
}
apu.pulse2.timer -= 1;
if apu.pulse2.timer <= 0 {
apu.pulse2.timer += PulsePeriod(apu.pulse2.frequency);
Expand Down Expand Up @@ -957,6 +1007,14 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {
if apu.sampleCounter >= 4194304 {
apu.sampleCounter -= 4194304;

var pulse1Units: int32 = 0;
var pulse2Units: int32 = 0;
if apu.wave.sampleCycles > 0 {
pulse1Units = apu.pulse1.sampleArea / apu.wave.sampleCycles;
pulse2Units = apu.pulse2.sampleArea / apu.wave.sampleCycles;
}
apu.pulse1.sampleArea = 0;
apu.pulse2.sampleArea = 0;
var waveUnits: int32 = 0;
if apu.wave.sampleCycles > 0 {
if WaveAboveNyquist(apu.wave.frequency) {
Expand All @@ -977,7 +1035,7 @@ pub func ApuTick(apu: *var Apu, tCycles: int) {

var left: int16 = 0;
var right: int16 = 0;
MixSample(apu, waveUnits, noiseUnits, @left, @right);
MixSample(apu, pulse1Units, pulse2Units, waveUnits, noiseUnits, @left, @right);
PushSample(apu, left, right);
}

Expand All @@ -998,22 +1056,22 @@ func ScaleUnitsToI16(v: int64) -> int16 {

/// 4chをNR51パンニング・NR50マスター音量で混合し、ステレオi16サンプル1組を
/// 返す。電源off中は無音(0,0)。waveUnits/noiseUnitsは呼び出し元(ApuTick)が
/// 区間平均(またはナイキスト超えフォールバック)で計算済みの-15..15単位。
/// Pulse/Noiseは瞬時値の単位をここで計算する。
/// 区間平均(waveはナイキスト超えで1周期平均へフォールバック)で計算済みの
/// -15..15単位。
///
/// スケーリング(浮動小数点を使わない固定小数点計算): 元の設計は
/// 各ch出力(-1.0..1.0に正規化) * 0.25 * masterVol(1/8..1) * 32767 だが、
/// 単位を-15..15のまま持ち回るため、分母を15*8*4=480にまとめて
/// 最後に一度だけ除算する。
func MixSample(apu: *Apu, waveUnits: int32, noiseUnits: int32, left: *var int16, right: *var int16) {
func MixSample(apu: *Apu, pulse1Units: int32, pulse2Units: int32, waveUnits: int32, noiseUnits: int32, left: *var int16, right: *var int16) {
if !apu.poweredOn {
*left = 0;
*right = 0;
return;
}

let ch1 = PulseOutputUnits(@apu.pulse1);
let ch2 = PulseOutputUnits(@apu.pulse2);
let ch1 = pulse1Units;
let ch2 = pulse2Units;
let ch3 = waveUnits;
let ch4 = noiseUnits;

Expand Down
1 change: 1 addition & 0 deletions Packages/Core/Src/SaveState.rux
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ func ReadPulseChannel(c: *var ReadCursor, ch: *var PulseChannel) {
ch.timer = GetI32(c);
ReadEnvelope(c, @ch.envelope);
ReadSweep(c, @ch.sweep);
ch.sampleArea = 0; // 保存対象外(Apu.rux の PulseChannel.sampleArea 参照)
}

func WriteWaveChannel(c: *var WriteCursor, ch: *WaveChannel) {
Expand Down
Loading