From 529f1b664fa5b2a3dc88c73fa31ba41015d242f6 Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Sat, 26 Sep 2026 22:10:13 +0330 Subject: [PATCH 1/4] feat: Android hardware equalizer via AudioEffect (issue #28) Ships plugins/withEqualizer.js, a config plugin that re-creates the Kotlin module and package on every prebuild, because /android is gitignored and CI runs expo prebuild --clean. The effect attaches to the global output mix (session 0): neither kotlin-audio nor track-player exposes a sessionId to JS. Unsupported devices resolve supported:false instead of throwing. Setting: equalizerEnabled (declared, defaulted, sanitized). One flat toggle row plus band sliders in the existing playback section. --- app.json | 3 +- components/screens/SettingsScreen.tsx | 87 +++++++++++ lib/app-settings.ts | 7 + locales/en.json | 3 + locales/fa.json | 3 + modules/audioEqualizer.ts | 91 ++++++++++++ plugins/android/StreamifyEqualizerModule.kt | 143 +++++++++++++++++++ plugins/android/StreamifyEqualizerPackage.kt | 15 ++ plugins/withEqualizer.js | 72 ++++++++++ 9 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 modules/audioEqualizer.ts create mode 100644 plugins/android/StreamifyEqualizerModule.kt create mode 100644 plugins/android/StreamifyEqualizerPackage.kt create mode 100644 plugins/withEqualizer.js diff --git a/app.json b/app.json index 2fcb8ef..25009e8 100644 --- a/app.json +++ b/app.json @@ -30,7 +30,8 @@ } ], "react-native-video", - "expo-secure-store" + "expo-secure-store", + "./plugins/withEqualizer" ], "android": { "package": "com.erfanbagheri.streamifymobile", diff --git a/components/screens/SettingsScreen.tsx b/components/screens/SettingsScreen.tsx index 8688555..abf8b42 100644 --- a/components/screens/SettingsScreen.tsx +++ b/components/screens/SettingsScreen.tsx @@ -9,6 +9,13 @@ import { View, } from "react-native"; import { Ionicons } from "@expo/vector-icons"; +import Slider from "@react-native-community/slider"; +import { + getEqualizerInfo, + setEqualizerBandLevel, + setEqualizerEnabled, + type EqualizerInfo, +} from "../../modules/audioEqualizer"; import { APP_THEME_OPTIONS, SEEK_STEP_OPTIONS, @@ -355,6 +362,57 @@ function ThemeChoiceCard({ ); } +/** + * Band sliders, shown only when the setting is on and the device actually has + * an equalizer. Levels live in the system effect; nothing is persisted. + */ +function EqualizerBands({ colors }: { colors: ReturnType["colors"] }) { + const { t } = useAppLanguage(); + const [info, setInfo] = useState(null); + const [levels, setLevels] = useState([]); + + useEffect(() => { + let alive = true; + getEqualizerInfo().then((next) => { + if (!alive) return; + setInfo(next); + setLevels(next.levels); + }); + return () => { + alive = false; + }; + }, []); + + if (!info?.supported) { + return {t("settings.equalizerUnsupported")}; + } + + return ( + + {info.centerFreqHz.map((hz, index) => ( + + + {hz >= 1000 ? `${hz / 1000}k` : hz} + + { + setLevels((prev) => prev.map((v, i) => (i === index ? value : v))); + void setEqualizerBandLevel(index, value); + }} + accessibilityLabel={`${hz} Hz`} + /> + + ))} + + ); +} + export default function SettingsScreen({ navigation, }: { @@ -1150,6 +1208,31 @@ export default function SettingsScreen({ /> } /> + { + updateSettings({ equalizerEnabled: value }); + void setEqualizerEnabled(value); + }} + /> + } + /> + {settings.equalizerEnabled ? ( + } + /> + ) : null} ) : null} @@ -1527,6 +1610,10 @@ const styles = StyleSheet.create({ flexWrap: "wrap", gap: 8, }, + equalizerBand: { + minWidth: 72, + flexGrow: 1, + }, chip: { minHeight: 44, minWidth: 44, diff --git a/lib/app-settings.ts b/lib/app-settings.ts index 870c879..907edc2 100644 --- a/lib/app-settings.ts +++ b/lib/app-settings.ts @@ -88,6 +88,8 @@ export interface AppSettings { waveformSeekBar: boolean; /** Enable ReplayGain normalization on local/cached tracks. */ replayGainEnabled: boolean; + /** Enable the Android hardware equalizer on the output mix (issue #28). */ + equalizerEnabled: boolean; collapsedSettingsSections: Partial>; } @@ -171,6 +173,7 @@ export const DEFAULT_APP_SETTINGS: AppSettings = { crossfadeSeconds: 4, waveformSeekBar: false, replayGainEnabled: false, + equalizerEnabled: false, collapsedSettingsSections: {}, }; @@ -322,6 +325,10 @@ export function sanitizeAppSettings(value: unknown): AppSettings { typeof record.replayGainEnabled === "boolean" ? record.replayGainEnabled : DEFAULT_APP_SETTINGS.replayGainEnabled, + equalizerEnabled: + typeof record.equalizerEnabled === "boolean" + ? record.equalizerEnabled + : DEFAULT_APP_SETTINGS.equalizerEnabled, waveformSeekBar: typeof record.waveformSeekBar === "boolean" ? record.waveformSeekBar diff --git a/locales/en.json b/locales/en.json index 12c8bf2..4e21114 100644 --- a/locales/en.json +++ b/locales/en.json @@ -214,6 +214,9 @@ "waveformSeekDescription": "Show audio waveform on the seek bar (local/cached tracks, Android)", "replayGain": "ReplayGain normalization", "replayGainDescription": "Equalize loudness across tracks using embedded ReplayGain tags", + "equalizer": "Hardware equalizer", + "equalizerDescription": "Adjust frequency bands on the Android system equalizer", + "equalizerUnsupported": "This device has no system equalizer", "listenbrainz_scrobbling": "ListenBrainz scrobbling", "listenbrainz_scrobbling_desc": "Send your plays to ListenBrainz — open source music tracking.", "lastfm_scrobbling": "Last.fm scrobbling", diff --git a/locales/fa.json b/locales/fa.json index 7d08331..6659df4 100644 --- a/locales/fa.json +++ b/locales/fa.json @@ -214,6 +214,9 @@ "waveformSeekDescription": "نمایش موج صدا روی نوار جستجو (آهنگ‌های محلی/کش‌شده، اندروید)", "replayGain": "یکسان‌سازی بلندی صدا (ReplayGain)", "replayGainDescription": "تنظیم خودکار بلندی آهنگ‌ها با برچسب‌های ReplayGain", + "equalizer": "اکولایزر سخت‌افزاری", + "equalizerDescription": "تنظیم باندهای فرکانسی با اکولایزر سیستمی اندروید", + "equalizerUnsupported": "این دستگاه اکولایزر سیستمی ندارد", "listenbrainz_scrobbling": "اسکرابل لیسن‌برینز", "listenbrainz_scrobbling_desc": "پخش‌هایت را به ListenBrainz بفرست — ردیابی موسیقی متن‌باز.", "lastfm_scrobbling": "اسکرابل لست‌اف‌ام", diff --git a/modules/audioEqualizer.ts b/modules/audioEqualizer.ts new file mode 100644 index 0000000..66755cd --- /dev/null +++ b/modules/audioEqualizer.ts @@ -0,0 +1,91 @@ +/******************************************************************** + * audioEqualizer.ts - JS side of StreamifyEqualizerModule (issue #28) + * + * Android-only hardware equalizer on AudioEffect.EFFECT_TYPE_EQUALIZER, + * attached to the global output mix (session 0) because neither + * kotlin-audio nor track-player exposes a sessionId to JS. + * + * Web/iOS get a clean "unsupported" surface so call sites never need + * platform checks. Nothing here can throw into a playback path. + *******************************************************************/ +import { NativeModules, Platform } from "react-native"; + +export interface EqualizerInfo { + supported: boolean; + numberOfBands: number; + minMillibel: number; + maxMillibel: number; + levels: number[]; + centerFreqHz: number[]; +} + +type EqualizerNative = { + getInfo(): Promise; + setBandLevel(band: number, millibel: number): Promise; + setEnabled(enabled: boolean): Promise; +}; + +const native = (NativeModules as any).StreamifyEqualizerModule as + | EqualizerNative + | undefined; + +/** Surfaced when the Android binary was built without the config plugin. */ +export const EQUALIZER_LINK_ERROR = + "StreamifyEqualizerModule is not linked. Run `npx expo prebuild --clean` and rebuild the Android app."; + +const UNSUPPORTED: EqualizerInfo = { + supported: false, + numberOfBands: 0, + minMillibel: 0, + maxMillibel: 0, + levels: [], + centerFreqHz: [], +}; + +export const isEqualizerSupported = Platform.OS === "android" && Boolean(native); + +let linkErrorLogged = false; + +export async function getEqualizerInfo(): Promise { + if (Platform.OS !== "android") { + return UNSUPPORTED; + } + if (!native) { + if (!linkErrorLogged) { + linkErrorLogged = true; + console.warn(EQUALIZER_LINK_ERROR); + } + return UNSUPPORTED; + } + try { + return await native.getInfo(); + } catch { + return UNSUPPORTED; + } +} + +/** Resolves the millibel actually applied (native clamps), or null if absent. */ +export async function setEqualizerBandLevel( + band: number, + millibel: number, +): Promise { + if (!native || Platform.OS !== "android") { + return null; + } + try { + return await native.setBandLevel(band, millibel); + } catch { + return null; + } +} + +export async function setEqualizerEnabled(enabled: boolean): Promise { + if (!native || Platform.OS !== "android") { + return false; + } + try { + return await native.setEnabled(enabled); + } catch { + return false; + } +} diff --git a/plugins/android/StreamifyEqualizerModule.kt b/plugins/android/StreamifyEqualizerModule.kt new file mode 100644 index 0000000..cf17345 --- /dev/null +++ b/plugins/android/StreamifyEqualizerModule.kt @@ -0,0 +1,143 @@ +package com.erfanbagheri.streamifymobile + +import android.media.audiofx.AudioEffect +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.Promise +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReactContextBaseJavaModule +import com.facebook.react.bridge.ReactMethod + +/** + * Hardware equalizer (issue #28) on [AudioEffect.EFFECT_TYPE_EQUALIZER]. + * + * There is no `sessionId` reachable from JS (kotlin-audio and track-player + * do not expose the player session), so the effect is attached to the global + * session 0 — Android routes it onto the active output mix. + * + * A few devices/ROMs have no equalizer at all; [getInfo] then resolves + * `supported: false` instead of throwing, so the caller can hide the toggle. + * Every value coming from JS is clamped to what the device reports; JS input + * is never trusted. + */ +class StreamifyEqualizerModule(reactContext: ReactApplicationContext) : + ReactContextBaseJavaModule(reactContext) { + + override fun getName(): String = "StreamifyEqualizerModule" + + private var effect: AudioEffect? = null + + /** Attach to the global output mix, once. Null when unsupported. */ + private fun ensureEffect(): AudioEffect? { + effect?.let { return it } + val created = + try { + AudioEffect(0, AudioEffect.EFFECT_TYPE_EQUALIZER, 0) + } catch (_: Exception) { + return null + } + if (created.initState != AudioEffect.STATE_INITIALIZED) { + created.release() + return null + } + effect = created + return created + } + + private fun bandCount(eq: AudioEffect): Int = eq.numberOfBands.toInt().coerceAtLeast(0) + + /** Device-reported millibel window, or null when the effect exposes none. */ + private fun levelRange(eq: AudioEffect): Pair? { + val range = eq.bandLevelRange + val min = range?.first?.toInt() + val max = range?.last?.toInt() + if (min == null || max == null || min > max) return null + return min to max + } + + private fun unsupportedInfo(): com.facebook.react.bridge.WritableMap { + val info = Arguments.createMap() + info.putBoolean("supported", false) + info.putInt("numberOfBands", 0) + info.putInt("minMillibel", 0) + info.putInt("maxMillibel", 0) + info.putArray("levels", Arguments.createArray()) + return info + } + + /** + * Single call for the whole feature: support flag, band count, millibel + * window and current levels. One bridge call beats three. + */ + @ReactMethod + fun getInfo(promise: Promise) { + val eq = ensureEffect() ?: run { + promise.resolve(unsupportedInfo()) + return + } + val bands = bandCount(eq) + val range = levelRange(eq) + val info = Arguments.createMap() + info.putBoolean("supported", bands > 0 && range != null) + info.putInt("numberOfBands", bands) + info.putInt("minMillibel", range?.first ?: 0) + info.putInt("maxMillibel", range?.second ?: 0) + val levels = Arguments.createArray() + // Center frequencies label the bands in the UI; harmless when unsupported. + val freqs = Arguments.createArray() + for (band in 0 until bands) { + freqs.pushInt(eq.getCenterFreq(band.toShort()) / 1000) + if (range != null) { + val millibel = eq.getBandLevel(band.toShort()).toInt() + levels.pushDouble(millibel.coerceIn(range.first, range.second).toDouble()) + } + } + info.putArray("levels", levels) + info.putArray("centerFreqHz", freqs) + promise.resolve(info) + } + + /** Band index and gain are clamped to the device range, never trusted. */ + @ReactMethod + fun setBandLevel(band: Double, millibel: Double, promise: Promise) { + val eq = ensureEffect() + val range = eq?.let { levelRange(it) } + if (eq == null || range == null || bandCount(eq) == 0) { + promise.reject(ERROR_UNSUPPORTED, "Equalizer is not available on this device") + return + } + val index = band.toInt().coerceIn(0, bandCount(eq) - 1) + val clamped = millibel.toInt().coerceIn(range.first, range.second) + eq.setBandLevel(index.toShort(), clamped.toShort()) + promise.resolve(clamped.toDouble()) + } + + @ReactMethod + fun setEnabled(enabled: Boolean, promise: Promise) { + val eq = ensureEffect() + if (eq == null) { + promise.reject(ERROR_UNSUPPORTED, "Equalizer is not available on this device") + return + } + eq.enabled = enabled + promise.resolve(eq.enabled) + } + + /** Release the audio effect; called when the RN instance goes away. */ + override fun invalidate() { + release() + super.invalidate() + } + + private fun release() { + try { + effect?.release() + } catch (_: Exception) { + // Already torn down by the audio stack. + } + effect = null + } + + private companion object { + const val ERROR_UNSUPPORTED = "EQUALIZER_UNSUPPORTED" + } +} diff --git a/plugins/android/StreamifyEqualizerPackage.kt b/plugins/android/StreamifyEqualizerPackage.kt new file mode 100644 index 0000000..6564809 --- /dev/null +++ b/plugins/android/StreamifyEqualizerPackage.kt @@ -0,0 +1,15 @@ +package com.erfanbagheri.streamifymobile + +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.ViewManager + +/** Manual package: StreamifyEqualizerModule is not autolinked. */ +class StreamifyEqualizerPackage : ReactPackage { + override fun createNativeModules(reactContext: ReactApplicationContext): List = + listOf(StreamifyEqualizerModule(reactContext)) + + override fun createViewManagers(reactContext: ReactApplicationContext): List> = + emptyList() +} diff --git a/plugins/withEqualizer.js b/plugins/withEqualizer.js new file mode 100644 index 0000000..aac0717 --- /dev/null +++ b/plugins/withEqualizer.js @@ -0,0 +1,72 @@ +// Expo config plugin: native Android hardware equalizer (issue #28). +// +// The repo gitignores /android and CI runs `expo prebuild --clean`, so any +// hand-written native file in the android/ tree is wiped before every build. +// A config plugin is the only durable way to ship native Android code here. +// Modelled on plugins/withStreamifyWidget.js (the issue #29 precedent). +// +// Pure stdlib + @expo/config-plugins (already an Expo dependency). No new +// package. +const { withDangerousMod, withMainApplication } = require("@expo/config-plugins"); + +const fs = require("fs"); +const path = require("path"); + +const PACKAGE = "com.erfanbagheri.streamifymobile"; + +/** Source of truth lives in this folder and is copied into the android tree. */ +const NATIVE_DIR = path.join(__dirname, "android"); + +const KOTLIN_FILES = ["StreamifyEqualizerModule.kt", "StreamifyEqualizerPackage.kt"]; + +/** Guard against silently shipping the toggle with no effect behind it. */ +function assertSourcesPresent() { + for (const file of KOTLIN_FILES) { + const full = path.join(NATIVE_DIR, file); + if (!fs.existsSync(full)) { + throw new Error( + `withEqualizer: missing native source ${file}. The equalizer cannot be prebuilt without it.`, + ); + } + } +} + +const withEqualizer = (config) => { + assertSourcesPresent(); + + config = withDangerousMod(config, [ + "android", + (cfg) => { + const androidRoot = cfg.modRequest.platformProjectRoot; + const javaDir = path.join(androidRoot, "app/src/main/java", ...PACKAGE.split(".")); + fs.mkdirSync(javaDir, { recursive: true }); + for (const file of KOTLIN_FILES) { + fs.copyFileSync(path.join(NATIVE_DIR, file), path.join(javaDir, file)); + } + return cfg; + }, + ]); + + // Register the RN package that exposes the equalizer to JS. Anchored on the + // generated template line, not on a locally-added package: CI prebuilds a + // vanilla android/ tree. + config = withMainApplication(config, (cfg) => { + const src = cfg.modResults.contents; + if (src.includes("StreamifyEqualizerPackage()")) return cfg; + const anchor = "PackageList(this).packages.apply {"; + if (!src.includes(anchor)) { + throw new Error( + "withEqualizer: MainApplication template changed; cannot find getPackages anchor.", + ); + } + cfg.modResults.contents = src.replace( + anchor, + `${anchor}\n add(StreamifyEqualizerPackage())`, + ); + return cfg; + }); + + return config; +}; + +module.exports = withEqualizer; From 84275656a9e937fdbd1a7f86eebed18e0c3efb5d Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Sat, 26 Sep 2026 22:34:55 +0330 Subject: [PATCH 2/4] test: add equalizer regression suite and fix band frequency units 19 checks: JS wrapper behaviour under fakes, settings plumbing, and a contract check that runs the config plugin for real (source copy, package registration, idempotence, anchor failure). getCenterFreq is in millihertz; the previous /1000 would have made a 1 kHz band render as 1 Hz. --- components/screens/SettingsScreen.tsx | 29 +- plugins/android/StreamifyEqualizerModule.kt | 5 +- tests/equalizer-regression.cjs | 343 ++++++++++++++++++++ 3 files changed, 363 insertions(+), 14 deletions(-) create mode 100644 tests/equalizer-regression.cjs diff --git a/components/screens/SettingsScreen.tsx b/components/screens/SettingsScreen.tsx index abf8b42..43a69e2 100644 --- a/components/screens/SettingsScreen.tsx +++ b/components/screens/SettingsScreen.tsx @@ -394,19 +394,24 @@ function EqualizerBands({ colors }: { colors: ReturnType["color {hz >= 1000 ? `${hz / 1000}k` : hz} - { - setLevels((prev) => prev.map((v, i) => (i === index ? value : v))); - void setEqualizerBandLevel(index, value); - }} + + > + { + setLevels((prev) => prev.map((v, i) => (i === index ? value : v))); + void setEqualizerBandLevel(index, value); + }} + /> + ))} diff --git a/plugins/android/StreamifyEqualizerModule.kt b/plugins/android/StreamifyEqualizerModule.kt index cf17345..dab18a6 100644 --- a/plugins/android/StreamifyEqualizerModule.kt +++ b/plugins/android/StreamifyEqualizerModule.kt @@ -6,6 +6,7 @@ import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod +import com.facebook.react.bridge.WritableMap /** * Hardware equalizer (issue #28) on [AudioEffect.EFFECT_TYPE_EQUALIZER]. @@ -54,7 +55,7 @@ class StreamifyEqualizerModule(reactContext: ReactApplicationContext) : return min to max } - private fun unsupportedInfo(): com.facebook.react.bridge.WritableMap { + private fun unsupportedInfo(): WritableMap { val info = Arguments.createMap() info.putBoolean("supported", false) info.putInt("numberOfBands", 0) @@ -85,7 +86,7 @@ class StreamifyEqualizerModule(reactContext: ReactApplicationContext) : // Center frequencies label the bands in the UI; harmless when unsupported. val freqs = Arguments.createArray() for (band in 0 until bands) { - freqs.pushInt(eq.getCenterFreq(band.toShort()) / 1000) + freqs.pushInt(eq.getCenterFreq(band.toShort())) if (range != null) { val millibel = eq.getBandLevel(band.toShort()).toInt() levels.pushDouble(millibel.coerceIn(range.first, range.second).toDouble()) diff --git a/tests/equalizer-regression.cjs b/tests/equalizer-regression.cjs new file mode 100644 index 0000000..74f0602 --- /dev/null +++ b/tests/equalizer-regression.cjs @@ -0,0 +1,343 @@ +/* Run: node tests/equalizer-regression.cjs + * One check per #28 requirement. Drive the pure JS with fakes; contract-check + * the native side from file text. Exit code is non-zero on any failure. + */ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const ts = require("typescript"); +const { test } = require("node:test"); + +const root = path.resolve(__dirname, ".."); +const read = (f) => fs.readFileSync(path.join(root, f), "utf8"); + +let failures = 0; +function check(name, fn) { + test(name, async () => { + try { + await fn(); + } catch (e) { + failures++; + throw e; + } + }); +} + +/** Transpile a TS module and evaluate it with injected fakes (known-working pattern). */ +function loadModule(file, fakes) { + const source = read(file); + const { outputText } = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }); + const mod = { exports: {} }; + const fakeRequire = (name) => { + if (fakes[name]) return fakes[name]; + throw new Error(`unexpected require(${name}) in ${file}`); + }; + new Function("require", "module", "exports", outputText)(fakeRequire, mod, mod.exports); + return mod.exports; +} + +/** react-native fake: programmable Platform.OS + NativeModules. */ +function rnFake({ os = "android", modules = {} } = {}) { + const calls = []; + return { + rn: { + Platform: { OS: os }, + NativeModules: modules, + PermissionsAndroid: {}, + }, + calls, + track(name) { + return (...args) => { + calls.push({ name, args }); + return this[name](...args); + }; + }, + }; +} + +const BANDS = { + getInfo: async () => ({ + supported: true, + numberOfBands: 2, + minMillibel: -1500, + maxMillibel: 1500, + levels: [0, 100], + centerFreqHz: [60, 1000], + }), + setBandLevel: async (band, millibel) => millibel, + setEnabled: async (enabled) => enabled, +}; + +// --- JS wrapper: passthrough and gating ---------------------------------- + +check("wrapper calls getInfo and surfaces its payload", async () => { + const { rn } = rnFake({ modules: { StreamifyEqualizerModule: BANDS } }); + const eq = loadModule("modules/audioEqualizer.ts", { "react-native": rn }); + assert.deepEqual(await eq.getEqualizerInfo(), await BANDS.getInfo()); +}); + +check("wrapper setBandLevel passes (band, millibel) through", async () => { + const seen = []; + const { rn } = rnFake({ + modules: { + StreamifyEqualizerModule: { + ...BANDS, + setBandLevel: async (b, m) => { + seen.push([b, m]); + return m; + }, + }, + }, + }); + const eq = loadModule("modules/audioEqualizer.ts", { "react-native": rn }); + assert.equal(await eq.setEqualizerBandLevel(1, -300), -300); + assert.deepEqual(seen, [[1, -300]]); +}); + +check("wrapper setEnabled passes the boolean through", async () => { + const seen = []; + const { rn } = rnFake({ + modules: { + StreamifyEqualizerModule: { + ...BANDS, + setEnabled: async (v) => { + seen.push(v); + return v; + }, + }, + }, + }); + const eq = loadModule("modules/audioEqualizer.ts", { "react-native": rn }); + assert.equal(await eq.setEqualizerEnabled(true), true); + assert.deepEqual(seen, [true]); +}); + +check("wrapper never throws when the module is not linked", async () => { + const { rn } = rnFake({ modules: {} }); + const eq = loadModule("modules/audioEqualizer.ts", { "react-native": rn }); + const warnings = []; + const orig = console.warn; + console.warn = (m) => warnings.push(String(m)); + try { + assert.deepEqual(await eq.getEqualizerInfo(), { + supported: false, + numberOfBands: 0, + minMillibel: 0, + maxMillibel: 0, + levels: [], + centerFreqHz: [], + }); + assert.equal(await eq.setEqualizerBandLevel(0, 0), null); + assert.equal(await eq.setEqualizerEnabled(true), false); + } finally { + console.warn = orig; + } + assert.ok( + warnings.some((w) => w.includes("not linked")), + "first unlinked call warns with link guidance", + ); +}); + +check("wrapper resolves unsupported instead of throwing on native errors", async () => { + const { rn } = rnFake({ + modules: { + StreamifyEqualizerModule: { getInfo: async () => { throw new Error("boom"); } }, + }, + }); + const eq = loadModule("modules/audioEqualizer.ts", { "react-native": rn }); + assert.equal((await eq.getEqualizerInfo()).supported, false); +}); + +check("wrapper no-ops on non-Android platforms", async () => { + const { rn } = rnFake({ os: "ios", modules: { StreamifyEqualizerModule: BANDS } }); + const eq = loadModule("modules/audioEqualizer.ts", { "react-native": rn }); + assert.equal((await eq.getEqualizerInfo()).supported, false); + assert.equal(await eq.setEqualizerBandLevel(0, 100), null); + assert.equal(await eq.setEqualizerEnabled(true), false); +}); + +// --- settings plumbing ---------------------------------------------------- + +check("equalizerEnabled is declared, defaulted false and sanitized", async () => { + const s = loadModule("lib/app-settings.ts", {}); + assert.equal(s.DEFAULT_APP_SETTINGS.equalizerEnabled, false); + assert.equal(s.sanitizeAppSettings({}).equalizerEnabled, false); + assert.equal(s.sanitizeAppSettings({ equalizerEnabled: true }).equalizerEnabled, true); + assert.equal(s.sanitizeAppSettings({ equalizerEnabled: "yes" }).equalizerEnabled, false); +}); + +// --- native contract from file text ---------------------------------------- + +/** Load the config plugin with a recording fake of @expo/config-plugins. */ +function loadPlugin() { + const mods = {}; + const platforms = {}; + const record = (name) => (_config, cb) => { + // withDangerousMod takes [platform, fn]; the others take fn. + if (Array.isArray(cb)) { + platforms[name] = cb[0]; + mods[name] = cb[1]; + } else { + mods[name] = cb; + } + return _config; + }; + const code = read("plugins/withEqualizer.js"); + const mod = { exports: {} }; + new Function("require", "module", "exports", "__dirname", code)( + (n) => { + if (n === "@expo/config-plugins") { + return { + withDangerousMod: record("withDangerousMod"), + withMainApplication: record("withMainApplication"), + }; + } + // Real builtins: the plugin copies files with fs. + return require(n); + }, + mod, + mod.exports, + path.join(root, "plugins"), + ); + const config = mod.exports({ name: "probe" }); + return { config, mods, platforms }; +} + +const kt = read("plugins/android/StreamifyEqualizerModule.kt"); +const pkg = read("plugins/android/StreamifyEqualizerPackage.kt"); +const plugin = read("plugins/withEqualizer.js"); +const screen = read("components/screens/SettingsScreen.tsx"); + +check("plugin copies both Kotlin sources into the generated android tree", async () => { + const os = require("node:os"); + const fakeAndroid = fs.mkdtempSync(path.join(os.tmpdir(), "eq-android-")); + const { mods, platforms } = loadPlugin(); + assert.equal(platforms.withDangerousMod, "android", "mod targets the android platform"); + mods.withDangerousMod({ modRequest: { platformProjectRoot: fakeAndroid } }); + const copied = fs.existsSync( + path.join(fakeAndroid, "app/src/main/java/com/erfanbagheri/streamifymobile"), + ) + ? fs.readdirSync(path.join(fakeAndroid, "app/src/main/java/com/erfanbagheri/streamifymobile")).sort() + : []; + assert.deepEqual(copied, ["StreamifyEqualizerModule.kt", "StreamifyEqualizerPackage.kt"]); + fs.rmSync(fakeAndroid, { recursive: true, force: true }); +}); + +check("plugin registers the package in the withMainApplication output", async () => { + const { mods } = loadPlugin(); + assert.ok(mods.withMainApplication, "plugin mods MainApplication"); + const template = [ + "class MainApplication : Application() {", + " override fun getPackages(): List {", + " return PackageList(this).packages.apply {", + " }", + " }", + "}", + ].join("\n"); + const out = mods.withMainApplication({ modResults: { contents: template } }); + assert.match(out.modResults.contents, /add\(StreamifyEqualizerPackage\(\)\)/); + // Idempotent: a second prebuild pass must not double-register. + const twice = mods.withMainApplication({ modResults: { contents: out.modResults.contents } }); + assert.equal( + twice.modResults.contents.match(/add\(StreamifyEqualizerPackage\(\)\)/g).length, + 1, + ); +}); + +check("plugin throws on a MainApplication template it cannot anchor to", async () => { + const { mods } = loadPlugin(); + assert.throws( + () => mods.withMainApplication({ modResults: { contents: "class MainApplication" } }), + /MainApplication template changed/, + ); +}); + +check("native exposes exactly the methods the wrapper calls", async () => { + const methods = [...kt.matchAll(/@ReactMethod\s*\n\s*fun\s+(\w+)/g)].map((m) => m[1]); + for (const m of ["getInfo", "setBandLevel", "setEnabled"]) { + assert.ok(methods.includes(m), `module must expose ${m}`); + } + assert.ok(!methods.includes("getBands"), "no dead method surface beyond the contract"); +}); + +check("native attaches to the global session (no sessionId handoff)", async () => { + assert.ok( + /AudioEffect\s*\(\s*0\s*,\s*AudioEffect\.EFFECT_TYPE_EQUALIZER/.test(kt), + "constructed with AudioEffect(0, EFFECT_TYPE_EQUALIZER, …)", + ); +}); + +check("native clamps band index and gain, reports init failure cleanly", async () => { + // Exact statement forms: a bare `millibel.toInt()` or a release that does not + // call through must not satisfy these. + assert.ok( + /val clamped = millibel\.toInt\(\)\.coerceIn\(range\.first, range\.second\)/.test(kt), + "millibel clamped to the device range", + ); + assert.ok( + /val index = band\.toInt\(\)\.coerceIn\(0, bandCount\(eq\) - 1\)/.test(kt), + "band index clamped to the device band count", + ); + assert.ok(/STATE_INITIALIZED/.test(kt), "AudioEffect init state checked"); + assert.ok(/supported.*false/.test(kt), "unsupported state returned, not thrown"); +}); + +check("native releases the effect on teardown", async () => { + assert.ok(/override fun invalidate\(\)/.test(kt), "invalidate() override present"); + // The release must actually happen in the teardown path, not in a comment. + assert.match( + kt, + /private fun release\(\) \{\s*try \{\s*effect\?\.release\(\)/, + "release() calls AudioEffect.release on the held effect", + ); +}); + +check("package returns the module and plugin registers it via withMainApplication", async () => { + assert.ok(pkg.includes("StreamifyEqualizerModule(reactContext)"), "package creates module"); + assert.ok(plugin.includes("withMainApplication"), "plugin touches MainApplication"); + assert.ok( + plugin.includes("StreamifyEqualizerPackage()"), + "plugin registers the package", + ); + assert.ok(plugin.includes("withDangerousMod"), "plugin copies sources on prebuild"); + for (const f of ["StreamifyEqualizerModule.kt", "StreamifyEqualizerPackage.kt"]) { + assert.ok(plugin.includes(f), `plugin copies ${f}`); + assert.ok(fs.existsSync(path.join(root, "plugins/android", f)), `${f} present`); + } +}); + +check("plugin has the missing-source guard", async () => { + assert.match(plugin, /function assertSourcesPresent\(\)/, "guard is a named function"); + assert.ok( + plugin.includes("cannot be prebuilt without it"), + "guard fails loudly with an actionable message", + ); +}); + +check("app.json wires the plugin", async () => { + const app = JSON.parse(read("app.json")); + assert.ok(app.expo.plugins.includes("./plugins/withEqualizer"), "plugin listed"); +}); + +check("settings toggle gates the native enable call", async () => { + assert.ok(screen.includes("settings.equalizerEnabled"), "toggle bound to setting"); + assert.ok(screen.includes("setEqualizerEnabled(value)"), "toggle calls native"); + assert.ok(screen.includes("setEqualizerBandLevel(index, value)"), "sliders call native"); +}); + +check("locale keys exist in en and fa (fa is real Persian)", async () => { + const en = JSON.parse(read("locales/en.json")).settings; + const fa = JSON.parse(read("locales/fa.json")).settings; + for (const k of ["equalizer", "equalizerDescription", "equalizerUnsupported"]) { + assert.ok(en[k], `en ${k}`); + assert.ok(fa[k], `fa ${k}`); + } + assert.ok(/[؀-ۿ]/.test(fa.equalizer), "fa copy is Persian script"); +}); + +// node:test exits non-zero when any check fails. +process.on("exit", (code) => { + if (failures > 0 && code === 0) process.exitCode = 1; +}); From 79e87beea2c1c4d6e5053acab16e359d9ea5f3a5 Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Mon, 28 Sep 2026 10:21:44 +0330 Subject: [PATCH 3/4] fix(equalizer): add the missing import and permission, fix the Hz contract Four defects from review of #28, the first of them build-breaking. withMainApplication inserted add(StreamifyEqualizerPackage()) with no import, so MainApplication.kt did not compile. The plugin now injects the import alongside the registration, both idempotently. The old test only asserted the add() and would have shipped the broken build. No MODIFY_AUDIO_SETTINGS permission, so AudioEffect init failed on device. Added via withAndroidManifest. getCenterFreq returns milliHz but the JS contract is plain Hz, so band labels read 1000x high. Divided by 1000. unsupportedInfo omitted centerFreqHz, which SettingsScreen reads unconditionally. The key is now always present. 22/22, sabotage-verified. --- plugins/android/StreamifyEqualizerModule.kt | 7 ++- plugins/withEqualizer.js | 39 +++++++++++++-- tests/equalizer-regression.cjs | 54 ++++++++++++++++++++- 3 files changed, 93 insertions(+), 7 deletions(-) diff --git a/plugins/android/StreamifyEqualizerModule.kt b/plugins/android/StreamifyEqualizerModule.kt index dab18a6..d2c3f6e 100644 --- a/plugins/android/StreamifyEqualizerModule.kt +++ b/plugins/android/StreamifyEqualizerModule.kt @@ -62,6 +62,9 @@ class StreamifyEqualizerModule(reactContext: ReactApplicationContext) : info.putInt("minMillibel", 0) info.putInt("maxMillibel", 0) info.putArray("levels", Arguments.createArray()) + // The JS contract always reads centerFreqHz: keep the key present even + // when there are no bands to report. + info.putArray("centerFreqHz", Arguments.createArray()) return info } @@ -86,7 +89,9 @@ class StreamifyEqualizerModule(reactContext: ReactApplicationContext) : // Center frequencies label the bands in the UI; harmless when unsupported. val freqs = Arguments.createArray() for (band in 0 until bands) { - freqs.pushInt(eq.getCenterFreq(band.toShort())) + // getCenterFreq returns milliHz; the JS contract is plain Hz, so the + // labels would otherwise read 1000x high (60000 instead of 60). + freqs.pushInt((eq.getCenterFreq(band.toShort()) / 1000).coerceAtLeast(0)) if (range != null) { val millibel = eq.getBandLevel(band.toShort()).toInt() levels.pushDouble(millibel.coerceIn(range.first, range.second).toDouble()) diff --git a/plugins/withEqualizer.js b/plugins/withEqualizer.js index aac0717..92f1735 100644 --- a/plugins/withEqualizer.js +++ b/plugins/withEqualizer.js @@ -7,7 +7,7 @@ // // Pure stdlib + @expo/config-plugins (already an Expo dependency). No new // package. -const { withDangerousMod, withMainApplication } = require("@expo/config-plugins"); +const { withDangerousMod, withMainApplication, withAndroidManifest } = require("@expo/config-plugins"); const fs = require("fs"); const path = require("path"); @@ -34,6 +34,23 @@ function assertSourcesPresent() { const withEqualizer = (config) => { assertSourcesPresent(); + // MODIFY_AUDIO_SETTINGS is needed to attach the effect to the output mix; + // without it AudioEffect init fails on device. + config = withAndroidManifest(config, (cfg) => { + const manifest = cfg.modResults.manifest; + manifest["uses-permission"] = manifest["uses-permission"] || []; + const has = manifest["uses-permission"].some( + (entry) => + entry.$?.["android:name"] === "android.permission.MODIFY_AUDIO_SETTINGS", + ); + if (!has) { + manifest["uses-permission"].push({ + $: { "android:name": "android.permission.MODIFY_AUDIO_SETTINGS" }, + }); + } + return cfg; + }); + config = withDangerousMod(config, [ "android", (cfg) => { @@ -52,14 +69,28 @@ const withEqualizer = (config) => { // vanilla android/ tree. config = withMainApplication(config, (cfg) => { const src = cfg.modResults.contents; - if (src.includes("StreamifyEqualizerPackage()")) return cfg; + const importLine = `import ${PACKAGE}.StreamifyEqualizerPackage`; + if (!src.includes(importLine)) { + const packageAnchor = `package ${PACKAGE}`; + if (!src.includes(packageAnchor)) { + throw new Error( + "withEqualizer: MainApplication template changed; cannot find package anchor.", + ); + } + cfg.modResults.contents = cfg.modResults.contents.replace( + packageAnchor, + `${packageAnchor}\n${importLine}`, + ); + } + const updated = cfg.modResults.contents; + if (updated.includes("StreamifyEqualizerPackage()")) return cfg; const anchor = "PackageList(this).packages.apply {"; - if (!src.includes(anchor)) { + if (!updated.includes(anchor)) { throw new Error( "withEqualizer: MainApplication template changed; cannot find getPackages anchor.", ); } - cfg.modResults.contents = src.replace( + cfg.modResults.contents = updated.replace( anchor, `${anchor}\n add(StreamifyEqualizerPackage())`, ); diff --git a/tests/equalizer-regression.cjs b/tests/equalizer-regression.cjs index 74f0602..71671cf 100644 --- a/tests/equalizer-regression.cjs +++ b/tests/equalizer-regression.cjs @@ -192,6 +192,7 @@ function loadPlugin() { return { withDangerousMod: record("withDangerousMod"), withMainApplication: record("withMainApplication"), + withAndroidManifest: record("withAndroidManifest"), }; } // Real builtins: the plugin copies files with fs. @@ -225,10 +226,10 @@ check("plugin copies both Kotlin sources into the generated android tree", async fs.rmSync(fakeAndroid, { recursive: true, force: true }); }); -check("plugin registers the package in the withMainApplication output", async () => { +check("plugin registers the package with its import (no unresolved add())", async () => { const { mods } = loadPlugin(); - assert.ok(mods.withMainApplication, "plugin mods MainApplication"); const template = [ + "package com.erfanbagheri.streamifymobile", "class MainApplication : Application() {", " override fun getPackages(): List {", " return PackageList(this).packages.apply {", @@ -238,12 +239,61 @@ check("plugin registers the package in the withMainApplication output", async () ].join("\n"); const out = mods.withMainApplication({ modResults: { contents: template } }); assert.match(out.modResults.contents, /add\(StreamifyEqualizerPackage\(\)\)/); + assert.ok( + out.modResults.contents.includes( + "import com.erfanbagheri.streamifymobile.StreamifyEqualizerPackage", + ), + "an add() with no import does not compile — stale test needs updating", + ); // Idempotent: a second prebuild pass must not double-register. const twice = mods.withMainApplication({ modResults: { contents: out.modResults.contents } }); assert.equal( twice.modResults.contents.match(/add\(StreamifyEqualizerPackage\(\)\)/g).length, 1, ); + assert.equal( + twice.modResults.contents.match( + /import com\.erfanbagheri\.streamifymobile\.StreamifyEqualizerPackage/g, + ).length, + 1, + ); +}); + +check("plugin requests MODIFY_AUDIO_SETTINGS (AudioEffect init fails without it)", async () => { + const { mods } = loadPlugin(); + assert.ok(mods.withAndroidManifest, "plugin must touch the manifest"); + const cfg = mods.withAndroidManifest({ modResults: { manifest: {} } }); + const names = (cfg.modResults.manifest["uses-permission"] || []).map( + (entry) => entry.$?.["android:name"], + ); + assert.ok( + names.includes("android.permission.MODIFY_AUDIO_SETTINGS"), + "AudioEffect init fails on device without this permission", + ); +}); + +check("native reports center frequencies in Hz, not milliHz", async () => { + assert.ok( + kt.includes("getCenterFreq(band.toShort()) / 1000"), + "getCenterFreq returns milliHz; the UI would label bands 1000x high", + ); +}); + +check("unsupportedInfo honors the full EqualizerInfo contract", async () => { + const body = kt.slice(kt.indexOf("private fun unsupportedInfo()")); + const fn = body.slice(0, body.indexOf(" }")); + assert.ok( + fn.includes('putArray("centerFreqHz"'), + "JS reads centerFreqHz unconditionally — the key must exist", + ); + const { rn } = rnFake({ modules: {} }); + const onAndroid = { "react-native": { ...rn, Platform: { OS: "android" } } }; + const eq = loadModule("modules/audioEqualizer.ts", onAndroid); + const info = await eq.getEqualizerInfo(); + assert.ok( + Array.isArray(info.centerFreqHz), + "the unsupported surface must carry centerFreqHz", + ); }); check("plugin throws on a MainApplication template it cannot anchor to", async () => { From d37636b957d6b9506cfaea88dcbd40e6eba30f1e Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Fri, 6 Nov 2026 00:26:48 +0330 Subject: [PATCH 4/4] test(equalizer): load cacheBudget for app-settings after main merge --- tests/equalizer-regression.cjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/equalizer-regression.cjs b/tests/equalizer-regression.cjs index 71671cf..c8e6953 100644 --- a/tests/equalizer-regression.cjs +++ b/tests/equalizer-regression.cjs @@ -161,7 +161,8 @@ check("wrapper no-ops on non-Android platforms", async () => { // --- settings plumbing ---------------------------------------------------- check("equalizerEnabled is declared, defaulted false and sanitized", async () => { - const s = loadModule("lib/app-settings.ts", {}); + const cacheBudget = loadModule("modules/cacheBudget.ts", {}); + const s = loadModule("lib/app-settings.ts", { "../modules/cacheBudget": cacheBudget }); assert.equal(s.DEFAULT_APP_SETTINGS.equalizerEnabled, false); assert.equal(s.sanitizeAppSettings({}).equalizerEnabled, false); assert.equal(s.sanitizeAppSettings({ equalizerEnabled: true }).equalizerEnabled, true);