Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Audio effects has presets and AutoEq headphone corrections
My-Name-Is-Jefff1cc608346f1
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex b409f21a..68706cab 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -102,7 +102,12 @@ Shared:one hook for every feature that wants it (PlayerState.x), the lock screen widget's flags, and in themore button's menu Speed and pitch: both done to Spotify's audio by Apple's time and pitch unit, putbetween its mixer and its RemoteIO unit by taking over the connection Spotify makes between them- (SpeedPitchMenu.x, SpeedPitch.x, SGTimePitch.m). The block goes into Spotify's own context menu sheet+ (SpeedPitchMenu.x, SpeedPitch.x, SGTimePitch.m). Pitch follows speed (on until switched off,+ spotifyglass.speed.pitchFollows) plays the speed through Apple's Varispeed instead, faster and higher+ together like a record; Varispeed also carries 1x while it is on, so a return to normal speed changes+ nothing, and the stretch is left for pitch alone at 1x, the two swapped only through a reset. Under the+ sliders a Reverb slider sets the audio effects' reverb amount (spotifyglass.dsp.reverb.amount), turning+ the effects and the reverb on with it. The block goes into Spotify's own context menu sheetand is drawn from its own measures, not the Kit's, so it sits there under either look. Tested on theMac against harness/pitch/ and in the simulator against harness/speed/ and harness/menu/AudioEffects/ the audio effects on Spotify's sound (AudioEffects.h has the keys and the page's calls): Spotify's@@ -112,8 +117,14 @@ Shared:hardware's, not the client format Spotify sets. The effects are the SGDSP*.m files, on Accelerate,Apple's Reverb2 unit, libbs2b and EEL2 (vendor/audio). Settings apply as they change, on a queue ofits own; the file effects read their files from Documents/Vitrine/Audio effects- (AudioEffectsFiles.m). Tested on the Mac against harness/audio-effects/, the hook in the simulator- against its sim/+ (AudioEffectsFiles.m). Presets and Headphones (AudioEffectsPresets.h lists their files): seven+ built-in presets over a reset that keep the Graphic EQ, the user's own as a copy of every dsp key, the+ settings from before the page's first pick saved as one of them, Before presets, and AutoEq's+ corrections, its INDEX.md fetched from GitHub and cached a month in Caches/Vitrine/AutoEq, a+ headphone's GraphicEQ file put into the Graphic EQ (AutoEq.m), None taking it off; a pick turns the+ master switch on.+ Tested on the Mac against harness/audio-effects/ and harness/autoeq/, the hook in the simulator+ against its sim/, the page against harness/audio-effects-page/Haptics/ Vibrations (Haptics.h lists its files): a tap of UIKit's feedback generators for the player's and the nowplaying bar's controls, the scrubber's tenths and ends, cover swipes, gestures and the lyrics page's tap toseek, at the strength set for them (ControlHaptics.x, SGFeedback.m); and Music Haptics, Core Haptics@@ -142,7 +153,8 @@ Native:Navbar/ Spotify's tab bar composed (Navbar.x, NavbarLayout.m, hooked from TabBarHooks.x), the Navbar and Add a tab pagesNowPlayingBar/ the device button hidden, the bar's flagsPlayer/ the full screen player (Player.x), its cards and buttons hidden (PlayerDeclutter.x), the glass lyrics card- (LyricsCard.x), the gestures' hookup, the Queue & devices flags+ (LyricsCard.x), the gestures' hookup and the hold on either side of the cover that plays at 2x until+ the finger lifts (PlayerGestures.x), the Queue & devices flagsLyrics/ the full screen lyrics page on glass (LyricsPage.x)Home/ the Home gradient, Home's sections and pills hidden (HomeDeclutter.x), the Home & Library pagePlaylist/ the playlist header and pills, hidden one switch each@@ -160,7 +172,9 @@ Redesigned:NowPlayingBar/ the glass now playing bar (NowPlayingBar.x), with Spotify's device button on it hidden on request(BarConnect.x, its own key and its own Now playing page, apart from the native look's)Player/ the redesigned full screen player (Player.h lists its files); its more button is handed to- Shared/Player's Speed and pitch, which draws in the menu it opens+ Shared/Player's Speed and pitch, which draws in the menu it opens, and a hold on either side of the+ cover plays at 2x until the finger lifts (PlayerArtwork.x), an octave higher while Pitch follows+ speed is onLyrics/ the full screen lyrics page on glass with Apple Music style lyrics over it, always on (SGRKaraokeView,which the player shows in itself too, Player/PlayerLyrics.x): lines sung over each other lit together,the stack moving on once the first is sung out; an instrumental break of 7 s or more held by three dots@@ -262,9 +276,11 @@ snare and a rumble under the bass), Beat (the taps without the rumble) or Bass (rumble), all applying straight away. Live Activity, on iOS 17 and up under either look: its switch and which view itshows, Lyrics, Queue or Control menu, bothapplying straight away, the row reading out the view or Off. Audio effects, in either look (Shared/AudioEffects/AudioEffectsPage.m):-the effects' switch with what the engine is doing under it, then a card per effect, each opening out into its-sliders, choices, curve or file library while its switch is on, everything applying as it changes; the row reads-out Off, On or how many effects are on. Home & Library, in the native look only:+the effects' switch with what the engine is doing under it, Presets (built-in ones and your own, saved, loaded+and deleted there) and Headphones (AutoEq's corrections, searched and applied to the Graphic EQ), either of which+turns the effects on, then a card per effect, each opening out into its sliders, choices, curve or file library+while its switch is on (Reverb has its Room and its Amount, the amount the player's ⋯ menu also sets), everything+applying as it changes; the row reads out Off, On or how many effects are on. Home & Library, in the native look only:the Gradient page (the wash behind the top of Home in one of eight colours, at three strengths andfour heights) and the Home flags, the parts of Home to hide including the DJ button and badge, theplaylist header, buttons and pills to hide, and the Library flags. Then Privacy & clutterdiff --git a/harness/audio-effects-page/README.md b/harness/audio-effects-page/README.mdindex 1bdb1b21..8c55c3b5 100644--- a/harness/audio-effects-page/README.md+++ b/harness/audio-effects-page/README.md@@ -25,6 +25,12 @@ equalizer's curve the cascade's own response through its handles, the width showthe stored 60), long choice names moving under the title at 375pt, an error row in the engine's wording, thecredits under the reset; the values stored under the right keys, snapped to their steps.+`save=<name>` stores a preset of the user's behind the page's back and `rows` logs each visible row with its tick+and VoiceOver value. 2026-10-05, iPhone 17 Pro on iOS 27.0: the Presets page's first pick saves Before presets at+the top of Yours and a tap on it puts the settings back; a swipe delete above the ticked preset keeps the tick on+it, and the last one leaves the placeholder. Headphones' None turns the Graphic EQ off and clears the headphone,+and a headphone being applied reads "Applying" to VoiceOver.+What it does not cover: a real finger. The drag is played through the curve's own methods, so whether itspan wins over the table's scroll when a finger starts on a handle (and loses anywhere else) is untestedhere; `hit` logs which band a finger going down at and around each handle would take. Nor the documentdiff --git a/harness/audio-effects-page/build.sh b/harness/audio-effects-page/build.shindex 040f0a14..d91f0920 100755--- a/harness/audio-effects-page/build.sh+++ b/harness/audio-effects-page/build.sh@@ -13,6 +13,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar-I"$SRC" -I"$FX" -isysroot "$SDK" -Wall -Wno-deprecated-declarations \"$(dirname "$0")/main.m" "$(dirname "$0")/../scene.m" "$(dirname "$0")/stubs.m" \"$FX"/AudioEffectsSettings.m "$FX"/AudioEffectsPage.m "$FX"/SGDSPCurveView.m "$FX"/AudioEffectsLibraryPage.m "$FX"/SGDSPFilters.m \+ "$FX"/AudioEffectsPresets.m "$FX"/AudioEffectsPresetsPage.m "$FX"/AutoEq.m \"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \-framework UIKit -framework QuartzCore -framework CoreGraphics -framework UniformTypeIdentifiers -framework Accelerate -framework Foundation \diff --git a/harness/audio-effects-page/main.m b/harness/audio-effects-page/main.mindex 58ceb579..9415dbd6 100644--- a/harness/audio-effects-page/main.m+++ b/harness/audio-effects-page/main.m@@ -16,11 +16,15 @@// there), swipe=<section>.<row>:<n> and band=<band>:<n> (VoiceOver's swipe on a slider or an equalizer band,// n times), string=<key after spotifyglass.dsp.>:<text> (stored behind the page's back, as the engine's// errors turn up), pop, delete=<row> (the library's swipe to delete on that file), hit (which band a finger-// takes around each handle, to the log), confirm (the alert's destructive button), dump (the stored dsp keys and the first sections' frames to the log).+// takes around each handle, to the log), confirm (the alert's destructive button), dump (the stored dsp keys and the first sections' frames to the log),+// save=<name> (the settings saved as a preset of the user's, behind the page's back), rows (each visible row's+// title, whether it is ticked and what VoiceOver reads as its value, to the log).+// Without keep, the user's presets are cleared too.#import <UIKit/UIKit.h>#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>#import "Shared/AudioEffects/AudioEffects.h"#import "Shared/AudioEffects/AudioEffectsPage.h"+#import "Shared/AudioEffects/AudioEffectsPresets.h"#import "Shared/AudioEffects/SGDSPCurveView.h"#import "Settings/SGModPage.h"@@ -61,6 +65,7 @@ static void findViews(UIView *root, Class kind, NSMutableArray *found) {for (NSString *key in store.dictionaryRepresentation.allKeys) {if ([key hasPrefix:@"spotifyglass.dsp"]) [store removeObjectForKey:key];}+ [store removeObjectForKey:SGKeyDSPUserPresets];}if ([args containsObject:@"master"]) SGDSPSetSwitch(SGKeyDSP, YES);if ([args containsObject:@"allon"]) for (NSString *key in effectKeys()) SGDSPSetSwitch(key, YES);@@ -224,11 +229,23 @@ static void findViews(UIView *root, Class kind, NSMutableArray *found) {(long)band, (long)[curve bandAt:CGPointMake(x, y)], (long)[curve bandAt:CGPointMake(x, y - 20)],(long)[curve bandAt:CGPointMake(x, y - 40)], (long)[curve bandAt:CGPointMake(x + 9, y)]);}+ } else if ([verb isEqualToString:@"save"]) {+ SGDSPSaveUserPreset(value);+ } else if ([verb isEqualToString:@"rows"]) {+ for (NSIndexPath *path in table.indexPathsForVisibleRows) {+ UITableViewCell *cell = [table cellForRowAtIndexPath:path];+ id content = cell.contentConfiguration;+ NSString *text = [content isKindOfClass:UIListContentConfiguration.class] ? [content text] : cell.textLabel.text;+ NSLog(@"[harness] row %ld.%ld %@%@%@", (long)path.section, (long)path.row, text,+ cell.accessibilityTraits & UIAccessibilityTraitSelected ? @" (ticked)" : @"",+ cell.accessibilityValue ? [@" value " stringByAppendingString:cell.accessibilityValue] : @"");+ }} else if ([verb isEqualToString:@"dump"]) {NSDictionary *all = NSUserDefaults.standardUserDefaults.dictionaryRepresentation;for (NSString *key in [all.allKeys sortedArrayUsingSelector:@selector(compare:)]) {if ([key hasPrefix:@"spotifyglass.dsp"]) NSLog(@"[harness] %@ = %@", key, all[key]);}+ NSLog(@"[harness] user presets: %@", [SGDSPUserPresetNames() componentsJoinedByString:@", "]);NSLog(@"[harness] summary: %@; on top %@ with %ld sections", SGDSPSummary(), self.nav.topViewController.class,(long)table.numberOfSections);for (NSInteger section = 0; section < MIN(3, table.numberOfSections); section++) {diff --git a/harness/autoeq/README.md b/harness/autoeq/README.mdnew file mode 100644index 00000000..3271120a--- /dev/null+++ b/harness/autoeq/README.md@@ -0,0 +1,22 @@+# Presets and AutoEq check++Audio effects > Presets and Headphones (`tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.h`) on the Mac,+with no UI: `AudioEffectsPresets.m`, `AutoEq.m`, `AudioEffectsSettings.m` and `Core/SGPrefs.m` as the tweak+compiles them, `shim/Core/SGCore.h` keeping SGCore.h's UIKit half out, and `SGDSPApply` counted rather than+run.++ ./build.sh && build/autoeq-check # offline+ build/autoeq-check online # also AutoEq's real index and files++Offline: INDEX.md lines with parentheses in folders, brackets in names, `&` and `$`, and broken lines; the raw+GraphicEQ addresses made from them; search; a GraphicEQ file applied (switch, nodes, headphone, the master+switch on with it); each built-in preset over the others, keeping the headphone's correction and turning the+master switch on; a saved preset reset and loaded back, Graphic EQ included, the master switch left out of it+and turned on by loading it.++Online: `results/INDEX.md` fetched from raw.githubusercontent.com (8850 headphones in October 2026), cached+and read back, Sennheiser HD 600 by oratory1990 found and its GraphicEQ applied, and a dozen headphones spread+across the index checked to have their GraphicEQ file where the address says. The cached copy is removed after.++The settings live in the check's own defaults domain and are cleared before and after. What it does not cover:+the two pages themselves, which the audio-effects-page harness shows.diff --git a/harness/autoeq/build.sh b/harness/autoeq/build.shnew file mode 100755index 00000000..ff6daa56--- /dev/null+++ b/harness/autoeq/build.sh@@ -0,0 +1,12 @@+#!/bin/sh+# Builds the presets and AutoEq check for the Mac: AudioEffectsPresets.m, AutoEq.m, AudioEffectsSettings.m and+# Core/SGPrefs.m as the tweak compiles them, shim/ standing in for SGCore.h's UIKit half.+set -e+cd "$(dirname "$0")"+SRC=../../tweak/Sources+FX=$SRC/Shared/AudioEffects+mkdir -p build+xcrun clang -fobjc-arc -O0 -g -Wall -Werror -target arm64-apple-macos13.0 -I shim -I "$SRC" -I "$FX" \+ check.m "$FX"/AudioEffectsPresets.m "$FX"/AutoEq.m "$FX"/AudioEffectsSettings.m "$SRC"/Core/SGPrefs.m \+ -framework Foundation -o build/autoeq-check+echo "built build/autoeq-check"diff --git a/harness/autoeq/check.m b/harness/autoeq/check.mnew file mode 100644index 00000000..7ee7b7f4--- /dev/null+++ b/harness/autoeq/check.m@@ -0,0 +1,193 @@+// Checks Presets and Headphones (Shared/AudioEffects/AudioEffectsPresets.h) on the Mac: INDEX.md's parsing on+// lines written to be awkward, the raw addresses made from them, search, the built-in and saved presets+// through the real settings, and, with `online`, AutoEq's real index fetched, cached and one headphone applied.+//+// ./build.sh && build/autoeq-check [online]+//+// Every line prints ok or FAIL; the exit status is the number of failures. The settings live in the check's+// own defaults domain, cleared before and after.+#import <Foundation/Foundation.h>+#import "AudioEffects.h"+#import "AudioEffectsApply.h"+#import "AudioEffectsPresets.h"++static int failures;++static void check(BOOL ok, NSString *what) {+ printf("%s %s\n", ok ? "ok " : "FAIL", what.UTF8String);+ failures += !ok;+}++// The engine is not here: what it was handed is counted instead.+static NSCountedSet<NSString *> *applied;+void SGDSPApply(NSString *effect) {+ [applied addObject:effect];+}++static void clearDefaults(void) {+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;+ for (NSString *key in store.dictionaryRepresentation) {+ if ([key hasPrefix:@"spotifyglass."]) [store removeObjectForKey:key];+ }+}++// Runs the main queue until `done` says so, the way the app's run loop would.+static void waitFor(BOOL (^done)(void)) {+ NSDate *limit = [NSDate dateWithTimeIntervalSinceNow:60];+ while (!done() && limit.timeIntervalSinceNow > 0) [NSRunLoop.mainRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];+}++static void checkParsing(void) {+ NSString *index =+ @"# Index\n"+ @"This is a list of all equalization profiles. Target is in parentheses if there are results with multiple targets\n"+ @"from the same source.\n\n"+ @"- [1Custom SA02](./crinacle/711%20in-ear/1Custom%20SA02) by crinacle on 711\n"+ @"- [1MORE Aero (ANC Off)](./HypetheSonics/GRAS%20RA0045%20in-ear/1MORE%20Aero%20(ANC%20Off)) by HypetheSonics on GRAS RA0045\n"+ @"- [Sennheiser HD 600](./oratory1990/over-ear/Sennheiser%20HD%20600) by oratory1990\n"+ @"- [AKG K371 [Harman] (Bass)](./Rtings/over-ear/AKG%20K371%20(Bass)) by Rtings\n"+ @"- [Sennheiser HD 600](./crinacle/GRAS%2043AG-7%20over-ear/Sennheiser%20HD%20600) by crinacle on GRAS 43AG-7\n"+ @"- [Sony WH-1000XM4 & $50 tips](./Super%20Review/over-ear/Sony%20WH-1000XM4%20&%20$50%20tips) by Super Review\n"+ @"- not a link\n"+ @"- [Broken](./no/closing by nobody\n";+ NSArray<SGAutoEqHeadphone *> *all = SGAutoEqParseIndex(index);+ check(all.count == 6, [NSString stringWithFormat:@"6 headphones parsed, the heading and the broken lines skipped (%lu)", (unsigned long)all.count]);+ if (all.count < 6) return;+ check([all[1].name isEqualToString:@"1MORE Aero (ANC Off)"] && [all[1].path isEqualToString:@"HypetheSonics/GRAS%20RA0045%20in-ear/1MORE%20Aero%20(ANC%20Off)"]+ && [all[1].source isEqualToString:@"HypetheSonics on GRAS RA0045"], @"parentheses in the name and the folder");+ check([all[3].name isEqualToString:@"AKG K371 [Harman] (Bass)"] && [all[3].path isEqualToString:@"Rtings/over-ear/AKG%20K371%20(Bass)"],+ @"brackets in the name");+ check([SGAutoEqGraphicEqURL(all[2].path).absoluteString isEqualToString:+ @"https://raw.githubusercontent.com/jaakkopasanen/AutoEq/master/results/oratory1990/over-ear/Sennheiser%20HD%20600/Sennheiser%20HD%20600%20GraphicEQ.txt"],+ @"the raw address of a GraphicEQ file");+ NSString *aero = SGAutoEqGraphicEqURL(all[1].path).absoluteString;+ check([aero hasSuffix:@"/1MORE%20Aero%20(ANC%20Off)/1MORE%20Aero%20(ANC%20Off)%20GraphicEQ.txt"], aero);+ NSString *sony = SGAutoEqGraphicEqURL(all[5].path).absoluteString;+ check([sony hasSuffix:@"/Sony%20WH-1000XM4%20&%20$50%20tips%20GraphicEQ.txt"] && [NSURL URLWithString:sony], sony);+ check([SGAutoEqNameOf(all[2].path) isEqualToString:@"Sennheiser HD 600"], @"a folder's name for the page's row");++ check(SGAutoEqSearch(all, @"hd 600").count == 2, @"search: two HD 600s");+ check(SGAutoEqSearch(all, @" HD600 ").count == 0, @"search: words, not a squashed name");+ check(SGAutoEqSearch(all, @"600 ORATORY").count == 1, @"search: any order, any case, the source too");+ check(SGAutoEqSearch(all, @"").count == 6, @"search: empty shows all");+}++static void checkPresets(void) {+ clearDefaults();+ NSString *line = SGDSPGraphicEqLine(@" GraphicEQ: 20 -1.2;\n 21 -1.1;\n\n");+ check([line isEqualToString:@"GraphicEQ: 20 -1.2; 21 -1.1;"], @"a GraphicEQ file's text onto one line");+ check(SGDSPGraphicEqLine(@"Preamp: -6 dB") == nil, @"other text is not a GraphicEQ line");++ // A headphone's correction in place, and other effects on.+ check(SGAutoEqApplyText(@"oratory1990/over-ear/Sennheiser%20HD%20600", @"GraphicEQ: 20 -1.2; 21 -1.1;\n"), @"a GraphicEQ file applied");+ check(SGDSPSwitch(SGKeyDSPGraphicEq) && [SGDSPString(SGKeyDSPGraphicEqNodes) isEqualToString:@"GraphicEQ: 20 -1.2; 21 -1.1;"]+ && [SGDSPString(SGKeyDSPGraphicEqHeadphone) isEqualToString:@"oratory1990/over-ear/Sennheiser%20HD%20600"],+ @"the Graphic EQ on, with the nodes and the headphone");+ check([applied countForObject:SGKeyDSPGraphicEq] > 0, @"the Graphic EQ handed to the engine");+ check(SGDSPSwitch(SGKeyDSP) && [applied countForObject:SGKeyDSP] > 0, @"the effects' master switch on with the headphone");+ check(!SGAutoEqApplyText(@"a/b", @"<html>404</html>"), @"a page that is not GraphicEQ is refused");+ SGDSPSetSwitch(SGKeyDSPTube, YES);+ SGDSPSetSwitch(SGKeyDSP, NO);++ NSArray<NSString *> *names = SGDSPBuiltInPresetNames();+ check(names.count >= 4 && [names containsObject:@"Concert hall"] && [names containsObject:@"Late night"], @"built-in presets");+ for (NSUInteger i = 0; i < names.count; i++) check(SGDSPBuiltInPresetDetail((NSInteger)i).length > 0, [@"a detail for " stringByAppendingString:names[i]]);++ SGDSPLoadBuiltInPreset((NSInteger)[names indexOfObject:@"Bass boost"]);+ check(SGDSPSwitch(SGKeyDSPBass) && SGDSPNumber(SGKeyDSPBassGain) == 8, @"Bass boost: bass on at 8 dB");+ check(!SGDSPSwitch(SGKeyDSPTube), @"Bass boost: the tube, on before, off");+ check(SGDSPSwitch(SGKeyDSPGraphicEq) && [SGDSPString(SGKeyDSPGraphicEqNodes) hasPrefix:@"GraphicEQ: 20 -1.2"]+ && SGDSPString(SGKeyDSPGraphicEqHeadphone).length, @"Bass boost: the headphone's correction kept");+ check(SGDSPSwitch(SGKeyDSP), @"Bass boost: the master switch on with it");++ SGDSPLoadBuiltInPreset((NSInteger)[names indexOfObject:@"Vocal clarity"]);+ check(SGDSPSwitch(SGKeyDSPEqualizer) && [SGDSPGains(SGKeyDSPEqualizerGains) isEqualToArray:SGDSPEqualizerPreset(4)]+ && !SGDSPSwitch(SGKeyDSPBass), @"Vocal clarity: the equalizer's Vocal curve, bass off");+ SGDSPLoadBuiltInPreset((NSInteger)[names indexOfObject:@"Concert hall"]);+ check(SGDSPSwitch(SGKeyDSPReverb) && SGDSPNumber(SGKeyDSPReverbPreset) == 7+ && [SGDSPReverbPresetNames()[7] isEqualToString:@"Large hall"], @"Concert hall: the Large hall reverb");+ // The user's own: everything, the Graphic EQ too.+ SGDSPLoadBuiltInPreset((NSInteger)[names indexOfObject:@"Late night"]);+ NSArray<NSNumber *> *eq = SGDSPGains(SGKeyDSPEqualizerGains);+ SGDSPSetNumber(SGKeyDSPPostGain, 2.5);+ SGDSPSaveUserPreset(@"Mine");+ SGDSPSaveUserPreset(@"another");+ check([SGDSPUserPresetNames() isEqualToArray:(@[@"another", @"Mine"])], @"saved presets listed by name");+ SGDSPResetAll();+ SGDSPSetSwitch(SGKeyDSP, NO);+ SGDSPSetString(SGKeyDSPGraphicEqNodes, @"GraphicEQ: 1000 3;");+ check(SGDSPLoadUserPreset(@"Mine"), @"a saved preset loads");+ check(SGDSPSwitch(SGKeyDSP), @"the master switch on with it");+ check(SGDSPSwitch(SGKeyDSPCompander) && [SGDSPGains(SGKeyDSPEqualizerGains) isEqualToArray:eq] && SGDSPNumber(SGKeyDSPPostGain) == 2.5,+ @"its effects and values back");+ check(SGDSPSwitch(SGKeyDSPGraphicEq) && [SGDSPString(SGKeyDSPGraphicEqNodes) hasPrefix:@"GraphicEQ: 20 -1.2"]+ && SGDSPString(SGKeyDSPGraphicEqHeadphone).length, @"its Graphic EQ back");+ check(![[NSUserDefaults.standardUserDefaults objectForKey:SGKeyDSPUserPresets][@"Mine"] objectForKey:SGKeyDSP],+ @"the master switch not in it");+ check(!SGDSPLoadUserPreset(@"nobody's"), @"an unknown name loads nothing");+ SGDSPDeleteUserPreset(@"another");+ check([SGDSPUserPresetNames() isEqualToArray:@[@"Mine"]], @"a preset deleted");+}++static void checkOnline(void) {+ clearDefaults();+ __block NSArray<SGAutoEqHeadphone *> *all;+ __block NSString *error;+ __block BOOL done = NO;+ SGAutoEqLoadIndex(YES, ^(NSArray<SGAutoEqHeadphone *> *headphones, NSString *why) {+ all = headphones, error = why, done = YES;+ });+ waitFor(^BOOL { return done; });+ check(all.count > 5000 && !error, [NSString stringWithFormat:@"AutoEq's index fetched: %lu headphones (%@)", (unsigned long)all.count, error ?: @"no error"]);+ NSURL *caches = [NSFileManager.defaultManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask].firstObject;+ NSString *cache = [caches URLByAppendingPathComponent:@"Vitrine/AutoEq/INDEX.md"].path;+ check([NSFileManager.defaultManager fileExistsAtPath:cache], @"and cached");++ done = NO;+ __block NSArray<SGAutoEqHeadphone *> *cached;+ SGAutoEqLoadIndex(NO, ^(NSArray<SGAutoEqHeadphone *> *headphones, NSString *why) {+ cached = headphones, done = YES;+ });+ waitFor(^BOOL { return done; });+ check(cached.count == all.count, @"read back from the cache");++ NSArray<SGAutoEqHeadphone *> *found = SGAutoEqSearch(all, @"Sennheiser HD 600 oratory1990");+ check(found.count == 1, [NSString stringWithFormat:@"search: Sennheiser HD 600 by oratory1990 (%lu)", (unsigned long)found.count]);+ if (!found.count) return;+ done = NO;+ error = nil;+ SGAutoEqApply(found[0], ^(NSString *why) {+ error = why, done = YES;+ });+ waitFor(^BOOL { return done; });+ NSString *nodes = SGDSPString(SGKeyDSPGraphicEqNodes);+ check(!error && SGDSPSwitch(SGKeyDSPGraphicEq) && [nodes hasPrefix:@"GraphicEQ: 20 "] && [nodes componentsSeparatedByString:@";"].count > 100+ && [SGDSPString(SGKeyDSPGraphicEqHeadphone) isEqualToString:found[0].path],+ [NSString stringWithFormat:@"HD 600's GraphicEQ downloaded and applied (%@, %lu points)", error ?: @"no error",+ (unsigned long)[nodes componentsSeparatedByString:@";"].count - 1]);++ // Spot-check the rest of the index: each GraphicEQ file is where the address says.+ NSUInteger reached = 0, tried = 0;+ for (NSUInteger i = 0; i < all.count; i += all.count / 12) {+ tried++;+ NSURL *url = SGAutoEqGraphicEqURL(all[i].path);+ NSData *data = [NSData dataWithContentsOfURL:url];+ NSString *text = data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : nil;+ if (SGDSPGraphicEqLine(text)) reached++;+ else printf(" missing: %s\n", url.absoluteString.UTF8String);+ }+ check(reached == tried, [NSString stringWithFormat:@"%lu of %lu headphones across the index have their GraphicEQ file", (unsigned long)reached, (unsigned long)tried]);+ [NSFileManager.defaultManager removeItemAtPath:cache error:nil];+}++int main(int argc, char **argv) {+ @autoreleasepool {+ applied = [NSCountedSet set];+ checkParsing();+ checkPresets();+ if (argc > 1 && !strcmp(argv[1], "online")) checkOnline();+ clearDefaults();+ printf("%d failed\n", failures);+ }+ return failures;+}diff --git a/harness/autoeq/shim/Core/SGCore.h b/harness/autoeq/shim/Core/SGCore.hnew file mode 100644index 00000000..ef640779--- /dev/null+++ b/harness/autoeq/shim/Core/SGCore.h@@ -0,0 +1,4 @@+// The part of Core/SGCore.h that AudioEffectsSettings.m uses, without the UIKit the rest brings: on the Mac+// it is found before the real one.+#import "Core/SGLog.h"+#import "Core/SGPrefs.h"diff --git a/tweak/Sources/App/About/Licenses.m b/tweak/Sources/App/About/Licenses.mindex 781fc87f..9472dd0a 100644--- a/tweak/Sources/App/About/Licenses.m+++ b/tweak/Sources/App/About/Licenses.m@@ -33,10 +33,13 @@ UIViewController *SGLicensesPage(void) {SGModRow *mod = SGLinkRow(@"Vitrine", @"GNU General Public License v3.0", @"https://www.gnu.org/licenses/gpl-3.0.html");SGModRow *bs2b = SGLinkRow(@"libbs2b", @"Crossfeed · MIT License", @"https://github.com/alexmarsev/libbs2b");SGModRow *wdl = SGLinkRow(@"WDL", @"Liveprog's EEL2 · zlib License", @"https://github.com/justinfrankel/WDL");+ // Not shipped: the Headphones page downloads its results when asked, but they are AutoEq's work all the same.+ SGModRow *autoEq = SGLinkRow(@"AutoEq", @"Headphone corrections · MIT License", @"https://github.com/jaakkopasanen/AutoEq");return [[SGModPage alloc] initWithTitle:@"Licenses" intro:@"The mod's own license, and the code from others it includes." sections:@[SGSection(nil, @[mod]),SGNotedSection(nil, @[bs2b], [@"Copyright (c) 2005 Boris Mikhaylov\n\n" stringByAppendingString:kMIT]),SGNotedSection(nil, @[wdl], [@"Copyright (C) 2004-2013 Cockos Incorporated\nCopyright (C) 1999-2003 Nullsoft, Inc.\n\n"stringByAppendingString:kZlib]),+ SGNotedSection(nil, @[autoEq], [@"Copyright (c) 2018-2022 Jaakko Pasanen\n\n" stringByAppendingString:kMIT]),] footer:nil];}diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffects.h b/tweak/Sources/Shared/AudioEffects/AudioEffects.hindex 6cd9273e..1093be37 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffects.h+++ b/tweak/Sources/Shared/AudioEffects/AudioEffects.h@@ -40,6 +40,9 @@// The Graphic EQ, in AutoEq's GraphicEQ format: "GraphicEQ: 20 -1.2; 21 -1.1; ...".#define SGKeyDSPGraphicEq @"spotifyglass.dsp.geq"#define SGKeyDSPGraphicEqNodes @"spotifyglass.dsp.geq.nodes"+// The AutoEq headphone the nodes came from, as its folder in AutoEq's results (SGAutoEqHeadphone.path);+// empty once the text is edited by hand.+#define SGKeyDSPGraphicEqHeadphone @"spotifyglass.dsp.geq.headphone"// File effects name a file in their library (SGDSPLibraryFiles), by its name alone: the app's container// moves on every reinstall, the name does not.diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsLibraryPage.m b/tweak/Sources/Shared/AudioEffects/AudioEffectsLibraryPage.mindex 519bf22f..32559b48 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffectsLibraryPage.m+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsLibraryPage.m@@ -6,6 +6,7 @@#import "Settings/SGPage.h"#import "Settings/SGPageStyle.h"#import "AudioEffectsPage.h"+#import "AudioEffectsPresets.h"static NSString *const kAutoEqURL = @"https://github.com/jaakkopasanen/AutoEq";@@ -347,7 +348,7 @@ typedef NS_ENUM(NSInteger, SGGraphicEqRow) {}- (BOOL)edited {- return ![[self cleaned:_text.text] isEqualToString:SGDSPString(SGKeyDSPGraphicEqNodes)];+ return ![SGDSPGraphicEqLine(_text.text) ?: _text.text isEqualToString:SGDSPString(SGKeyDSPGraphicEqNodes)];}- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {@@ -392,22 +393,16 @@ typedef NS_ENUM(NSInteger, SGGraphicEqRow) {else [self save:kFlatGraphicEq];}-// One line, trimmed: AutoEq's files end in a newline, and a copy out of a web page often has more.-- (NSString *)cleaned:(NSString *)text {- NSCharacterSet *space = NSCharacterSet.whitespaceAndNewlineCharacterSet;- NSArray<NSString *> *words = [text componentsSeparatedByCharactersInSet:space];- words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];- return [words componentsJoinedByString:@" "];-}-- (void)save:(NSString *)text {- NSString *line = [self cleaned:text ?: @""];- if (![line.lowercaseString hasPrefix:@"graphiceq:"]) {+ NSString *line = SGDSPGraphicEqLine(text);+ if (!line) {showAlert(self, text.length ? @"Not a GraphicEQ line" : @"Nothing to paste",@"It starts with \"GraphicEQ:\", then pairs of a frequency and a gain: GraphicEQ: 20 -1.2; 21 -1.1; …");return;}[_text resignFirstResponder];+ // Text of one's own is no longer the headphone's correction the Headphones row names.+ if (![line isEqualToString:SGDSPString(SGKeyDSPGraphicEqNodes)]) SGDSPSetString(SGKeyDSPGraphicEqHeadphone, @"");SGDSPSetString(SGKeyDSPGraphicEqNodes, line);_text.text = line;[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:SGGraphicEqSave inSection:2]] withRowAnimation:UITableViewRowAnimationNone];diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.h b/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.hindex dd0e5e15..2cee2ed5 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.h+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.h@@ -5,6 +5,7 @@// AudioEffectsPage.m the page: the switch, the status, the effects' cards, their sliders and choices// SGDSPCurveView.m the equalizer's and the compander's curve, with a handle to drag per band// AudioEffectsLibraryPage.m a file effect's library (the convolver's, ViPER DDC's, Liveprog's) and the GraphicEQ editor+// AudioEffectsPresetsPage.m Presets and Headphones (AudioEffectsPresets.h)//// Main thread only.#import <UIKit/UIKit.h>@@ -19,3 +20,9 @@ UIViewController *SGDSPLibraryPage(SGDSPFileKind kind);UIViewController *SGDSPGraphicEqPage(void);// The choice of a file effect's library, "None" when there is none.NSString *SGDSPChosenFile(SGDSPFileKind kind);++// The pages the Presets and Headphones rows under the effects' switch push (AudioEffectsPresetsPage.m), and+// the headphone in use, "None" while the Graphic EQ holds none.+UIViewController *SGDSPPresetsPage(void);+UIViewController *SGDSPHeadphonesPage(void);+NSString *SGDSPHeadphoneSummary(void);diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.m b/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.mindex 0ed17175..0dece5e6 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.m+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsPage.m@@ -502,7 +502,7 @@ static UIView *valueAndChevron(NSString *text) {#pragma mark - rows-// Section 0 is the effects' switch, then a card per effect, then the reset.+// Section 0 is the effects' switch, Presets and Headphones, then a card per effect, then the reset.- (SGDSPEffect *)effectIn:(NSInteger)section {return section >= 1 && section <= (NSInteger)_effects.count ? _effects[(NSUInteger)section - 1] : nil;}@@ -522,7 +522,7 @@ static UIView *valueAndChevron(NSString *text) {- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {SGDSPEffect *e = [self effectIn:section];- return e ? [self rowCountOf:e] : 1;+ return e ? [self rowCountOf:e] : section == 0 ? 3 : 1;}// No views, but asked for all the same: without them the table keeps its own spacing, not the heights below.@@ -577,6 +577,8 @@ static UIView *valueAndChevron(NSString *text) {}- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section == 0 && path.row == 1) return [self valueCell:table title:@"Presets" value:@""];+ if (path.section == 0 && path.row == 2) return [self valueCell:table title:@"Headphones" value:SGDSPHeadphoneSummary()];if (path.section == 0) {UITableViewCell *cell = SGDequeueCell(table, @"master");[self fillHead:cell title:@"Effects" subtitle:SGDSPStatus() symbol:@"waveform"];@@ -665,6 +667,10 @@ static UIView *valueAndChevron(NSString *text) {[self confirmReset];return;}+ if (path.section == 0 && path.row > 0) {+ [self.navigationController pushViewController:path.row == 1 ? SGDSPPresetsPage() : SGDSPHeadphonesPage() animated:YES];+ return;+ }SGDSPRow *row = [self rowAt:path];if (!row) return;if (row.kind == SGDSPRowChoice) [self.navigationController pushViewController:[[SGDSPChoicePage alloc] initWithRow:row] animated:YES];@@ -672,7 +678,7 @@ static UIView *valueAndChevron(NSString *text) {}- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {- if (path.section == (NSInteger)_effects.count + 1) return YES;+ if (path.section == (NSInteger)_effects.count + 1 || (path.section == 0 && path.row > 0)) return YES;SGDSPRow *row = [self rowAt:path];return row && (row.kind == SGDSPRowChoice || row.kind == SGDSPRowPage);}diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.h b/tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.hnew file mode 100644index 00000000..f73953d0--- /dev/null+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.h@@ -0,0 +1,60 @@+// Presets and headphones, the two rows under the effects' switch on the Audio effects page.+//+// AudioEffectsPresets.m the built-in presets, the user's own, and the GraphicEQ line check+// AutoEq.m AutoEq's index of headphones, cached, and a headphone's GraphicEQ applied+// AudioEffectsPresetsPage.m their pages+//+// Main thread, except where a function says otherwise.+#import <Foundation/Foundation.h>++// The user's presets, by name, each the spotifyglass.dsp.* keys as they were saved. Outside the dsp.+// prefix, so a preset never holds the presets.+#define SGKeyDSPUserPresets @"spotifyglass.audioPresets"++#pragma mark - presets++// A built-in preset sets a few effects over a reset, leaving the Graphic EQ (the headphones' correction) as+// it is: the correction belongs to the headphones, not to the taste. Loading any preset, or applying a+// headphone, turns the effects' master switch on too, so the pick is heard.+NSArray<NSString *> *SGDSPBuiltInPresetNames(void);+NSString *SGDSPBuiltInPresetDetail(NSInteger index); // the effects it turns on, for the row's subtitle+void SGDSPLoadBuiltInPreset(NSInteger index);++// A user's preset is everything: every spotifyglass.dsp.* key but the master switch, Graphic EQ included.+NSArray<NSString *> *SGDSPUserPresetNames(void); // sorted+void SGDSPSaveUserPreset(NSString *name); // replaces one of the same name+BOOL SGDSPLoadUserPreset(NSString *name);+void SGDSPDeleteUserPreset(NSString *name);++// The text as one GraphicEQ line, trimmed and on one line, or nil when it is not one: what the Graphic EQ+// editor saves and what a headphone's file is checked with.+NSString *SGDSPGraphicEqLine(NSString *text);++#pragma mark - AutoEq++// One headphone of AutoEq's results (github.com/jaakkopasanen/AutoEq, MIT): the name, who measured it+// ("crinacle on 711"), and its folder under results/ as INDEX.md writes it, percent-encoded.+@interface SGAutoEqHeadphone : NSObject+@property (nonatomic, copy) NSString *name;+@property (nonatomic, copy) NSString *source;+@property (nonatomic, copy) NSString *path;+@end++// INDEX.md's "- [Name](./path) by source" lines; anything else is skipped. Any thread.+NSArray<SGAutoEqHeadphone *> *SGAutoEqParseIndex(NSString *markdown);+// The raw address of the headphone's "<folder> GraphicEQ.txt". Any thread.+NSURL *SGAutoEqGraphicEqURL(NSString *path);+// The headphones whose name and source hold every word of the query, case and accents aside.+NSArray<SGAutoEqHeadphone *> *SGAutoEqSearch(NSArray<SGAutoEqHeadphone *> *all, NSString *query);+// The headphone a folder names, for the page's row: its last part, decoded.+NSString *SGAutoEqNameOf(NSString *path);++// The index, from Caches/Vitrine/AutoEq unless `refresh` or the copy is a month old, else from GitHub (the+// cached copy still answering when GitHub does not). `done` runs once on the main queue, with the+// headphones, and why GitHub did not answer when it did not.+void SGAutoEqLoadIndex(BOOL refresh, void (^done)(NSArray<SGAutoEqHeadphone *> *headphones, NSString *error));+// Downloads the headphone's GraphicEQ and applies it; `done` on the main queue with nil or why not.+void SGAutoEqApply(SGAutoEqHeadphone *headphone, void (^done)(NSString *error));+// The second half of that: the file's text into the Graphic EQ, its switch and the master switch on. NO when+// it is not GraphicEQ.+BOOL SGAutoEqApplyText(NSString *path, NSString *text);diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.m b/tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.mnew file mode 100644index 00000000..868505ac--- /dev/null+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsPresets.m@@ -0,0 +1,143 @@+// The presets: built-in ones over a reset, and the user's own as a copy of every dsp key. Everything goes back+// in through AudioEffects.h's setters, so it is clamped and applied the way the page's own changes are.+#import "AudioEffects.h"+#import "AudioEffectsApply.h"+#import "AudioEffectsPresets.h"++static NSString *const kPrefix = @"spotifyglass.dsp.";++static NSUserDefaults *store(void) {+ return NSUserDefaults.standardUserDefaults;+}++// A value back through its setter: a switch (the key naming its own effect), a number, the gains as a+// list, or text. Anything else is left out, a preset from a later build naming a key this one lacks too.+static void setValue(NSString *key, id value) {+ if (![key hasPrefix:kPrefix]) return;+ if ([value isKindOfClass:NSArray.class]) SGDSPSetGains(key, value);+ else if ([value isKindOfClass:NSString.class]) SGDSPSetString(key, value);+ else if (![value isKindOfClass:NSNumber.class]) return;+ else if ([SGDSPEffectOf(key) isEqualToString:key]) SGDSPSetSwitch(key, [value boolValue]);+ else SGDSPSetNumber(key, [value doubleValue]);+}++// A pick is meant to be heard: the master switch, off until asked for, comes on with it.+static void turnOn(void) {+ if (!SGDSPSwitch(SGKeyDSP)) SGDSPSetSwitch(SGKeyDSP, YES);+}++static NSDictionary<NSString *, id> *currentValues(void) {+ NSDictionary<NSString *, id> *all = store().dictionaryRepresentation;+ NSMutableDictionary<NSString *, id> *values = [NSMutableDictionary dictionary];+ for (NSString *key in all) {+ if ([key hasPrefix:kPrefix]) values[key] = all[key];+ }+ return values;+}++#pragma mark - built in++typedef struct {+ NSString *__unsafe_unretained name, *__unsafe_unretained detail;+} SGDSPPresetName;++static const SGDSPPresetName kBuiltIn[] = {+ {@"Bass boost", @"Bass boost at 8 dB"},+ {@"Vocal clarity", @"Equalizer on voices, a light compander"},+ {@"Late night", @"Quiet and loud evened out, less bass"},+ {@"Concert hall", @"A large hall's reverb, a wider stage"},+ {@"Warm analog", @"Tube warmth, a warm equalizer"},+ {@"Headphone comfort", @"Crossfeed, a softer top"},+ {@"Wide stereo", @"Stereo widening"},+};++static NSArray<NSNumber *> *equalizer(NSString *preset) {+ return SGDSPEqualizerPreset((NSInteger)[SGDSPEqualizerPresetNames() indexOfObject:preset]);+}++static NSDictionary<NSString *, id> *builtInValues(NSInteger index) {+ switch (index) {+ case 0: return @{SGKeyDSPBass: @YES, SGKeyDSPBassGain: @8};+ case 1: return @{SGKeyDSPEqualizer: @YES, SGKeyDSPEqualizerGains: equalizer(@"Vocal"),+ SGKeyDSPCompander: @YES, SGKeyDSPCompanderGains: @[@0, @0.2, @0.3, @0.3, @0.3, @0.2, @0]};+ // The compander over 0 lifts the quiet parts and holds the loud ones; the gain brings the level back.+ case 2: return @{SGKeyDSPCompander: @YES, SGKeyDSPCompanderGains: @[@0.6, @0.7, @0.8, @0.8, @0.8, @0.7, @0.6],+ SGKeyDSPCompanderTime: @0.3, SGKeyDSPEqualizer: @YES,+ SGKeyDSPEqualizerGains: @[@-6, @-5, @-4, @-2, @-1, @0, @0, @0, @0, @0, @0, @0, @-1, @-2, @-2],+ SGKeyDSPPostGain: @3, SGKeyDSPLimiterThreshold: @-3};+ case 3: return @{SGKeyDSPReverb: @YES, SGKeyDSPReverbPreset: @7, SGKeyDSPReverbAmount: @40,+ SGKeyDSPStereoWide: @YES, SGKeyDSPStereoWideLevel: @65};+ case 4: return @{SGKeyDSPTube: @YES, SGKeyDSPTubeDrive: @6, SGKeyDSPEqualizer: @YES, SGKeyDSPEqualizerGains: equalizer(@"Warm")};+ case 5: return @{SGKeyDSPCrossfeed: @YES, SGKeyDSPCrossfeedMode: @2, SGKeyDSPEqualizer: @YES,+ SGKeyDSPEqualizerGains: @[@0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @-1, @-2, @-2, @-3, @-3]};+ case 6: return @{SGKeyDSPStereoWide: @YES, SGKeyDSPStereoWideLevel: @75};+ }+ return nil;+}++NSArray<NSString *> *SGDSPBuiltInPresetNames(void) {+ NSMutableArray<NSString *> *names = [NSMutableArray array];+ for (size_t i = 0; i < sizeof kBuiltIn / sizeof *kBuiltIn; i++) [names addObject:kBuiltIn[i].name];+ return names;+}++NSString *SGDSPBuiltInPresetDetail(NSInteger index) {+ return index >= 0 && index < (NSInteger)(sizeof kBuiltIn / sizeof *kBuiltIn) ? kBuiltIn[index].detail : nil;+}++void SGDSPLoadBuiltInPreset(NSInteger index) {+ NSDictionary<NSString *, id> *values = builtInValues(index);+ if (!values) return;+ NSMutableDictionary<NSString *, id> *kept = [NSMutableDictionary dictionary];+ NSDictionary<NSString *, id> *now = currentValues();+ for (NSString *key in now) {+ if ([SGDSPEffectOf(key) isEqualToString:SGKeyDSPGraphicEq]) kept[key] = now[key];+ }+ SGDSPResetAll();+ for (NSString *key in kept) setValue(key, kept[key]);+ for (NSString *key in values) setValue(key, values[key]);+ turnOn();+}++#pragma mark - the user's++static NSDictionary<NSString *, NSDictionary *> *userPresets(void) {+ id presets = [store() objectForKey:SGKeyDSPUserPresets];+ return [presets isKindOfClass:NSDictionary.class] ? presets : @{};+}++NSArray<NSString *> *SGDSPUserPresetNames(void) {+ return [userPresets().allKeys sortedArrayUsingSelector:@selector(localizedStandardCompare:)];+}++void SGDSPSaveUserPreset(NSString *name) {+ if (!name.length) return;+ NSMutableDictionary *presets = [userPresets() mutableCopy];+ presets[name] = currentValues();+ [store() setObject:presets forKey:SGKeyDSPUserPresets];+}++BOOL SGDSPLoadUserPreset(NSString *name) {+ NSDictionary *values = userPresets()[name];+ if (![values isKindOfClass:NSDictionary.class]) return NO;+ SGDSPResetAll();+ for (NSString *key in values) setValue(key, values[key]);+ turnOn();+ return YES;+}++void SGDSPDeleteUserPreset(NSString *name) {+ NSMutableDictionary *presets = [userPresets() mutableCopy];+ [presets removeObjectForKey:name];+ [store() setObject:presets forKey:SGKeyDSPUserPresets];+}++#pragma mark - GraphicEQ text++// One line: AutoEq's files end in a newline, and a copy out of a web page often has more.+NSString *SGDSPGraphicEqLine(NSString *text) {+ NSArray<NSString *> *words = [text ?: @"" componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];+ NSString *line = [words componentsJoinedByString:@" "];+ return [line.lowercaseString hasPrefix:@"graphiceq:"] ? line : nil;+}diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsPresetsPage.m b/tweak/Sources/Shared/AudioEffects/AudioEffectsPresetsPage.mnew file mode 100644index 00000000..67394465--- /dev/null+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsPresetsPage.m@@ -0,0 +1,389 @@+// The Presets and Headphones pages the Audio effects page's first card opens. Both stay open after a pick,+// so one preset or one headphone after another can be heard before going back.+#import "Core/SGCore.h"+#import "Settings/SGPage.h"+#import "Settings/SGPageStyle.h"+#import "AudioEffectsPage.h"+#import "AudioEffectsPresets.h"++static void showAlert(UIViewController *owner, NSString *title, NSString *message) {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];+ [owner presentViewController:alert animated:YES completion:nil];+}++static void tick(UITableViewCell *cell, BOOL on) {+ if (on) {+ UIImageView *tick = SGSymbolView(@"checkmark", 13, UIImageSymbolWeightSemibold, 16);+ tick.tintColor = SGGreen();+ cell.accessoryView = tick;+ }+ cell.accessibilityTraits = on ? UIAccessibilityTraitButton | UIAccessibilityTraitSelected : UIAccessibilityTraitButton;+}++#pragma mark - presets++// A pick replaces every effect's settings, so the first pick each time the page opens saves them first,+// as one of the user's presets under this name, kept at the top of theirs: a tap on it puts them back.+static NSString *const kBeforePresets = @"Before presets";++// The user's presets, the settings from before the last round of picks first.+static NSArray<NSString *> *userPresetNames(void) {+ NSMutableArray<NSString *> *names = [SGDSPUserPresetNames() mutableCopy];+ if ([names containsObject:kBeforePresets]) {+ [names removeObject:kBeforePresets];+ [names insertObject:kBeforePresets atIndex:0];+ }+ return names;+}++// The built-in presets, then the user's, then Save. The last one picked is ticked until something else is.+@interface SGDSPPresetList : SGPage+@end++@implementation SGDSPPresetList {+ NSArray<NSString *> *_builtIn, *_mine;+ NSIndexPath *_picked;+ UIView *_footer;+ BOOL _kept; // the settings from before this page's first pick are saved+}++- (instancetype)init {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = @"Presets";+ _builtIn = SGDSPBuiltInPresetNames();+ return self;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ _footer = SGNote(@"Picking a preset turns Audio effects on and replaces the other effects' settings. A built-in "+ "preset leaves the Graphic EQ, your headphones' correction, as it is; your own presets keep every "+ "effect, the Graphic EQ too. What you had before the first pick is kept under Yours as Before presets. "+ "Swipe left on one of yours to delete it.");+ self.tableView.tableFooterView = _footer;+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ SGFitNote(self.tableView, _footer, 16, 24);+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGInsetForBars(self.tableView);+}++- (void)viewWillAppear:(BOOL)animated {+ [super viewWillAppear:animated];+ _mine = userPresetNames();+ [self.tableView reloadData];+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return 3;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ if (section == 0) return (NSInteger)_builtIn.count;+ if (section == 1) return MAX((NSInteger)_mine.count, 1);+ return 1;+}++- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ return section == 2 ? nil : SGSectionHeader(table, section == 0 ? @"Built in" : @"Yours");+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return section == 2 ? SGSectionGap : SGSectionHeaderHeight;+}++- (UIView *)tableView:(UITableView *)table viewForFooterInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForFooterInSection:(NSInteger)section {+ return CGFLOAT_MIN;+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ UITableViewCell *cell = SGDequeueCell(table, @"preset");+ if (path.section == 2) {+ SGFillCell(cell, @"Save current settings…", @"Every effect as it is now, under a name", nil, @"square.and.arrow.down");+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ return cell;+ }+ if (path.section == 1 && !_mine.count) {+ SGFillCell(cell, @"None saved yet", nil, SGGrey(), nil);+ cell.accessibilityTraits = UIAccessibilityTraitNone;+ return cell;+ }+ BOOL builtIn = path.section == 0;+ SGFillCell(cell, (builtIn ? _builtIn : _mine)[(NSUInteger)path.row], builtIn ? SGDSPBuiltInPresetDetail(path.row) : nil, nil, nil);+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ tick(cell, [path isEqual:_picked]);+ return cell;+}++- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {+ return path.section != 1 || _mine.count;+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ if (path.section == 2) {+ [self askForName];+ return;+ }+ if (path.section == 1 && !_mine.count) return;+ NSString *name = path.section == 1 ? _mine[(NSUInteger)path.row] : nil;+ // Loading Before presets itself is the way back, so it is never written over by its own pick.+ if (!_kept && ![name isEqualToString:kBeforePresets]) {+ SGDSPSaveUserPreset(kBeforePresets);+ _kept = YES;+ _mine = userPresetNames();+ }+ if (path.section == 0) SGDSPLoadBuiltInPreset(path.row);+ else if (!SGDSPLoadUserPreset(name)) return;+ _picked = name ? [NSIndexPath indexPathForRow:(NSInteger)[_mine indexOfObject:name] inSection:1] : path;+ [table reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)] withRowAnimation:UITableViewRowAnimationNone];+}++- (UISwipeActionsConfiguration *)tableView:(UITableView *)table trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)path {+ if (path.section != 1 || !_mine.count) return nil;+ NSString *name = _mine[(NSUInteger)path.row];+ UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"Delete"+ handler:^(UIContextualAction *action, UIView *view, void (^done)(BOOL)) {+ SGDSPDeleteUserPreset(name);+ self->_mine = userPresetNames();+ NSIndexPath *picked = self->_picked;+ if (picked.section == 1 && picked.row == path.row) self->_picked = nil;+ else if (picked.section == 1 && picked.row > path.row) self->_picked = [NSIndexPath indexPathForRow:picked.row - 1 inSection:1];+ // The rows under it close up; the last one gives way to the placeholder instead.+ if (self->_mine.count) [self.tableView deleteRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationAutomatic];+ else [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];+ done(YES);+ }];+ delete.image = [UIImage systemImageNamed:@"trash"];+ return [UISwipeActionsConfiguration configurationWithActions:@[delete]];+}++- (void)askForName {+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Save preset"+ message:@"A preset of the same name is replaced." preferredStyle:UIAlertControllerStyleAlert];+ [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {+ field.placeholder = @"Name";+ field.autocapitalizationType = UITextAutocapitalizationTypeSentences;+ field.keyboardAppearance = UIKeyboardAppearanceDark;+ }];+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];+ [alert addAction:[UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {+ NSString *name = [alert.textFields.firstObject.text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ if (!name.length) return;+ SGDSPSaveUserPreset(name);+ self->_mine = userPresetNames();+ self->_picked = [NSIndexPath indexPathForRow:(NSInteger)[self->_mine indexOfObject:name] inSection:1];+ [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)] withRowAnimation:UITableViewRowAnimationFade];+ }]];+ [self presentViewController:alert animated:YES completion:nil];+}++@end++UIViewController *SGDSPPresetsPage(void) {+ return [SGDSPPresetList new];+}++#pragma mark - headphones++// AutoEq's headphones under a search field, the one in use ticked, with None above them. A tap downloads its+// GraphicEQ and turns the Graphic EQ on with it; None turns it off again. Pulling down fetches the list again.+@interface SGDSPHeadphoneList : SGPage <UISearchBarDelegate>+@end++@implementation SGDSPHeadphoneList {+ NSArray<SGAutoEqHeadphone *> *_all, *_shown;+ NSString *_message; // loading, or why the list did not come+ BOOL _failed;+ NSString *_applying; // the path being downloaded+ UISearchBar *_search;+ UIView *_header, *_footer;+}++- (instancetype)init {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = @"Headphones";+ return self;+}++- (void)viewDidLoad {+ [super viewDidLoad];+ UITableView *table = self.tableView;+ table.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;+ _search = [UISearchBar new];+ _search.placeholder = @"Search headphones";+ _search.searchBarStyle = UISearchBarStyleMinimal;+ _search.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ _search.keyboardAppearance = UIKeyboardAppearanceDark;+ _search.delegate = self;+ _header = SGNote(@"Corrections that make your headphones sound neutral, measured by AutoEq. Picking one turns Audio effects and the Graphic EQ on with it.");+ [_header addSubview:_search];+ table.tableHeaderView = _header;+ _footer = SGNote(@"From AutoEq by Jaakko Pasanen, MIT License. Pull down to fetch the list again.");+ table.tableFooterView = _footer;+ self.refreshControl = [UIRefreshControl new];+ [self.refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];+ [self load:NO];+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ _search.frame = CGRectMake(8, 4, self.tableView.bounds.size.width - 16, 44);+ SGFitNote(self.tableView, _header, 52, 8);+ SGFitNote(self.tableView, _footer, 16, 24);+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGInsetForBars(self.tableView);+}++- (void)refresh {+ [self load:YES];+}++- (void)load:(BOOL)refresh {+ if (!_all) _message = @"Loading AutoEq's list…";+ _failed = NO;+ [self.tableView reloadData];+ SGAutoEqLoadIndex(refresh, ^(NSArray<SGAutoEqHeadphone *> *headphones, NSString *error) {+ [self.refreshControl endRefreshing];+ if (headphones) self->_all = headphones;+ self->_failed = error != nil;+ self->_message = error ? [NSString stringWithFormat:@"%@. Tap to try again.", error] : nil;+ [self filter];+ });+}++- (void)filter {+ _shown = SGAutoEqSearch(_all ?: @[], _search.text);+ [self.tableView reloadData];+}++- (void)searchBar:(UISearchBar *)bar textDidChange:(NSString *)text {+ [self filter];+}++- (void)searchBarSearchButtonClicked:(UISearchBar *)bar {+ [bar resignFirstResponder];+}++// Whether a headphone's correction is what the Graphic EQ plays, rather than nothing or the user's own curve.+static BOOL headphoneInUse(void) {+ return SGDSPSwitch(SGKeyDSPGraphicEq) && SGDSPString(SGKeyDSPGraphicEqHeadphone).length;+}++// Sections: the loading or error message, None, the headphones.+- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return 3;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ if (section == 0) return _message ? 1 : 0;+ if (section == 1) return 1;+ return _all && !_shown.count && _search.text.length ? 1 : (NSInteger)_shown.count;+}++- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return section == 0 && !_message ? CGFLOAT_MIN : SGSectionGap;+}++- (UIView *)tableView:(UITableView *)table viewForFooterInSection:(NSInteger)section {+ return nil;+}++- (CGFloat)tableView:(UITableView *)table heightForFooterInSection:(NSInteger)section {+ return CGFLOAT_MIN;+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ UITableViewCell *cell = SGDequeueCell(table, @"headphone");+ if (path.section == 0) {+ SGFillCell(cell, _message, nil, _failed ? SGRed() : SGGrey(), _failed ? @"exclamationmark.triangle.fill" : nil);+ cell.selectionStyle = _failed ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;+ return cell;+ }+ cell.accessibilityValue = nil;+ if (path.section == 1) {+ SGFillCell(cell, @"None", nil, nil, nil);+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ tick(cell, !headphoneInUse());+ return cell;+ }+ if (!_shown.count) {+ SGFillCell(cell, @"No headphones match", nil, SGGrey(), nil);+ cell.accessibilityTraits = UIAccessibilityTraitNone;+ return cell;+ }+ SGAutoEqHeadphone *headphone = _shown[(NSUInteger)path.row];+ SGFillCell(cell, headphone.name, headphone.source, nil, nil);+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ if ([headphone.path isEqualToString:_applying]) {+ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium];+ spinner.color = SGGrey();+ spinner.accessibilityLabel = @"Applying";+ [spinner startAnimating];+ cell.accessoryView = spinner;+ // The cell is what VoiceOver reads, not the spinner in it.+ cell.accessibilityValue = @"Applying";+ return cell;+ }+ tick(cell, headphoneInUse() && [headphone.path isEqualToString:SGDSPString(SGKeyDSPGraphicEqHeadphone)]);+ return cell;+}++- (BOOL)tableView:(UITableView *)table shouldHighlightRowAtIndexPath:(NSIndexPath *)path {+ if (path.section == 0) return _failed;+ return (path.section == 1 || _shown.count > 0) && !_applying;+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ if (path.section == 0) {+ if (_failed) [self load:YES];+ return;+ }+ if (_applying) return;+ if (path.section == 1) {+ // Only a headphone's correction is taken off: a curve of the user's own, with no headphone, stays.+ if (!headphoneInUse()) return;+ SGDSPSetString(SGKeyDSPGraphicEqHeadphone, @"");+ SGDSPSetSwitch(SGKeyDSPGraphicEq, NO);+ [table reloadData];+ return;+ }+ if (!_shown.count) return;+ SGAutoEqHeadphone *headphone = _shown[(NSUInteger)path.row];+ _applying = headphone.path;+ [table reloadData];+ SGAutoEqApply(headphone, ^(NSString *error) {+ self->_applying = nil;+ [self.tableView reloadData];+ if (error) showAlert(self, [NSString stringWithFormat:@"Could not apply %@", headphone.name], error);+ });+}++@end++UIViewController *SGDSPHeadphonesPage(void) {+ return [SGDSPHeadphoneList new];+}++NSString *SGDSPHeadphoneSummary(void) {+ NSString *path = SGDSPString(SGKeyDSPGraphicEqHeadphone);+ return path.length && SGDSPSwitch(SGKeyDSPGraphicEq) ? SGAutoEqNameOf(path) : @"None";+}diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffectsSettings.m b/tweak/Sources/Shared/AudioEffects/AudioEffectsSettings.mindex ab3000ba..939ae762 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffectsSettings.m+++ b/tweak/Sources/Shared/AudioEffects/AudioEffectsSettings.m@@ -38,6 +38,7 @@ static NSDictionary<NSString *, NSString *> *stringDefaults(void) {SGKeyDSPCompanderGains: @"0;0;0;0;0;0;0",SGKeyDSPEqualizerGains: @"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0",SGKeyDSPGraphicEqNodes: @"GraphicEQ: 0.0 0.0;",+ SGKeyDSPGraphicEqHeadphone: @"",SGKeyDSPConvolverFile: @"",SGKeyDSPDDCFile: @"",SGKeyDSPLiveprogFile: @"",diff --git a/tweak/Sources/Shared/AudioEffects/AutoEq.m b/tweak/Sources/Shared/AudioEffects/AutoEq.mnew file mode 100644index 00000000..f0088968--- /dev/null+++ b/tweak/Sources/Shared/AudioEffects/AutoEq.m@@ -0,0 +1,139 @@+// AutoEq's headphone corrections, read straight from its public repository: github.com/jaakkopasanen/AutoEq,+// MIT License, Copyright (c) 2018-2022 Jaakko Pasanen. Nothing of it ships in the mod; results/INDEX.md and+// the chosen headphone's GraphicEQ file are downloaded when asked for.+//+// INDEX.md, as of October 2026, is a heading and a note, then one line per result:+// - [1MORE Quad Driver](./crinacle/711%20in-ear/1MORE%20Quad%20Driver) by crinacle on 711+// and the folder holds "<folder's last part> GraphicEQ.txt", one "GraphicEQ: 20 -0.2; 21 -0.2; ..." line.+// The file is named after the folder, not the name in brackets: the name can carry a target the folder+// does not.+#import "Core/SGLog.h"+#import "AudioEffects.h"+#import "AudioEffectsPresets.h"++static NSString *const kResults = @"https://raw.githubusercontent.com/jaakkopasanen/AutoEq/master/results/";+static const NSTimeInterval kIndexLife = 30 * 24 * 3600;++@implementation SGAutoEqHeadphone+@end++NSArray<SGAutoEqHeadphone *> *SGAutoEqParseIndex(NSString *markdown) {+ NSMutableArray<SGAutoEqHeadphone *> *headphones = [NSMutableArray array];+ [markdown enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {+ if (![line hasPrefix:@"- ["]) return;+ // The last "](./" and the last ") by ": names hold brackets and folders parentheses.+ NSRange link = [line rangeOfString:@"](./" options:NSBackwardsSearch];+ NSRange by = [line rangeOfString:@") by " options:NSBackwardsSearch];+ if (link.location == NSNotFound || by.location == NSNotFound || by.location <= NSMaxRange(link)) return;+ SGAutoEqHeadphone *headphone = [SGAutoEqHeadphone new];+ headphone.name = [line substringWithRange:NSMakeRange(3, link.location - 3)];+ headphone.path = [line substringWithRange:NSMakeRange(NSMaxRange(link), by.location - NSMaxRange(link))];+ headphone.source = [line substringFromIndex:NSMaxRange(by)];+ if (headphone.name.length && headphone.path.length) [headphones addObject:headphone];+ }];+ return headphones;+}++// Decoded and encoded again: INDEX.md leaves some characters raw ("$", "&", parentheses) that a URL may not.+NSURL *SGAutoEqGraphicEqURL(NSString *path) {+ NSString *folder = path.stringByRemovingPercentEncoding ?: path;+ NSString *file = [NSString stringWithFormat:@"%@/%@ GraphicEQ.txt", folder, folder.lastPathComponent];+ NSString *encoded = [file stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];+ return encoded ? [NSURL URLWithString:[kResults stringByAppendingString:encoded]] : nil;+}++NSString *SGAutoEqNameOf(NSString *path) {+ NSString *folder = path.stringByRemovingPercentEncoding ?: path;+ return folder.lastPathComponent;+}++NSArray<SGAutoEqHeadphone *> *SGAutoEqSearch(NSArray<SGAutoEqHeadphone *> *all, NSString *query) {+ NSStringCompareOptions loose = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;+ NSArray<NSString *> *words = [query componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceCharacterSet];+ words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];+ if (!words.count) return all;+ NSMutableArray<SGAutoEqHeadphone *> *found = [NSMutableArray array];+ for (SGAutoEqHeadphone *headphone in all) {+ NSString *text = [NSString stringWithFormat:@"%@ %@", headphone.name, headphone.source];+ BOOL match = YES;+ for (NSString *word in words) match = match && [text rangeOfString:word options:loose].location != NSNotFound;+ if (match) [found addObject:headphone];+ }+ return found;+}++#pragma mark - downloads++static NSURL *cachedIndex(void) {+ NSURL *caches = [NSFileManager.defaultManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask].firstObject;+ NSURL *folder = [caches URLByAppendingPathComponent:@"Vitrine/AutoEq" isDirectory:YES];+ [NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:nil];+ return [folder URLByAppendingPathComponent:@"INDEX.md"];+}++// The body of a 200 answer as text, or nil and why not. `done` on URLSession's queue, not the main one.+static void fetchText(NSURL *url, void (^done)(NSString *text, NSString *error)) {+ NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;+ NSString *text = status == 200 && data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : nil;+ NSString *why = text ? nil : error ? error.localizedDescription : [NSString stringWithFormat:@"GitHub answered %ld", (long)status];+ if (why) SGLog(@"autoeq: %@ failed (%@)", url.path, why);+ done(text, why);+ }] resume];+}++void SGAutoEqLoadIndex(BOOL refresh, void (^done)(NSArray<SGAutoEqHeadphone *> *, NSString *)) {+ NSURL *cache = cachedIndex();+ NSDate *saved = [NSFileManager.defaultManager attributesOfItemAtPath:cache.path error:nil].fileModificationDate;+ void (^fromCache)(NSString *) = ^(NSString *why) {+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ NSString *text = [NSString stringWithContentsOfURL:cache encoding:NSUTF8StringEncoding error:nil];+ NSArray<SGAutoEqHeadphone *> *headphones = text ? SGAutoEqParseIndex(text) : nil;+ dispatch_async(dispatch_get_main_queue(), ^{+ // A failed refresh still says so over the saved list.+ done(headphones.count ? headphones : nil, why ?: (headphones.count ? nil : @"The saved list could not be read"));+ });+ });+ };+ if (saved && !refresh && -saved.timeIntervalSinceNow < kIndexLife) {+ fromCache(nil);+ return;+ }+ // Its 8850 lines are read and saved off the main thread, which has only the answer.+ fetchText([NSURL URLWithString:[kResults stringByAppendingString:@"INDEX.md"]], ^(NSString *text, NSString *error) {+ // A page that answers but holds no headphones is not kept over a good copy.+ NSArray<SGAutoEqHeadphone *> *headphones = text ? SGAutoEqParseIndex(text) : nil;+ if (!headphones.count) {+ fromCache(error ?: @"AutoEq's list has no headphones in it");+ return;+ }+ [text writeToURL:cache atomically:YES encoding:NSUTF8StringEncoding error:nil];+ dispatch_async(dispatch_get_main_queue(), ^{ done(headphones, nil); });+ });+}++BOOL SGAutoEqApplyText(NSString *path, NSString *text) {+ NSString *line = SGDSPGraphicEqLine(text);+ if (!line || !path.length) return NO;+ SGDSPSetString(SGKeyDSPGraphicEqNodes, line);+ SGDSPSetString(SGKeyDSPGraphicEqHeadphone, path);+ SGDSPSetSwitch(SGKeyDSPGraphicEq, YES);+ // The correction is meant to be heard: the master switch, off until asked for, comes on with it.+ if (!SGDSPSwitch(SGKeyDSP)) SGDSPSetSwitch(SGKeyDSP, YES);+ return YES;+}++void SGAutoEqApply(SGAutoEqHeadphone *headphone, void (^done)(NSString *)) {+ NSURL *url = SGAutoEqGraphicEqURL(headphone.path);+ if (!url) {+ done(@"Its address could not be made");+ return;+ }+ fetchText(url, ^(NSString *text, NSString *error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (error) done(error);+ else done(SGAutoEqApplyText(headphone.path, text) ? nil : @"The file is not a GraphicEQ line");+ });+ });+}