From 0df3df09d1a9795f8b63e4d0c1a94f71f8e8c3d1 Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:10:50 +0530 Subject: [PATCH 1/8] feat(audio): introduce reversible quality DSP and learning overlay --- fc/spatial-audio/experimental/apply.py | 223 +++++++++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 fc/spatial-audio/experimental/apply.py diff --git a/fc/spatial-audio/experimental/apply.py b/fc/spatial-audio/experimental/apply.py new file mode 100644 index 00000000000..c2e5bccd133 --- /dev/null +++ b/fc/spatial-audio/experimental/apply.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Build-only, reversible DSP/learning experiment layered over FC's proven engine. + +The stable FC spatial audio source is untouched. All edits target generated +app source AFTER fc/spatial-audio/apply.py and stop on upstream drift. +""" +from pathlib import Path +import re +import shutil + +ROOT = Path(__file__).resolve().parents[3] +EXPERIMENT = Path(__file__).resolve().parent +PROCESSOR = ROOT / "app/src/main/java/com/music/zenith/playback/SpatialAudioProcessor.kt" +LEARNER = ROOT / "app/src/main/java/com/music/zenith/playback/SpatialAudioLearning.kt" +TEST = ROOT / "app/src/test/java/com/music/zenith/playback/SpatialAudioQualityTest.kt" + + +def active() -> bool: + config = (EXPERIMENT / "config.properties").read_text(encoding="utf-8") + modes = re.findall(r"(?m)^enabled=(true|false)$", config) + if len(modes) != 1: + raise SystemExit("Spatial audio experiment requires exactly one enabled=true/false") + return modes[0] == "true" + + +def replace(text: str, before: str, after: str, count: int = 1) -> str: + hits = text.count(before) + if hits != count: + raise SystemExit( + f"Spatial quality overlay refused to patch: expected {count} anchors " + f"but found {hits}: {before[:85]!r}" + ) + return text.replace(before, after) + + +def upgrade_processor(text: str) -> str: + # Modest widening and crossfeed changes, not a different DSP architecture. + text = replace(text, "private val widthGain = 2.5f", "private val widthGain = 2.0f") + text = replace(text, "private val outputGain = 0.82f", "private val outputGain = 0.86f") + text = replace(text, "private val crossfeedGain = 0.2f", "private val crossfeedGain = 0.16f") + text = replace(text, "private val lowpassCoeff = 0.3f", "private var lowpassCoeff = 0.3f") + text = replace(text, "const val DELAY_MS = 15", "const val DELAY_MS = 12") + text = replace( + text, + " if (sampleRate > 0) {\n profileAccumulator?", + " if (sampleRate > 0) {\n" + " // Stable cutoff in Hz across 44.1, 48 and 96 kHz outputs.\n" + " lowpassCoeff = (1.0 - kotlin.math.exp(\n" + " -2.0 * kotlin.math.PI * 1600.0 / sampleRate.toDouble()\n" + " )).toFloat()\n" + " profileAccumulator?", + ) + + # Hard sample-peak ceiling with common L/R gain and fast attack, slow recovery. + # A shared gain avoids image wandering between channels. + text = replace( + text, + " private var mix = 0f\n", + " private var mix = 0f\n" + " private var limiterGain = 1f\n" + " private val peakCeiling = 0.98f\n", + ) + text = replace( + text, " val step = rampStep()\n", + " val step = rampStep()\n val releaseStep = limiterReleaseStep()\n", + count=2, + ) + text = replace( + text, " if (mix == 0f && target == 0f) {\n", + " if (mix == 0f && target == 0f) {\n limiterGain = 1f\n", + count=2, + ) + text = replace( + text, + " block.samples[idx] = if (mix >= 1f) wetLeft else left + (wetLeft - left) * mix\n" + " block.samples[idx + 1] = if (mix >= 1f) wetRight else right + (wetRight - right) * mix", + " val mixedLeft = if (mix >= 1f) wetLeft else left + (wetLeft - left) * mix\n" + " val mixedRight = if (mix >= 1f) wetRight else right + (wetRight - right) * mix\n" + " val peak = maxOf(kotlin.math.abs(mixedLeft), kotlin.math.abs(mixedRight))\n" + " val required = if (mix > 0f && peak > peakCeiling) peakCeiling / peak else 1f\n" + " limiterGain = if (required < limiterGain) required else minOf(1f, limiterGain + releaseStep)\n" + " block.samples[idx] = mixedLeft * limiterGain\n" + " block.samples[idx + 1] = mixedRight * limiterGain", + ) + text = replace( + text, + " val outLeft = if (mix >= 1f) wetLeft else left + (wetLeft - left) * mix\n" + " val outRight = if (mix >= 1f) wetRight else right + (wetRight - right) * mix\n" + " outputBuffer.putShort(PcmBoundary.clamp16FromFloat(outLeft))\n" + " outputBuffer.putShort(PcmBoundary.clamp16FromFloat(outRight))", + " val outLeft = if (mix >= 1f) wetLeft else left + (wetLeft - left) * mix\n" + " val outRight = if (mix >= 1f) wetRight else right + (wetRight - right) * mix\n" + " val peak = maxOf(kotlin.math.abs(outLeft), kotlin.math.abs(outRight))\n" + " val required = if (mix > 0f && peak > peakCeiling) peakCeiling / peak else 1f\n" + " limiterGain = if (required < limiterGain) required else minOf(1f, limiterGain + releaseStep)\n" + " outputBuffer.putShort(PcmBoundary.clamp16FromFloat(outLeft * limiterGain))\n" + " outputBuffer.putShort(PcmBoundary.clamp16FromFloat(outRight * limiterGain))", + ) + text = replace( + text, + " dIdx = (dIdx + 1) % delaySize", + " dIdx++\n if (dIdx == delaySize) dIdx = 0", + count=2, + ) + text = replace( + text, + " private fun rampStep(): Float =\n" + " if (sampleRate > 0) 1000f / (sampleRate * RAMP_MS) else 1f\n", + " private fun rampStep(): Float =\n" + " if (sampleRate > 0) 1000f / (sampleRate * RAMP_MS) else 1f\n" + "\n" + " private fun limiterReleaseStep(): Float =\n" + " if (sampleRate > 0) 1000f / (sampleRate * 250f) else 1f\n", + ) + text = replace( + text, + " override fun onFlush() {\n snapMix = true\n", + " override fun onFlush() {\n snapMix = true\n limiterGain = 1f\n", + ) + text = replace( + text, + " override fun onReset() {\n delayLeft = FloatArray(0)\n", + " override fun onReset() {\n limiterGain = 1f\n delayLeft = FloatArray(0)\n", + ) + + # No ByteBuffer duplicate per dry audio block. Use absolute reads with no position changes. + text = replace( + text, + " val view = input.duplicate().order(ByteOrder.nativeOrder())\n" + " val start = view.position()\n" + " val availableFrames = view.remaining() / BYTES_PER_FRAME", + " val start = input.position()\n" + " val availableFrames = input.remaining() / BYTES_PER_FRAME", + ) + text = replace( + text, + " view.position(start + frame * BYTES_PER_FRAME)\n" + " observeFrame(accumulator, view.short.toDouble() * scale, view.short.toDouble() * scale)", + " val offset = start + frame * BYTES_PER_FRAME\n" + " observeFrame(accumulator, input.getShort(offset).toDouble() * scale,\n" + " input.getShort(offset + 2).toDouble() * scale)", + ) + text = replace( + text, + " val frameCount = inputBuffer.remaining() / BYTES_PER_FRAME\n", + " inputBuffer.order(ByteOrder.nativeOrder())\n" + " val frameCount = inputBuffer.remaining() / BYTES_PER_FRAME\n", + ) + + # One-shot callbacks are dispatched off the real-time thread on a shared + # prestarted, bounded worker (no per-block callback allocations). + text = replace( + text, + " if (profile.isUsable) {\n" + " onProfileReady?.invoke(accumulator.trackId, accumulator.title, accumulator.artist, profile)\n" + " }\n", + " if (profile.isUsable) {\n" + " val callback = onProfileReady\n" + " if (callback != null) {\n" + " val trackId = accumulator.trackId\n" + " val title = accumulator.title\n" + " val artist = accumulator.artist\n" + " PROFILE_DISPATCH.execute { callback(trackId, title, artist, profile) }\n" + " }\n" + " }\n", + ) + text = replace( + text, + " private companion object {\n", + " private companion object {\n" + " // One background worker shared by both crossfade processors; tasks are bounded.\n" + " private val PROFILE_DISPATCH = java.util.concurrent.ThreadPoolExecutor(\n" + " 1, 1, 0L, java.util.concurrent.TimeUnit.MILLISECONDS,\n" + " java.util.concurrent.ArrayBlockingQueue(32),\n" + " java.util.concurrent.ThreadFactory { task ->\n" + " Thread(task, \"FC-SpatialProfile\").apply { isDaemon = true }\n" + " },\n" + " java.util.concurrent.ThreadPoolExecutor.DiscardPolicy(),\n" + " ).apply { prestartAllCoreThreads() }\n" + ) + return text + + +def upgrade_learner(text: str) -> str: + # Be conservative about Auto Off; On remains the safe existing default. + text = replace( + text, + "private const val CONFIDENCE_THRESHOLD = 0.75", + "private const val CONFIDENCE_THRESHOLD = 0.80\n" + " private const val AUTO_OFF_THRESHOLD = 0.85" + ) + text = replace( + text, + "private const val MIN_EFFECTIVE_NEIGHBOURS = 3.0", + "private const val MIN_EFFECTIVE_NEIGHBOURS = 3.5" + ) + text = replace( + text, + " onShare <= 1.0 - CONFIDENCE_THRESHOLD -> SpatialAudioDecisionReason.AUTO_LEARNED_OFF", + " onShare <= 1.0 - AUTO_OFF_THRESHOLD -> SpatialAudioDecisionReason.AUTO_LEARNED_OFF" + ) + return text + + +def main() -> None: + if not active(): + print("Experimental Spatial Audio quality overlay disabled: original engine unchanged.") + return + if not PROCESSOR.is_file() or not LEARNER.is_file(): + raise SystemExit("FC's stable Spatial Audio overlay must run before the experimental overlay") + processor = upgrade_processor(PROCESSOR.read_text(encoding="utf-8")) + learner = upgrade_learner(LEARNER.read_text(encoding="utf-8")) + # All compatibility anchors validated before any source write. + PROCESSOR.write_text(processor, encoding="utf-8") + LEARNER.write_text(learner, encoding="utf-8") + TEST.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(EXPERIMENT / "SpatialAudioQualityTest.kt", TEST) + print("Experimental Spatial Audio upgrade active: sample-peak safety, rate-aware crossfeed,") + print("allocation-free PCM16 profiling, async profile callback, guarded Auto learning, DSP tests.") + + +if __name__ == "__main__": + main() From 277dbab82ac4c9796c1f74629f0189241188f418 Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:13:00 +0530 Subject: [PATCH 2/8] test(audio): add sample-peak, PCM16, rate, callback and learning regression coverage --- .../experimental/SpatialAudioQualityTest.kt | 219 ++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 fc/spatial-audio/experimental/SpatialAudioQualityTest.kt diff --git a/fc/spatial-audio/experimental/SpatialAudioQualityTest.kt b/fc/spatial-audio/experimental/SpatialAudioQualityTest.kt new file mode 100644 index 00000000000..2e49ba27817 --- /dev/null +++ b/fc/spatial-audio/experimental/SpatialAudioQualityTest.kt @@ -0,0 +1,219 @@ +package com.music.zenith.playback + +import com.music.zenith.playback.audio.AudioBlock +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.sin +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Production-gated checks only for the removable FC quality experiment. */ +class SpatialAudioQualityTest { + private fun block(frames: Int = 4096, left: Float, right: Float): AudioBlock { + val result = AudioBlock(channelCount = 2, capacityFrames = frames) + for (i in 0 until frames) { + result.samples[i * 2] = left + result.samples[i * 2 + 1] = right + } + result.setFrameCount(frames) + return result + } + + private fun peak(block: AudioBlock): Float { + var max = 0f + for (i in 0 until block.sampleCount) max = maxOf(max, abs(block.samples[i])) + return max + } + + private fun processor(rate: Int, on: Boolean = true) = SpatialAudioProcessor().apply { + learningEnabled = false + configure(rate, 2) + enabled = on + } + + @Test fun aggressiveAntiphaseRemainsBelowSamplePeakCeiling() { + for (rate in listOf(44_100, 48_000, 96_000)) { + val dsp = processor(rate) + val audio = block(left = 0.99f, right = -0.99f) + repeat(3) { + dsp.process(audio) + assertTrue("sample peak at " + rate + " Hz: " + peak(audio), peak(audio) <= 0.981f) + assertTrue(audio.samples.all { it.isFinite() }) + } + } + } + + @Test fun ordinaryStereoSignalsNeverProduceNonFiniteSamples() { + for (rate in listOf(44_100, 48_000, 96_000)) { + val dsp = processor(rate) + val audio = AudioBlock(channelCount = 2, capacityFrames = 4096) + repeat(4096) { frame -> + audio.samples[frame * 2] = + (0.96 * sin(2.0 * PI * 440 * frame / rate)).toFloat() + audio.samples[frame * 2 + 1] = + (0.93 * sin(2.0 * PI * 447 * frame / rate)).toFloat() + } + audio.setFrameCount(4096) + repeat(4) { + dsp.process(audio) + assertTrue("bad output at $rate Hz", audio.samples.all { it.isFinite() }) + assertTrue("clipped output at $rate Hz", peak(audio) <= 0.981f) + } + } + } + + @Test fun disabledProcessingIsBitExactForFloat32() { + for (rate in listOf(44_100, 48_000, 96_000)) { + val dsp = processor(rate, on = false) + val audio = block(left = 0.751f, right = -0.623f) + val original = audio.samples.copyOf() + repeat(5) { + dsp.process(audio) + assertArrayEquals(original, audio.samples, 0f) + } + } + } + + @Test fun offToOnAndBackCannotGenerateOutOfRangeFloatSamples() { + val dsp = processor(48_000, on = false) + var audio = block(left = 0.88f, right = -0.88f) + dsp.process(audio) + dsp.enabled = true + repeat(6) { + audio = block(left = 0.88f, right = -0.88f) + dsp.process(audio) + assertTrue(peak(audio) <= 0.981f) + } + dsp.enabled = false + repeat(8) { + audio = block(left = 0.88f, right = -0.88f) + dsp.process(audio) + assertTrue(peak(audio) <= 0.981f) + } + } + + @Test fun monoFloatPlaybackRemainsUntouched() { + val dsp = SpatialAudioProcessor().apply { + configure(48_000, 1) + enabled = true + } + val mono = AudioBlock(channelCount = 1, capacityFrames = 128) + for (i in mono.samples.indices) mono.samples[i] = (i - 64) / 128f + mono.setFrameCount(128) + val original = mono.samples.copyOf() + dsp.process(mono) + assertArrayEquals(original, mono.samples, 0f) + } + + @Test fun pcm16BypassPreservesSamplesAndBufferPosition() { + val dsp = processor(48_000, on = false) + val input = ByteBuffer.allocateDirect(4096 * 4).order(ByteOrder.nativeOrder()) + repeat(4096) { + input.putShort(12345.toShort()) + input.putShort((-12345).toShort()) + } + input.flip() + dsp.queueInput(input) + assertEquals(input.limit(), input.position()) + val output = dsp.getOutput().order(ByteOrder.nativeOrder()) + assertEquals(4096 * 4, output.remaining()) + repeat(4096) { + assertEquals(12345, output.short.toInt()) + assertEquals(-12345, output.short.toInt()) + } + } + + @Test fun pcm16WideningNeverWrapsOrHardClips() { + val dsp = processor(48_000) + val input = ByteBuffer.allocateDirect(4096 * 4).order(ByteOrder.nativeOrder()) + repeat(4096) { + input.putShort(32000.toShort()) + input.putShort((-32000).toShort()) + } + input.flip() + dsp.queueInput(input) + val output = dsp.getOutput().order(ByteOrder.nativeOrder()) + assertEquals(4096 * 4, output.remaining()) + while (output.hasRemaining()) { + assertTrue("PCM16 sample was clipped or wrapped", abs(output.short.toInt()) <= 32120) + } + } + + @Test fun profileCompletionCallbackRunsOffPlaybackThread() { + val dsp = SpatialAudioProcessor() + dsp.configure(48_000, 2) + dsp.setTrackContext("test-track", "Track", "Artist") + dsp.enabled = true + val latch = CountDownLatch(1) + val callbackThread = AtomicReference() + dsp.onProfileReady = { _, _, _, profile -> + if (profile.isUsable) { + callbackThread.set(Thread.currentThread().name) + latch.countDown() + } + } + val input = block(left = 0.30f, right = -0.25f) + repeat(100) { dsp.process(input) } + assertTrue("profile callback not delivered", latch.await(5, TimeUnit.SECONDS)) + assertEquals("FC-SpatialProfile", callbackThread.get()) + } + + private fun audioProfile() = SpatialAudioProfile( + sampleRateHz = 6_000, + frameCount = 6_000L * 8, + stereoWidth = 0.72f, + channelCorrelation = 0.25f, + lowFrequencySideRatio = 0.31f, + highFrequencyRatio = 0.39f, + crestFactor = 3.4f, + rms = 0.14f, + ) + private fun example(i: Int, feedback: SpatialAudioFeedback) = + SpatialAudioExample("song-$i", "Artist $i", feedback, audioProfile()) + + private fun recommend(items: List): SpatialAudioDecision = + SpatialAudioLearner.decide( + mode = SpatialAudioMode.AUTO, + preference = SpatialAudioPreference.AUTO, + profile = audioProfile(), + artist = "Unknown", + examples = items, + learningEnabled = true, + isPhoneSpeaker = false, + allowOnPhoneSpeaker = false, + isDolbyAtmos = false, + dspAvailable = true, + ) + + @Test fun fourOfFiveOffLabelsAreNotYetConfidentEnoughToDisableAuto() { + val decision = recommend( + (1..4).map { example(it, SpatialAudioFeedback.OFF) } + + example(5, SpatialAudioFeedback.ON) + ) + assertTrue(decision.enabled) + assertEquals(SpatialAudioDecisionReason.AUTO_UNCERTAIN, decision.reason) + } + + @Test fun fourStrongOffLabelsCanStillTeachAutoOff() { + val decision = recommend((1..4).map { example(it, SpatialAudioFeedback.OFF) }) + assertFalse(decision.enabled) + assertEquals(SpatialAudioDecisionReason.AUTO_LEARNED_OFF, decision.reason) + } + + @Test fun fourOfFivePositiveLabelsCanStillTeachAutoOn() { + val decision = recommend( + (1..4).map { example(it, SpatialAudioFeedback.ON) } + + example(5, SpatialAudioFeedback.OFF) + ) + assertTrue(decision.enabled) + assertEquals(SpatialAudioDecisionReason.AUTO_LEARNED_ON, decision.reason) + } +} From a30aaa257cfd921d5f60ebbd9e6bae939b615977 Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:13:09 +0530 Subject: [PATCH 3/8] feat(audio): enable reversible experimental quality layer for validated release --- fc/spatial-audio/experimental/config.properties | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 fc/spatial-audio/experimental/config.properties diff --git a/fc/spatial-audio/experimental/config.properties b/fc/spatial-audio/experimental/config.properties new file mode 100644 index 00000000000..a4790119071 --- /dev/null +++ b/fc/spatial-audio/experimental/config.properties @@ -0,0 +1,3 @@ +# Temporary optional DSP quality layer. Set false to restore the last verified FC engine. +# Any change from the previously shipped flag triggers a versioned APK release. +enabled=true From 3d42ca8e3c09c0d4dda7f5ec8f67ad886a46612d Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:14:46 +0530 Subject: [PATCH 4/8] ci(audio): gate temporary quality overlay and bump version on enable or rollback --- .github/workflows/fc-sync-release.yml | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/.github/workflows/fc-sync-release.yml b/.github/workflows/fc-sync-release.yml index 911e1431079..92ec06550d8 100644 --- a/.github/workflows/fc-sync-release.yml +++ b/.github/workflows/fc-sync-release.yml @@ -139,6 +139,13 @@ jobs: set -euo pipefail CURRENT_UPSTREAM_VERSION="$(sed -n 's/^upstreamVersion=//p' fc/version.properties)" VERSION_NAME="$(sed -n 's/^versionName=//p' fc/version.properties)" + EXPERIMENT_ENABLED="$(sed -n 's/^enabled=//p' fc/spatial-audio/experimental/config.properties)" + LAST_EXPERIMENT_ENABLED="$(sed -n 's/^experimentalAudio=//p' fc/version.properties)" + LAST_EXPERIMENT_ENABLED="${LAST_EXPERIMENT_ENABLED:-false}" + if [[ "$EXPERIMENT_ENABLED" != "true" && "$EXPERIMENT_ENABLED" != "false" ]]; then + echo "Invalid experimental spatial audio flag" >&2 + exit 1 + fi if [[ -z "$CURRENT_UPSTREAM_VERSION" || -z "$VERSION_NAME" ]]; then echo "Missing FC upstreamVersion/versionName metadata." >&2 exit 1 @@ -152,7 +159,7 @@ jobs: release_asset_exists=true fi - if [[ "$UPSTREAM_VERSION" != "$CURRENT_UPSTREAM_VERSION" || "$UPSTREAM_CHANGED" == "true" ]]; then + if [[ "$UPSTREAM_VERSION" != "$CURRENT_UPSTREAM_VERSION" || "$UPSTREAM_CHANGED" == "true" || "$EXPERIMENT_ENABLED" != "$LAST_EXPERIMENT_ENABLED" ]]; then # A new stable series starts at .1; new main commits in that series increment the FC revision. python3 fc/bump-version.py "$UPSTREAM_VERSION" should_release=true @@ -167,6 +174,11 @@ jobs: should_release=false fi + if [[ "$should_release" == "true" ]]; then + # Record the shipped variant after a release is selected; flag changes bump version. + sed -i '/^experimentalAudio=/d' fc/version.properties + printf 'experimentalAudio=%s\n' "$EXPERIMENT_ENABLED" >> fc/version.properties + fi VERSION_CODE="$(sed -n 's/^versionCode=//p' fc/version.properties)" VERSION_NAME="$(sed -n 's/^versionName=//p' fc/version.properties)" echo "should_release=$should_release" >> "$GITHUB_OUTPUT" @@ -252,6 +264,14 @@ jobs: echo "included=true" >> "$GITHUB_OUTPUT" fi + - name: Apply temporary Spatial Audio quality experiment + id: spatial_quality + if: steps.decision.outputs.should_release == 'true' + shell: bash + run: | + set -euo pipefail + python3 fc/spatial-audio/experimental/apply.py + echo "enabled=$(sed -n 's/^enabled=//p' fc/spatial-audio/experimental/config.properties)" >> "$GITHUB_OUTPUT" - name: Fill missing Android locale fallbacks for this build if: steps.decision.outputs.should_release == 'true' run: | @@ -442,6 +462,7 @@ jobs: app/src/main/java/com/music/zenith/playback/SpatialAudioDecisionEngine.kt app/src/main/java/com/music/zenith/TopBarActionVisibility.kt app/src/test/java/com/music/zenith/playback/SpatialAudioLearningTest.kt + app/src/test/java/com/music/zenith/playback/SpatialAudioQualityTest.kt app/src/test/java/com/music/zenith/playback/SpatialAudioPreferenceTest.kt app/src/test/java/com/music/zenith/playback/SpatialAudioDecisionEngineTest.kt ) @@ -510,6 +531,7 @@ jobs: - Includes ${{ steps.upstream.outputs.commits_ahead }} upstream commits beyond the stable baseline when built as a main snapshot. - FC Zenith follows upstream main automatically. Every new source snapshot must pass tests, build and signature verification before publishing. - The same FC signing certificate is checked before publishing. + - Experimental DSP quality layer: ${{ steps.spatial_quality.outputs.enabled }} (reversible; includes audio regression tests). - Spatial Audio: ${{ steps.spatial_audio.outputs.included == 'true' && 'Includes the persistent FC stereo learner, binary per-track On/Off with Auto status, and phone-speaker/Atmos/DSP safety bypasses. Profiles and explicit feedback remain on-device.' || 'Not included in this build.' }} Obtainium source: https://github.com/Batmancpu/FCZenith From 0975247d016b37b1674aa536eaacab12199452a3 Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:15:54 +0530 Subject: [PATCH 5/8] fix(audio): account for floating point equality at 80% learning threshold --- fc/spatial-audio/experimental/apply.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/fc/spatial-audio/experimental/apply.py b/fc/spatial-audio/experimental/apply.py index c2e5bccd133..afa5f8783d4 100644 --- a/fc/spatial-audio/experimental/apply.py +++ b/fc/spatial-audio/experimental/apply.py @@ -194,6 +194,11 @@ def upgrade_learner(text: str) -> str: "private const val MIN_EFFECTIVE_NEIGHBOURS = 3.0", "private const val MIN_EFFECTIVE_NEIGHBOURS = 3.5" ) + text = replace( + text, + " onShare >= CONFIDENCE_THRESHOLD -> SpatialAudioDecisionReason.AUTO_LEARNED_ON", + " onShare + 1.0e-9 >= CONFIDENCE_THRESHOLD -> SpatialAudioDecisionReason.AUTO_LEARNED_ON", + ) text = replace( text, " onShare <= 1.0 - CONFIDENCE_THRESHOLD -> SpatialAudioDecisionReason.AUTO_LEARNED_OFF", From 16c209149658cb148874a293b91b0595b452008e Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:16:23 +0530 Subject: [PATCH 6/8] docs(audio): describe reversible DSP design, measured tests and hardware QA limits --- fc/spatial-audio/experimental/README.md | 55 +++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 fc/spatial-audio/experimental/README.md diff --git a/fc/spatial-audio/experimental/README.md b/fc/spatial-audio/experimental/README.md new file mode 100644 index 00000000000..ec2e9571de7 --- /dev/null +++ b/fc/spatial-audio/experimental/README.md @@ -0,0 +1,55 @@ +# Temporary FC Spatial Audio quality experiment + +This layer is **optional and removable**. It is applied only to the generated +Android sources in the GitHub Actions build workspace, *after* +`fc/spatial-audio/apply.py`. The existing tested permanent FC Spatial Audio +engine is preserved byte-for-byte in `fc/spatial-audio/SpatialAudioProcessor.kt` +and `SpatialAudioLearning.kt`. + +## What changes when enabled + +- Reduce mid/side gain from 2.5 to 2.0 and crossfeed from 0.20 to 0.16; shorten + crossfeed delay to 12 ms to reduce aggressive image expansion. +- Calculate the one-pole crossfeed low-pass from a 1.6-kHz cutoff and the actual + sample rate instead of reusing a fixed coefficient at 44.1/48/96 kHz. +- Add a common-L/R, fast-attack sample-peak limiter with 0.98 ceiling and + 250-ms release. It protects the DSP path while preserving a bit-exact bypass + when disabled. This is **not a true-peak/oversampling limiter**; real-device + listening and intersample-peak verification remain necessary. +- Remove per-block ByteBuffer duplication during PCM16 analysis and replace + delay ring modulo with a wrap comparison. Publish completed audio-profile + fingerprints on one bounded pre-started worker, not on the audio callback. +- Increase the effective-independent-evidence requirement from 3.0 to 3.5 and + raise the Auto On/Off confidence gates to 80% / 85%, respectively. Existing + explicit On/Off choices and all safety bypasses remain authoritative. +- Add `SpatialAudioQualityTest.kt` to the production unit-test suite covering + sample peaks and numeric safety across 44.1/48/96 kHz, PCM16 bypass and + limiting, bit-exact disabled Float32, mono bypass, background completion, + toggling and conservative Auto learning. + +## Release and rollback + +Set `enabled=true` in `config.properties` to opt in. Set `enabled=false` +to return to the original FC Spatial Audio implementation. Committing a flag +change to main triggers a new numbered release, with strictly increasing +Android versionCode and unchanged signing certificate, app package, brrMusic +branding, Fluid Cloud compatibility and existing preferences. + +The workflow restores every generated Kotlin file and test to the upstream +checkout before committing to main. The stable integration assets themselves +remain unchanged. Missing exact patch anchors abort the release. + +## QA evidence and limitations + +CI unit tests and an APK build can establish compilation, the algorithmic +sample-peak ceiling, deterministic bypass and release signing. They cannot +certify subjective sound quality, perceptual spaciousness, end-to-end true +peaks or device-specific output behavior. + +Before declaring this engine the preferred permanent version, perform A/B +listening against the baseline signed APK on wired headphones, Bluetooth and +USB DAC, with low and high volumes. Verify phone-speaker and Dolby Atmos +bypasses, Fluid Cloud and crossfade behavior on physical devices. Look for +vocal coloration, pumping, fatigue, clipping and dropouts. If regressions +appear, switch the flag off and issue a new release without changing +upstream application code. From ae1f1d09ec2931094333158a0453341b84bd7b93 Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:17:17 +0530 Subject: [PATCH 7/8] ci(audio): validate proposed spatial DSP with isolated PR production tests --- .../workflows/fc-spatial-quality-verify.yml | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 .github/workflows/fc-spatial-quality-verify.yml diff --git a/.github/workflows/fc-spatial-quality-verify.yml b/.github/workflows/fc-spatial-quality-verify.yml new file mode 100644 index 00000000000..1cc0fc80115 --- /dev/null +++ b/.github/workflows/fc-spatial-quality-verify.yml @@ -0,0 +1,119 @@ +name: FC Spatial Audio — isolated quality validation + +on: + pull_request: + branches: [main] + paths: + - 'fc/spatial-audio/experimental/**' + - '.github/workflows/fc-sync-release.yml' + - '.github/workflows/fc-spatial-quality-verify.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: fc-spatial-verify-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + verify-quality-engine: + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - name: Checkout proposed sources + uses: actions/checkout@v4 + with: + fetch-depth: 0 + lfs: true + + - name: JDK 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Gradle cache + uses: gradle/actions/setup-gradle@v4 + + - name: Install native Android tools + shell: bash + run: | + set -euo pipefail + SDKM="${ANDROID_HOME:-/usr/local/lib/android/sdk}/cmdline-tools/latest/bin/sdkmanager" + yes | "$SDKM" --licenses > /dev/null || true + "$SDKM" 'cmake;3.22.1' 'ndk;27.0.12077973' + + - name: Install icon resizing dependency + run: python3 -m pip install --user Pillow + + - name: Apply the regular, then experimental, spatial overlays + shell: bash + run: | + set -euo pipefail + export FC_VERSION_CODE="$(sed -n 's/^versionCode=//p' fc/version.properties)" + export FC_VERSION_NAME="$(sed -n 's/^versionName=//p' fc/version.properties)" + python3 fc/apply-overlay.py + python3 fc/spatial-audio/apply.py + python3 fc/spatial-audio/experimental/apply.py + python3 fc/branding/apply.py + + - name: Fill missing Android locale fallbacks for this build + run: | + python3 - <<'PY' + import copy + import xml.etree.ElementTree as ET + from pathlib import Path + + base_path = Path("app/src/main/res/values/strings.xml") + base_root = ET.parse(base_path).getroot() + supported = {"string", "plurals", "string-array"} + base_entries = {} + for element in list(base_root): + name = element.attrib.get("name") + if (element.tag in supported and name + and element.attrib.get("translatable") != "false"): + if name in base_entries: + raise SystemExit(f"Duplicate base Android resource: {name}") + base_entries[name] = element + + for qualifier in ("values-in", "values-ko"): + locale_path = Path("app/src/main/res") / qualifier / "strings.xml" + locale_tree = ET.parse(locale_path) + locale_root = locale_tree.getroot() + locale_entries = {} + for element in list(locale_root): + name = element.attrib.get("name") + if element.tag in supported and name: + locale_entries.setdefault(name, []).append(element) + + added = 0 + for name, base_element in base_entries.items(): + existing = locale_entries.get(name, []) + if any(item.attrib.get("translatable") != "false" for item in existing): + continue + + # Replace a locale-specific translatable=false placeholder if one + # exists; otherwise append the same English fallback Android + # would resolve at runtime. Existing translations are untouched. + for item in existing: + locale_root.remove(item) + locale_root.append(copy.deepcopy(base_element)) + added += 1 + + if added: + locale_tree.write(locale_path, encoding="utf-8", xml_declaration=True) + ET.parse(locale_path) # Fail here if generated XML is malformed. + print(f"{qualifier}: added {added} English fallback entries for this build.") + PY + + - name: Apply reversible brrMusic presentation overlay + if: steps.decision.outputs.should_release == 'true' + run: python3 fc/branding/apply.py + - name: Run all production unit tests, including new audio regressions + run: | + set -euo pipefail + chmod +x gradlew + FC_VERSION_CODE="$(sed -n 's/^versionCode=//p' fc/version.properties)" \ + FC_VERSION_NAME="$(sed -n 's/^versionName=//p' fc/version.properties)" \ + ./gradlew :app:testProdReleaseUnitTest --no-daemon --stacktrace From fd9ba0602f3215acbb8c81421224cc11d743ca29 Mon Sep 17 00:00:00 2001 From: Batmancpu Date: Sat, 14 Nov 2026 23:17:37 +0530 Subject: [PATCH 8/8] ci(audio): remove duplicate branding step from isolated verification --- .github/workflows/fc-spatial-quality-verify.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/fc-spatial-quality-verify.yml b/.github/workflows/fc-spatial-quality-verify.yml index 1cc0fc80115..e87e8356839 100644 --- a/.github/workflows/fc-spatial-quality-verify.yml +++ b/.github/workflows/fc-spatial-quality-verify.yml @@ -107,9 +107,6 @@ jobs: print(f"{qualifier}: added {added} English fallback entries for this build.") PY - - name: Apply reversible brrMusic presentation overlay - if: steps.decision.outputs.should_release == 'true' - run: python3 fc/branding/apply.py - name: Run all production unit tests, including new audio regressions run: | set -euo pipefail