Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
fix: each of Spotify's output units keeps its own mixer, clock and format
My-Name-Is-Jeff8ce79faa275d
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex dfed6a6b..778f6b2c 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -156,12 +156,23 @@ 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). Pitch follows speed (on until switched off,+ (SpeedPitchMenu.x, SpeedPitch.x, SGTimePitch.m). Spotify runs a chain per sample rate, so a local+ file at another rate can have two RemoteIO units running at once: SpeedPitch.x keeps a record+ per unit (its own mixer, sample time, largest slice and formats; AudioOutputUnitStop and+ AudioComponentInstanceDispose rebound too, a disposed unit forgotten after its render in progress)+ and names one the music's (SGPlayerMusicOutput), the one Spotify started or connected last, or+ one with sound when that one has had none for a second; speed and pitch, Sing's stage, the audio+ effects and Music Haptics follow it (SGPlayerWatchMusicOutput), and the other plays as Spotify+ made it. A connection whose formats the callback cannot take (not float with a buffer per channel,+ more than two channels, or a mixer at another rate than the unit) gets Spotify's own connection+ back. Each start, stop and dispose is logged as `audio:` with its formats and where the processors+ are. Pitch follows speed (on until switched off,spotifyglass.speed.pitchFollows) plays the speed through Apple's Varispeed instead, faster and highertogether like a record; Varispeed also carries 1x while it is on, so a return to normal speed changesnothing, and the stretch is left for pitch alone at 1x, the two swapped only through a reset. A newformat on either side of the output while it runs (a route to another rate, Spotify handing it- another one) makes the unit again for it, and until then the sound passes as it is. Under the+ another one) makes the unit again for it, and until then the sound passes as it is. harness/speed's+ `two` runs a 44.1 and a 48 kHz chain at once. Under thesliders a Reverb slider sets the audio effects' reverb amount (spotifyglass.dsp.reverb.amount), turningthe 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 the@@ -172,9 +183,8 @@ Shared:block stays out of it unless the sheet itself is shown (SGPlayerMenuReplaced). Switch to video,the chip over the title of a song with a music video, is hidden under either look on request(VideoSwitch.x, spotifyglass.hide.videoSwitch), by its identifier in FloatingElementsUnit- AudioEffects/ the audio effects on Spotify's sound (AudioEffects.h has the keys and the page's calls): Spotify's- import of AudioOutputUnitStart is rebound, as Music Haptics does, and a render notify on its RemoteIO- unit runs each finished buffer through the mod's own engine, re-blocked to 1024 frames one block late,+ AudioEffects/ the audio effects on Spotify's sound (AudioEffects.h has the keys and the page's calls): a render+ notify on the music's RemoteIO unit (SGPlayerMusicOutput, Shared/Player) runs each finished buffer through the mod's own engine, re-blocked to 1024 frames one block late,in place (AudioEffects.x, SGDSPEngine.m). The buffers are in the unit's output format, thehardware'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 of@@ -205,8 +215,8 @@ Shared: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- playing along with the song: Spotify's import of AudioOutputUnitStart is rebound so its RemoteIO output- unit gets a render notify, the samples, in the unit's output format (the hardware's), go through a drum+ playing along with the song: the music's RemoteIO output unit (SGPlayerMusicOutput, Shared/Player)+ gets a render notify, the samples, in the unit's output format (the hardware's), go through a drumand bass analyzer on the render thread (SGMusicAnalyzer.m, plain C), and a thread of its own schedulesthe taps and the rumble for when the sound is heard, at their strength and leaving out what Followsleaves out (MusicHaptics.x). Everything applies at once; nothing plays while Spotify is not the activediff --git a/harness/audio-effects/README.md b/harness/audio-effects/README.mdindex d4f5991f..3afd538f 100644--- a/harness/audio-effects/README.md+++ b/harness/audio-effects/README.md@@ -40,13 +40,16 @@ into an app whose main executable is the harness, so its `AudioOutputUnitStart`slot as Spotify's does. A second render notify, added after the output started and so after the effects', measureswhat they left in the buffer while a script flips settings: the switch off and a gain that must not apply, theswitch on and -12 dB, a Liveprog script from the library swapping the channels, a reverb ringing out after the-source stops, a file missing from the library and its error, then a 16-bit interleaved client at 48 kHz.+source stops, a file missing from the library and its error, then a 16-bit interleaved client at 48 kHz, then a+second chain at 44.1 kHz started beside it: the effects move to the second chain and the first plays untouched,+and when the second stops they move back. SpeedPitch.x is compiled in, since it names the output the effects+follow.THEOS=$HOME/theos ./build-sim.shxcrun simctl install <udid> build/sim/AudioEffectsHarness.appxcrun simctl launch --console-pty <udid> com.vojta.audioeffectsharness-Use a device of your own on the iOS 26.5 runtime (`xcrun simctl create`), by UDID, and launch it once: the iOS 27-simulator crashes harnesses like this one, and every crash puts a dialog on the Mac's screen. The tweak's own lines+Use a device of your own (`xcrun simctl create`), by UDID. The app has the shared scene delegate (`../scene.m`),+without which iOS 27 kills it at launch; 2026-10-06 all passed on the iOS 27.0 simulator. The tweak's own linesare in the unified log:`xcrun simctl spawn <udid> log show --last 2m --predicate 'eventMessage CONTAINS "[spotifyglass]"'`.diff --git a/harness/audio-effects/build-sim.sh b/harness/audio-effects/build-sim.shindex 1853e12e..1fa38fff 100755--- a/harness/audio-effects/build-sim.sh+++ b/harness/audio-effects/build-sim.sh@@ -1,8 +1,9 @@#!/bin/sh# Builds the simulator harness (sim/main.m): AudioEffects.x generated by logos with the internal generator as-# the tweak builds it, its settings, libraries and engine, and the third-party C (vendor/audio, made here-# first), in an app whose main executable is the harness, so the rebinding of AudioOutputUnitStart takes as it-# does in Spotify.+# the tweak builds it, its settings, libraries and engine, Shared/Player's SpeedPitch.x, which keeps Spotify's+# outputs apart and tells the effects which is the music's, and the third-party C (vendor/audio, made here+# first), in an app whose main executable is the harness, so the rebinding of Spotify's audio imports takes as+# it does in Spotify.# THEOS=$HOME/theos ./build-sim.shset -ecd "$(dirname "$0")"@@ -14,12 +15,13 @@ make -s -C "$VENDOR" PLATFORM=sim -j8rm -rf "$OUT"mkdir -p "$OUT/gen" "$OUT/AudioEffectsHarness.app""$THEOS/bin/logos.pl" -c generator=internal "$FX/AudioEffects.x" > "$OUT/gen/AudioEffects.m"+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/Player/SpeedPitch.x" > "$OUT/gen/SpeedPitch.m"SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O1 -isysroot "$SDK" -Wno-deprecated-declarations \- -I"$SRC" -I"$FX" -isystem "$VENDOR/libbs2b" -isystem "$VENDOR/wdl/eel2" \- sim/main.m "$OUT/gen/AudioEffects.m" "$FX/AudioEffectsSettings.m" "$FX/AudioEffectsFiles.m" "$FX"/SGDSPEngine.m "$FX"/SGDSPFilters.m \+ -I"$SRC" -I"$FX" -I"$SRC/Shared/Player" -isystem "$VENDOR/libbs2b" -isystem "$VENDOR/wdl/eel2" \+ sim/main.m ../scene.m "$OUT/gen/AudioEffects.m" "$OUT/gen/SpeedPitch.m" "$SRC/Shared/Player/SGTimePitch.m" "$FX/AudioEffectsSettings.m" "$FX/AudioEffectsFiles.m" "$FX"/SGDSPEngine.m "$FX"/SGDSPFilters.m \"$FX"/SGDSPConvolver.m "$FX"/SGDSPTone.m "$FX"/SGDSPDynamics.m "$FX"/SGDSPCrossfeed.m "$FX"/SGDSPReverb.m "$FX"/SGDSPLiveprog.m \- "$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$VENDOR/build/sim/libsgaudio.a" \+ "$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$SRC/Core/SGUIMode.m" "$SRC/Core/SGFlagForce.m" "$VENDOR/build/sim/libsgaudio.a" \-framework UIKit -framework AudioToolbox -framework AVFoundation -framework Accelerate -framework Foundation \-o "$OUT/AudioEffectsHarness.app/AudioEffectsHarness"cat > "$OUT/AudioEffectsHarness.app/Info.plist" <<'PLIST'@@ -32,7 +34,15 @@ cat > "$OUT/AudioEffectsHarness.app/Info.plist" <<'PLIST'<key>CFBundleVersion</key><string>1</string><key>CFBundleShortVersionString</key><string>1.0</string><key>UILaunchScreen</key><dict/>-<key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key><false/></dict>+<key>UIApplicationSceneManifest</key><dict>+ <key>UIApplicationSupportsMultipleScenes</key><false/>+ <key>UISceneConfigurations</key><dict>+ <key>UIWindowSceneSessionRoleApplication</key><array><dict>+ <key>UISceneConfigurationName</key><string>Default</string>+ <key>UISceneDelegateClassName</key><string>SGRHarnessScene</string>+ </dict></array>+ </dict>+</dict></dict></plist>PLISTecho "built $OUT/AudioEffectsHarness.app"diff --git a/harness/audio-effects/sim/main.m b/harness/audio-effects/sim/main.mindex 709434b8..1fa4030e 100644--- a/harness/audio-effects/sim/main.m+++ b/harness/audio-effects/sim/main.m@@ -19,6 +19,15 @@static const float kAmplitude = 0.25f;+// SpeedPitch.x hooks Spotify's player state; this stands in for it.+@interface SPTPlayerState : NSObject+@end+@implementation SPTPlayerState+- (double)playbackSpeed {+ return 1;+}+@end+static atomic_bool sg_mute;static atomic_uint_fast64_t sg_phase;static double sg_generatorRate;@@ -40,8 +49,9 @@ static OSStatus generate(void *refCon, AudioUnitRenderActionFlags *flags, constenum { kProbeCalls = 64 };typedef struct { float left, right; UInt32 frames; bool silent; } ProbeCall;-static ProbeCall sg_calls[kProbeCalls];-static atomic_uint sg_callCount;+// One ring per output: [0] the chain the script starts with, [1] the second chain run beside it.+static ProbeCall sg_calls[2][kProbeCalls];+static atomic_uint sg_callCount[2];static OSStatus probe(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,UInt32 frames, AudioBufferList *data) {@@ -55,21 +65,22 @@ static OSStatus probe(void *refCon, AudioUnitRenderActionFlags *flags, const Audleft += l[i] * l[i];right += r[i] * r[i];}- unsigned n = atomic_load(&sg_callCount);- sg_calls[n % kProbeCalls] = (ProbeCall){(float)(left / frames), (float)(right / frames), frames, (*flags & kAudioUnitRenderAction_OutputIsSilence) != 0};- atomic_store(&sg_callCount, n + 1);+ int which = (int)(intptr_t)refCon;+ unsigned n = atomic_load(&sg_callCount[which]);+ sg_calls[which][n % kProbeCalls] = (ProbeCall){(float)(left / frames), (float)(right / frames), frames, (*flags & kAudioUnitRenderAction_OutputIsSilence) != 0};+ atomic_store(&sg_callCount[which], n + 1);return noErr;}-// The level of the last `calls` renders, in dB RMS, per channel.-static void level(unsigned calls, double *left, double *right, unsigned *frames, unsigned *silentCalls) {- unsigned n = atomic_load(&sg_callCount);+// The level of output `which`'s last `calls` renders, in dB RMS, per channel.+static void levelOf(int which, unsigned calls, double *left, double *right, unsigned *frames, unsigned *silentCalls) {+ unsigned n = atomic_load(&sg_callCount[which]);double l = 0, r = 0;unsigned count = 0;*frames = 0;*silentCalls = 0;for (unsigned i = 0; i < calls && i < n && i < kProbeCalls; i++) {- ProbeCall call = sg_calls[(n - 1 - i) % kProbeCalls];+ ProbeCall call = sg_calls[which][(n - 1 - i) % kProbeCalls];l += call.left;r += call.right;*frames = call.frames;@@ -80,12 +91,16 @@ static void level(unsigned calls, double *left, double *right, unsigned *frames,*right = count ? 10 * log10(r / count + 1e-20) : -200;}+static void level(unsigned calls, double *left, double *right, unsigned *frames, unsigned *silentCalls) {+ levelOf(0, calls, left, right, frames, silentCalls);+}+static int sg_failures;-static void report(NSString *what, double wantLeft, double wantRight) {+static void reportOutput(int which, NSString *what, double wantLeft, double wantRight) {double left, right;unsigned frames, silent;- level(8, &left, &right, &frames, &silent);+ levelOf(which, 8, &left, &right, &frames, &silent);BOOL ok = (isnan(wantLeft) || fabs(left - wantLeft) < 0.6) && (isnan(wantRight) || fabs(right - wantRight) < 0.6);if (!ok) sg_failures++;NSLog(@"[harness] %@ %-44@ left %6.1f dB, right %6.1f dB (want %@, %@), slices of %u, %u silent; status \"%@\"", ok ? @" ok " : @"FAILED",@@ -93,6 +108,10 @@ static void report(NSString *what, double wantLeft, double wantRight) {isnan(wantRight) ? @"any" : [NSString stringWithFormat:@"%.1f", wantRight], frames, silent, SGDSPStatus());}+static void report(NSString *what, double wantLeft, double wantRight) {+ reportOutput(0, what, wantLeft, wantRight);+}+#pragma mark - the chainstatic AudioUnit make(OSType type, OSType subType) {@@ -112,6 +131,7 @@ static void check(OSStatus status, const char *what) {@implementation SGDSPHarnessDelegate {AudioUnit _converter, _mixer, _output;+ AudioUnit _secondConverter, _secondMixer, _secondOutput;}// Spotify's way: float, one buffer per channel, converter -> mixer -> RemoteIO, slices of 4096.@@ -136,10 +156,34 @@ static void check(OSStatus status, const char *what) {for (int i = 0; i < 3; i++) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &slice, sizeof slice), "slice");for (int i = 0; i < 3; i++) check(AudioUnitInitialize(units[i]), "initialize");check(AudioOutputUnitStart(_output), "start");- check(AudioUnitAddRenderNotify(_output, probe, NULL), "probe");+ check(AudioUnitAddRenderNotify(_output, probe, (void *)0), "probe");[self logScopes];}+// A second chain, Spotify's way at `rate`, started beside the first, the way Spotify runs a chain per sample+// rate; its own probe is output 1's.+- (void)startSecondChainAt:(double)rate {+ _secondConverter = make(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter);+ _secondMixer = make(kAudioUnitType_Mixer, kAudioUnitSubType_MultiChannelMixer);+ _secondOutput = make(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO);+ AURenderCallbackStruct callback = {generate, NULL};+ check(AudioUnitSetProperty(_secondConverter, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback), "callback");+ AudioStreamBasicDescription format = {rate, kAudioFormatLinearPCM, kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved, 4, 1, 4, 2, 32, 0};+ AudioUnit units[] = {_secondConverter, _secondMixer, _secondOutput};+ for (int i = 0; i < 3; i++) {+ if (i < 2) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, sizeof format), "format out");+ check(AudioUnitSetProperty(units[i], kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof format), "format in");+ }+ AudioUnitConnection toMixer = {_secondConverter, 0, 0}, toOutput = {_secondMixer, 0, 0};+ check(AudioUnitSetProperty(_secondMixer, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toMixer, sizeof toMixer), "connect mixer");+ check(AudioUnitSetProperty(_secondOutput, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toOutput, sizeof toOutput), "connect output");+ UInt32 slice = 4096;+ for (int i = 0; i < 3; i++) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &slice, sizeof slice), "slice");+ for (int i = 0; i < 3; i++) check(AudioUnitInitialize(units[i]), "initialize");+ check(AudioOutputUnitStart(_secondOutput), "start");+ check(AudioUnitAddRenderNotify(_secondOutput, probe, (void *)1), "probe");+}+// What the client format is and what the notify gets: the output scope, the hardware's.- (void)logScopes {AudioStreamBasicDescription client = {0}, hardware = {0};@@ -156,7 +200,7 @@ static void check(OSStatus status, const char *what) {// still gets the output side's float, now with the engine following the rate change.- (void)startInt16ChainAt:(double)rate {AudioOutputUnitStop(_output);- AudioUnitRemoveRenderNotify(_output, probe, NULL);+ AudioUnitRemoveRenderNotify(_output, probe, (void *)0);AudioUnit old[] = {_output, _mixer, _converter};for (int i = 0; i < 3; i++) {if (!old[i]) continue;@@ -179,7 +223,7 @@ static void check(OSStatus status, const char *what) {check(AudioUnitInitialize(_converter), "initialize converter");check(AudioUnitInitialize(_output), "initialize output");check(AudioOutputUnitStart(_output), "start");- check(AudioUnitAddRenderNotify(_output, probe, NULL), "probe");+ check(AudioUnitAddRenderNotify(_output, probe, (void *)0), "probe");[self logScopes];}@@ -227,14 +271,23 @@ static void check(OSStatus status, const char *what) {SGDSPSetNumber(SGKeyDSPPostGain, 0);SGDSPSetSwitch(SGKeyDSPLiveprog, YES);}, @(nothing), @(sine)],+ // Two outputs at once: the effects follow the one Spotify started last, and the other plays as it is.+ @[@"a 44.1 kHz float chain started beside it", ^{ [self startSecondChainAt:44100]; }, @(sine), @(nothing), @(nothing), @(sine)],+ @[@"44.1 kHz chain stopped: back on the 16-bit one", ^{+ check(AudioOutputUnitStop(self->_secondOutput), "stop");+ // The effects' notify went back on after the probe; the probe goes after it again, to read what it left.+ AudioUnitRemoveRenderNotify(self->_output, probe, (void *)0);+ check(AudioUnitAddRenderNotify(self->_output, probe, (void *)0), "probe");+ }, @(nothing), @(sine)],@[@"master off again", ^{ SGDSPSetSwitch(SGKeyDSP, NO); }, @(sine), @(nothing)],];__block NSString *label = nil;- __block double wantLeft = 0, wantRight = 0;+ __block double wantLeft = 0, wantRight = 0, wantSecondLeft = NAN, wantSecondRight = NAN;double step = 2.5, at = 1;for (NSArray *entry in script) {[self after:at do:^{if (label) report(label, wantLeft, wantRight);+ if (label && !isnan(wantSecondLeft)) reportOutput(1, [label stringByAppendingString:@" (2nd)"], wantSecondLeft, wantSecondRight);if ([label hasPrefix:@"the source goes silent"]) {// The tail: the level over the renders since the source stopped, loud at first, then less.double left, right;@@ -250,6 +303,8 @@ static void check(OSStatus status, const char *what) {label = entry[0];wantLeft = [entry[2] doubleValue];wantRight = [entry[3] doubleValue];+ wantSecondLeft = entry.count > 5 ? [entry[4] doubleValue] : NAN;+ wantSecondRight = entry.count > 5 ? [entry[5] doubleValue] : NAN;((void (^)(void))entry[1])();}];if ([entry[0] hasPrefix:@"the source goes silent"]) {diff --git a/harness/haptics/build-sim.sh b/harness/haptics/build-sim.shindex 5f377c39..d5781d28 100755--- a/harness/haptics/build-sim.sh+++ b/harness/haptics/build-sim.sh@@ -22,10 +22,12 @@ firm -rf "$OUT"mkdir -p "$OUT/gen" "$OUT/HapticsHarness.app""$THEOS/bin/logos.pl" -c generator=internal "$HAPTICS/MusicHaptics.x" > "$OUT/gen/MusicHaptics.m"+# Shared/Player keeps Spotify's outputs apart and tells Music Haptics which is the music's.+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/Player/SpeedPitch.x" > "$OUT/gen/SpeedPitch.m"SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O1 -isysroot "$SDK" -Wno-deprecated-declarations \- $EXTRA -I"$SRC" -I"$SRC/Shared/Haptics" -Isim \- sim/main.m sim/fakehaptics.m ../scene.m "$OUT/gen/MusicHaptics.m" "$HAPTICS/SGMusicAnalyzer.m" $SETTINGS \+ $EXTRA -I"$SRC" -I"$SRC/Shared/Haptics" -I"$SRC/Shared/Player" -Isim \+ sim/main.m sim/fakehaptics.m ../scene.m "$OUT/gen/MusicHaptics.m" "$OUT/gen/SpeedPitch.m" "$SRC/Shared/Player/SGTimePitch.m" "$HAPTICS/SGMusicAnalyzer.m" $SETTINGS \"$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$SRC/Core/SGUIMode.m" "$SRC/Core/SGViewTree.m" "$SRC/Core/SGFlagForce.m" \-framework UIKit -framework QuartzCore -framework CoreGraphics -framework AudioToolbox -framework AVFoundation -framework Foundation \-o "$OUT/HapticsHarness.app/HapticsHarness"diff --git a/harness/speed/README.md b/harness/speed/README.mdindex 14d14378..e1453959 100644--- a/harness/speed/README.md+++ b/harness/speed/README.md@@ -15,8 +15,21 @@ logging how fast the converter's callback (the decoder) was drained and how farfrom the content played. 2026-09-18: drained 1.00x, 1.50x, 1.50x, 0.75x, 1.00x; position within 12 ms.`rate` sets the output's input side to 48 kHz while it runs, halfway through the 1.5x step, with no new-`AudioOutputUnitStart`. The mod's format listener reads the new format and makes the chain's unit again-(`a unit in the chain for 48000 Hz, 2 channels`); until then a unit made for another rate passes the-sound as it is. 2026-10-05: the unit was made again at 48 kHz at once, with 0 underruns. The drain-figures after the change read about 1.09 times the speed, because the harness's mixer stays at 44.1 kHz-and the output now takes 48 kHz from it.+`AudioOutputUnitStart`, while the mixer stays at 44.1 kHz. The mod's format listener sees the mixer and the+output disagree and gives Spotify's own connection back (`given Spotify's own connection back`), which sets the+output's input to the mixer's 44.1 kHz again; the formats agree, and the callback takes over again. 2026-10-06:+drained 1.00x, 1.50x, 1.50x, 0.75x, 1.00x through the change. Before, the callback pulled the 44.1 kHz mixer+for the 48 kHz output, and the drain read 1.09x.++`two` runs Spotify's chain twice at once, 44.1 and 48 kHz, the way Spotify runs a chain per sample rate when a+local file has another rate than the stream before it. Each chain's drain is measured in seconds of its own+rate for each second its output played (the simulator's output stalls now and then), and each step prints+PASS or FAIL: both at 1.00x side by side; 1.5x on the chain started last only; its stop moving the 1.5x to the+other and its start bringing it back; a third unit fed by a render callback of its own (voice search's kind)+started without taking it; a silent decoder giving it up to the chain with sound within 1.5 s, and+keeping it there when the sound comes back; a disposed mixer, then a disposed running output, with nothing else+changed. 2026-10-06, iOS 27.0 simulator: all PASS. The same run on the code before this record of outputs:+the 48 kHz mixer drained 1.92x with both chains started (both outputs pulled it), 2.88x at 1.5x, and the+44.1 kHz chain not at all, then silence once the 48 kHz one stopped.++ xcrun simctl launch --console-pty <udid> com.vojta.speedharness twodiff --git a/harness/speed/main.m b/harness/speed/main.mindex 230a02e8..c0cc506c 100644--- a/harness/speed/main.m+++ b/harness/speed/main.m@@ -7,8 +7,14 @@// THEOS=$HOME/theos ./build.sh && xcrun simctl install booted build/SpeedHarness.app// xcrun simctl launch --console-pty booted com.vojta.speedharness [rate]//-// `rate` hands the running output a 48 kHz format halfway through the 1.5x step, with no new start: the-// mod's format listener must make its unit again for 48 kHz (`a unit in the chain for 48000 Hz`).+// `rate` hands the running output a 48 kHz format halfway through the 1.5x step, with no new start, while its+// mixer stays at 44.1 kHz: the mod's format listener gives Spotify's own connection back rather than play the+// mixer fast through its callback.+//+// `two` runs a second chain at 48 kHz beside the first at 44.1, both started, the way Spotify runs a chain per+// sample rate, and checks that each decoder is drained at its own rate and only the music's output (the one+// started last, or the one with sound) takes the speed, through a stop, a start, a silent decoder, a disposed+// mixer and a disposed output. Each check prints PASS or FAIL.#import <UIKit/UIKit.h>#import <AudioToolbox/AudioToolbox.h>#import <AVFoundation/AVFoundation.h>@@ -22,6 +28,19 @@ BOOL SGPlayerSpeedAllowed(void);static const double kRate = 44100;static atomic_uint_fast64_t sg_decoded;+AudioUnit SGPlayerMusicOutput(void);++// A chain of its own, for `two`: its decoder's count, and whether it hands over silence.+typedef struct {+ double rate;+ atomic_uint_fast64_t decoded;+ atomic_bool mute;+ AudioUnit converter, mixer, output;+ atomic_uint_fast64_t played; // frames its output rendered, at the hardware's rate+ double hardwareRate;+ uint64_t lastDecoded, lastPlayed;+} Chain;+// Spotify's player state as far as -position goes (disassembly of -[SPTPlayerState position]).@interface SPTPlayerState : NSObject@property (nonatomic) double positionAsOfTimestamp;@@ -47,6 +66,33 @@ static OSStatus decoder(void *refCon, AudioUnitRenderActionFlags *flags, const Areturn noErr;}+static OSStatus chainDecoder(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,+ UInt32 frames, AudioBufferList *data) {+ Chain *chain = refCon;+ uint64_t start = atomic_fetch_add(&chain->decoded, frames);+ BOOL mute = atomic_load(&chain->mute);+ for (UInt32 i = 0; i < frames; i++) {+ float value = mute ? 0 : 0.05f * sinf(2 * M_PI * 440 * (start + i) / chain->rate);+ for (UInt32 b = 0; b < data->mNumberBuffers; b++) ((float *)data->mBuffers[b].mData)[i] = value;+ }+ return noErr;+}++static OSStatus counted(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,+ UInt32 frames, AudioBufferList *data) {+ Chain *chain = refCon;+ if ((*flags & kAudioUnitRenderAction_PostRender) && bus == 0) atomic_fetch_add(&chain->played, frames);+ return noErr;+}++// Voice search's kind of unit: Spotify's own callback, silence here.+static OSStatus silentInput(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,+ UInt32 frames, AudioBufferList *data) {+ for (UInt32 b = 0; b < data->mNumberBuffers; b++) memset(data->mBuffers[b].mData, 0, data->mBuffers[b].mDataByteSize);+ *flags |= kAudioUnitRenderAction_OutputIsSilence;+ return noErr;+}+static AudioUnit make(OSType type, OSType subType) {AudioComponentDescription description = {type, subType, kAudioUnitManufacturer_Apple, 0, 0};AudioUnit unit = NULL;@@ -101,6 +147,58 @@ static void check(OSStatus status, const char *what) {NSLog(@"[harness] output's input set to 48000 Hz while running: status %d", (int)status);}+// Spotify's chain at `rate`, wired and started the way AudioUnitDriver2 does it.+static void startChain(Chain *chain) {+ chain->converter = make(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter);+ chain->mixer = make(kAudioUnitType_Mixer, kAudioUnitSubType_MultiChannelMixer);+ chain->output = make(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO);+ AURenderCallbackStruct callback = {chainDecoder, chain};+ check(AudioUnitSetProperty(chain->converter, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback), "callback");+ AudioStreamBasicDescription format = {chain->rate, kAudioFormatLinearPCM, kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved, 4, 1, 4, 2, 32, 0};+ AudioUnit units[] = {chain->converter, chain->mixer, chain->output};+ for (int i = 0; i < 3; i++) {+ if (i < 2) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof format), "format in");+ if (i < 2) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, sizeof format), "format out");+ }+ check(AudioUnitSetProperty(chain->output, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof format), "output in");+ AudioUnitConnection toMixer = {chain->converter, 0, 0}, toOutput = {chain->mixer, 0, 0};+ check(AudioUnitSetProperty(chain->mixer, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toMixer, sizeof toMixer), "connect mixer");+ check(AudioUnitSetProperty(chain->output, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toOutput, sizeof toOutput), "connect output");+ UInt32 slice = 4096;+ for (int i = 0; i < 3; i++) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &slice, sizeof slice), "slice");+ for (int i = 0; i < 3; i++) check(AudioUnitInitialize(units[i]), "initialize");+ AudioStreamBasicDescription hardware = {0};+ UInt32 size = sizeof hardware;+ check(AudioUnitGetProperty(chain->output, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &hardware, &size), "hardware format");+ chain->hardwareRate = hardware.mSampleRate;+ check(AudioUnitAddRenderNotify(chain->output, counted, chain), "count");+ check(AudioOutputUnitStart(chain->output), "start");+}++static Chain sg_a = {.rate = 44100}, sg_b = {.rate = 48000};+static int sg_failures;++// Each chain's decoder drained since the last call, in seconds of its own rate for each second its output+// played (the simulator's output stalls now and then, so the wall clock is no measure), against what is+// expected; 0 for a chain that should not be drained at all, or whose output does not play.+static void expect(NSString *what, double wantA, double wantB) {+ Chain *chains[] = {&sg_a, &sg_b};+ double want[] = {wantA, wantB}, got[2];+ for (int i = 0; i < 2; i++) {+ uint64_t decoded = atomic_load(&chains[i]->decoded), played = atomic_load(&chains[i]->played);+ double playedSeconds = chains[i]->hardwareRate > 0 ? (played - chains[i]->lastPlayed) / chains[i]->hardwareRate : 0;+ got[i] = playedSeconds > 0.5 ? (decoded - chains[i]->lastDecoded) / chains[i]->rate / playedSeconds : 0;+ chains[i]->lastDecoded = decoded;+ chains[i]->lastPlayed = played;+ }+ if (wantA < 0) return;+ BOOL pass = fabs(got[0] - wantA) < 0.06 && fabs(got[1] - wantB) < 0.06;+ if (!pass) sg_failures++;+ AudioUnit musicUnit = SGPlayerMusicOutput();+ NSLog(@"[harness] %@ %-44@ 44.1 kHz chain drained %.2fx (want %.2f), 48 kHz chain %.2fx (want %.2f); the processors on %@", pass ? @"PASS" : @"FAIL",+ what, got[0], want[0], got[1], want[1], musicUnit == sg_a.output ? @"44.1" : musicUnit == sg_b.output ? @"48" : @"neither");+}+- (void)report:(NSString *)what {NSTimeInterval now = CACurrentMediaTime();uint64_t decoded = atomic_load(&sg_decoded);@@ -127,6 +225,10 @@ static void check(OSStatus status, const char *what) {self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];self.window.rootViewController = [UIViewController new];[self.window makeKeyAndVisible];+ if ([NSProcessInfo.processInfo.arguments containsObject:@"two"]) {+ [self runTwo];+ return YES;+ }[self startChain];NSLog(@"[harness] speed allowed: %d", SGPlayerSpeedAllowed());[self after:1 do:^{ [self playerReports]; self->_lastDecoded = atomic_load(&sg_decoded); self->_lastAt = CACurrentMediaTime(); }];@@ -157,6 +259,59 @@ static void check(OSStatus status, const char *what) {return YES;}+// Two chains at once. Every step is measured over 2 s, from half a second after the change it makes; a silent+// output gives the processors up within 1.5 s, so that step waits 2 s first.+- (void)runTwo {+ [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryPlayback error:nil];+ [AVAudioSession.sharedInstance setActive:YES error:nil];+ startChain(&sg_a);+ __block double at = 0.5;+ __block double settle = 0.5;+ void (^step)(NSString *, double, double, void (^)(void)) = ^(NSString *what, double wantA, double wantB, void (^change)(void)) {+ [self after:at do:^{+ if (change) change();+ }];+ [self after:at + settle do:^{+ expect(@"(settling)", -1, -1);+ }];+ [self after:at + settle + 2 do:^{+ expect(what, wantA, wantB);+ }];+ at += settle + 2;+ settle = 0.5;+ };+ // The second chain is the music's once started; the first plays on at its own rate.+ step(@"one chain, normal", 1, 0, nil);+ step(@"48 kHz chain started too, normal", 1, 1, ^{ startChain(&sg_b); });+ step(@"1.5x: only the 48 kHz chain", 1, 1.5, ^{ SGSetPlayerSpeed(1.5); });+ step(@"48 kHz stopped: 1.5x moves to 44.1", 1.5, 0, ^{ check(AudioOutputUnitStop(sg_b.output), "stop"); });+ step(@"48 kHz started again: back to it", 1, 1.5, ^{ check(AudioOutputUnitStart(sg_b.output), "start"); });+ // A unit Spotify feeds through a render callback of its own (voice search) never takes the processors from a+ // connected one.+ step(@"a callback-fed unit started: 1.5x stays", 1, 1.5, ^{+ AudioUnit voice = make(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO);+ AURenderCallbackStruct callback = {silentInput, NULL};+ check(AudioUnitSetProperty(voice, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback), "voice callback");+ check(AudioUnitInitialize(voice), "voice initialize");+ check(AudioOutputUnitStart(voice), "voice start");+ });+ settle = 2;+ step(@"48 kHz silent for a while: 1.5x to 44.1", 1.5, 1, ^{ atomic_store(&sg_b.mute, true); });+ step(@"48 kHz sound again: stays on 44.1", 1.5, 1, ^{ atomic_store(&sg_b.mute, false); });+ step(@"48 kHz mixer disposed: 44.1 unchanged", 1.5, 0, ^{ check(AudioComponentInstanceDispose(sg_b.mixer), "dispose mixer"); });+ step(@"44.1 stopped, 48 output disposed", 0, 0, ^{+ check(AudioOutputUnitStop(sg_a.output), "stop");+ check(AudioComponentInstanceDispose(sg_b.output), "dispose output");+ });+ settle = 1; // the simulator's IO takes a moment to come back once nothing runs+ step(@"44.1 started again, still 1.5x", 1.5, 0, ^{ check(AudioOutputUnitStart(sg_a.output), "start"); });+ step(@"back to normal", 1, 0, ^{ SGSetPlayerSpeed(1); });+ [self after:at + 0.5 do:^{+ NSLog(@"[harness] two chains: %d failures", sg_failures);+ exit(sg_failures ? 1 : 0);+ }];+}+@end__attribute__((constructor(101))) static void sgr_harnessDefaults(void) {diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffects.x b/tweak/Sources/Shared/AudioEffects/AudioEffects.xindex c762a393..89a5a8ea 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffects.x+++ b/tweak/Sources/Shared/AudioEffects/AudioEffects.x@@ -3,11 +3,12 @@//// Spotify plays through Core Audio units of its own (AudioUnitDriver2 in the binary: converter, EQ, mixer// and a RemoteIO output unit, started with AudioOutputUnitStart), with no Objective-C method between it and-// the unit. So Spotify's import of AudioOutputUnitStart is rebound (Core/SGRebind.h; Music Haptics and Speed-// and pitch rebind it too, and each replacement calls on what the slot held), and every RemoteIO unit it-// starts gets a render notify. After each render the notify reads the buffer bound for the speaker into-// float lanes, runs the engine over them and writes them back, in place: the way the first version of Pitch-// worked on the phone. Speed and pitch feeds the unit's input, so its sound reaches the notify changed.+// the unit, and it can run two such chains at once, one per sample rate. Shared/Player keeps them apart and+// names the music's output (SGPlayerMusicOutput); that one gets a render notify. After each render the notify+// reads the buffer bound for the speaker into float lanes, runs the engine over them and writes them back, in+// place: the way the first version of Pitch worked on the phone. A notify stays on a unit that was the music's+// once and does nothing there, so one engine never runs on two render threads. Speed and pitch feeds the+// unit's input, so its sound reaches the notify changed.//// The engine is made the first time the output starts with the master switch on, at the output's rate,// and lives as long as Spotify: the render thread may be holding it at any time. With the switch off the@@ -25,7 +26,7 @@#import <os/lock.h>#import <stdatomic.h>#import "Core/SGCore.h"-#import "Core/SGRebind.h"+#import "Shared/Player/SpeedPitch.h"#import "AudioEffects.h"#import "AudioEffectsApply.h"#import "SGDSPEngine.h"@@ -50,6 +51,7 @@ typedef enum { SGOutputUnseen, SGOutputPCM, SGOutputUnsupported } SGOutputState;static _Atomic(SGDSPEngine *) sg_engine; // made once on the queue, never freedstatic atomic_bool sg_running; // the switch on and the engine set up for the outputstatic atomic_int sg_outputState;+static BOOL sg_reachable; // Shared/Player reaches Spotify's output// The format of the buffers the notify gets: the rate, and the layout packed into one word so the render// thread never reads half of a change (flags in the low 32 bits, then channels, then bytes per sample).static atomic_uint_fast64_t sg_rateBits;@@ -164,9 +166,11 @@ static void processBuffer(SGDSPEngine *engine, AudioUnitRenderActionFlags *flagsif (loud) *flags &= ~kAudioUnitRenderAction_OutputIsSilence;}+// `refCon` is the unit; only the music's output is processed.static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,UInt32 frames, AudioBufferList *data) {if (!(*flags & kAudioUnitRenderAction_PostRender) || bus != 0 || !data || !data->mNumberBuffers || !frames) return noErr;+ if (refCon != SGPlayerMusicOutput()) return noErr;if (!atomic_load_explicit(&sg_running, memory_order_acquire)) return noErr;SGDSPEngine *engine = atomic_load_explicit(&sg_engine, memory_order_acquire);// A new rate is being set up on the queue: until then the sound passes as it is.@@ -182,12 +186,6 @@ static NSString *fourCC(UInt32 code) {return @(text);}-static BOOL isRemoteIO(AudioUnit unit) {- AudioComponentDescription description = {0};- if (!unit || AudioComponentGetDescription(AudioComponentInstanceGetComponent(unit), &description) != noErr) return NO;- return description.componentType == kAudioUnitType_Output && description.componentSubType == kAudioUnitSubType_RemoteIO;-}-static NSString *formatText(AudioStreamBasicDescription format) {if (format.mFormatID != kAudioFormatLinearPCM) return [NSString stringWithFormat:@"'%@'", fourCC(format.mFormatID)];return [NSString stringWithFormat:@"%.0f Hz, %u channels, %u-bit %@%@", format.mSampleRate, (unsigned)format.mChannelsPerFrame,@@ -234,30 +232,19 @@ static BOOL readFormat(AudioUnit unit) {return YES;}-// The hardware's format changing under a running unit (a route to a device at another rate).-static void formatChanged(void *refCon, AudioUnit unit, AudioUnitPropertyID property, AudioUnitScope scope, AudioUnitElement element) {- if (property == kAudioUnitProperty_StreamFormat && scope == kAudioUnitScope_Output && element == 0) readFormat(unit);-}-+// The music's output started, changed or changed format (Shared/Player): its format read, the notify on it.static void listenTo(AudioUnit unit) {- AudioUnitRemoveRenderNotify(unit, rendered, NULL);- AudioUnitRemovePropertyListenerWithUserData(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);- AudioUnitAddPropertyListener(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);+ if (!unit) return;+ AudioUnitRemoveRenderNotify(unit, rendered, unit);if (!readFormat(unit)) return;- // The sound held from before the output stopped would play first; the stream starts over instead.+ // The sound held from before the output stopped, or from another output, would play first; the stream+ // starts over instead.SGDSPEngine *engine = atomic_load(&sg_engine);if (engine) SGDSPEngineRestart(engine);- OSStatus status = AudioUnitAddRenderNotify(unit, rendered, NULL);+ OSStatus status = AudioUnitAddRenderNotify(unit, rendered, unit);if (status != noErr) SGLog(@"dsp: the render notify could not be added (%d)", (int)status);}-static OSStatus (*sg_startOutput)(AudioUnit unit);--static OSStatus startOutput(AudioUnit unit) {- if (isRemoteIO(unit)) listenTo(unit);- return sg_startOutput(unit);-}-#pragma mark - errors// An effect's name in the log, by its switch key.@@ -558,7 +545,7 @@ NSString *SGDSPStatus(void) {if (!SGDSPSwitch(SGKeyDSP)) return @"Off";if (atomic_load(&sg_outputState) == SGOutputUnsupported) return @"Spotify's output is in a format the engine does not take";SGDSPEngine *engine = atomic_load(&sg_engine);- if (!sg_startOutput) return @"Unavailable: Spotify's output could not be reached";+ if (!sg_reachable) return @"Unavailable: Spotify's output could not be reached";if (!engine || !atomic_load(&sg_running)) return @"Waiting for Spotify to play";double rate = SGDSPEngineSampleRate(engine);double load = SGDSPEngineReadStats(engine, false).load;@@ -580,9 +567,9 @@ void SGDSPCompanderResponse(NSArray<NSNumber *> *gains, NSInteger count, double}%ctor {- if (!SGRebindImport("AudioOutputUnitStart", startOutput, (void **)&sg_startOutput) || !sg_startOutput) {- sg_startOutput = NULL;- SGLog(@"dsp: Spotify does not import AudioOutputUnitStart, the effects cannot reach its sound");+ sg_reachable = SGPlayerWatchMusicOutput(listenTo);+ if (!sg_reachable) {+ SGLog(@"dsp: Spotify's output cannot be reached, the effects cannot reach its sound");return;}SGLog(@"dsp: listening for Spotify's output unit (%@)", SGDSPSwitch(SGKeyDSP) ? @"on" : @"off");diff --git a/tweak/Sources/Shared/Haptics/MusicHaptics.x b/tweak/Sources/Shared/Haptics/MusicHaptics.xindex 10867374..ff36f973 100644--- a/tweak/Sources/Shared/Haptics/MusicHaptics.x+++ b/tweak/Sources/Shared/Haptics/MusicHaptics.x@@ -3,13 +3,14 @@//// Spotify plays through Core Audio units of its own (AudioUnitDriver2 in the binary: converter, EQ, mixer// and a RemoteIO output unit, started with AudioOutputUnitStart(_outputUnit)), with no Objective-C-// method between it and the unit. So Spotify's import of AudioOutputUnitStart is rebound-// (Core/SGRebind.h), and every RemoteIO unit it starts gets a render notify: after each render, the-// buffer bound for the speaker is mixed to mono and handed to the analyzer (SGMusicAnalyzer.h) on-// the render thread, which puts what it hears into a ring of events. That buffer is in the unit's output-// format, the hardware's, not the one Spotify hands the unit (in the simulator 48 kHz float with a buffer-// per channel, whatever the client: harness/audio-effects/sim, harness/haptics/sim), so the analyzer runs at-// the hardware's rate, and a listener on the format follows it to a new one. The render timestamp says when+// method between it and the unit, and it can run two such chains at once, one per sample rate. Shared/Player+// keeps them apart and names the music's output (SGPlayerMusicOutput), and that one gets a render notify:+// after each render, the buffer bound for the speaker is mixed to mono and handed to the analyzer+// (SGMusicAnalyzer.h) on the render thread, which puts what it hears into a ring of events. A notify stays on+// a unit that was the music's once and does nothing there, so the one analyzer never hears two outputs. That+// buffer is in the unit's output format, the hardware's, not the one Spotify hands the unit (in the simulator+// 48 kHz float with a buffer per channel, whatever the client: harness/audio-effects/sim, harness/haptics/sim),+// so the analyzer runs at the hardware's rate, and Shared/Player says when it changes. The render timestamp says when// that buffer reaches the output; AVAudioSession's output latency (large over Bluetooth) is added, so// a tap lands when its drum is heard. A thread of this file's own takes the events off the ring and// schedules them with Core Haptics at those times: each hit a transient, the rumble one looping@@ -39,7 +40,7 @@#import <pthread.h>#import <stdatomic.h>#import "Core/SGCore.h"-#import "Core/SGRebind.h"+#import "Shared/Player/SpeedPitch.h"#import "Haptics.h"#import "SGMusicAnalyzer.h"@@ -123,11 +124,11 @@ static inline float sampleAt(const void *data, UInt32 index, UInt32 bytes, BOOL// The hardware's format is float with a buffer per channel, but it is read rather than assumed (readFormat),// and buffers not laid out the way it says are left alone rather than read as noise: the format read at the-// start can be a moment old.+// start can be a moment old. `refCon` is the unit; only the music's output is heard.static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,UInt32 frames, AudioBufferList *data) {if (!(*flags & kAudioUnitRenderAction_PostRender) || bus != 0 || !data || !data->mNumberBuffers || !frames) return noErr;- if (!atomic_load_explicit(&sg_listening, memory_order_relaxed)) return noErr;+ if (!atomic_load_explicit(&sg_listening, memory_order_relaxed) || refCon != SGPlayerMusicOutput()) return noErr;if (*flags & kAudioUnitRenderAction_OutputIsSilence) return noErr;uint64_t layout = atomic_load_explicit(&sg_layout, memory_order_relaxed);@@ -179,8 +180,6 @@ static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const#pragma mark - the output unit-static OSStatus (*sg_startOutput)(AudioUnit unit);-static NSString *fourCC(UInt32 code) {char text[5] = {(char)(code >> 24), (char)(code >> 16), (char)(code >> 8), (char)code, 0};return @(text);@@ -224,32 +223,17 @@ static void readFormat(AudioUnit unit) {atomic_store(&sg_layout, (uint64_t)format.mFormatFlags | (uint64_t)(format.mChannelsPerFrame & 0xffff) << 32 | (uint64_t)bytes << 48);}-// The hardware's format changing under a running unit (a route to a device at another rate).-static void formatChanged(void *refCon, AudioUnit unit, AudioUnitPropertyID property, AudioUnitScope scope, AudioUnitElement element) {- if (property == kAudioUnitProperty_StreamFormat && scope == kAudioUnitScope_Output && element == 0) readFormat(unit);-}-+// The music's output started, changed or changed format (Shared/Player): its format read, the notify on it,+// and the analyzer started over, since what it held came from before.static void listenTo(AudioUnit unit) {- AudioComponentDescription description = {0};- if (AudioComponentGetDescription(AudioComponentInstanceGetComponent(unit), &description) != noErr) return;- if (description.componentType != kAudioUnitType_Output || description.componentSubType != kAudioUnitSubType_RemoteIO) {- static int logged;- if (logged++ < 8) SGLog(@"music haptics: a started unit is not RemoteIO ('%@' '%@'), not listened to", fourCC(description.componentType), fourCC(description.componentSubType));- return;- }- AudioUnitRemoveRenderNotify(unit, rendered, NULL);- AudioUnitRemovePropertyListenerWithUserData(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);- AudioUnitAddPropertyListener(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);+ if (!unit) return;+ AudioUnitRemoveRenderNotify(unit, rendered, unit);readFormat(unit);- OSStatus status = AudioUnitAddRenderNotify(unit, rendered, NULL);+ atomic_fetch_add(&sg_generation, 1);+ OSStatus status = AudioUnitAddRenderNotify(unit, rendered, unit);if (status != noErr) SGLog(@"music haptics: the render notify could not be added (%d)", (int)status);}-static OSStatus startOutput(AudioUnit unit) {- if (unit) listenTo(unit);- return sg_startOutput(unit);-}-#pragma mark - the player threadstatic CHHapticEngine *sg_engine;@@ -591,8 +575,8 @@ void SGMusicHapticsWatchTaps(void (^watcher)(float intensity)) {mach_timebase_info_data_t timebase;mach_timebase_info(&timebase);sg_secondsPerTick = (double)timebase.numer / timebase.denom / 1e9;- if (!SGRebindImport("AudioOutputUnitStart", startOutput, (void **)&sg_startOutput) || !sg_startOutput) {- SGLog(@"music haptics: Spotify does not import AudioOutputUnitStart, Music Haptics is inactive");+ if (!SGPlayerWatchMusicOutput(listenTo)) {+ SGLog(@"music haptics: Spotify's output cannot be reached, Music Haptics is inactive");return;}sg_wake = dispatch_semaphore_create(0);diff --git a/tweak/Sources/Shared/Player/SpeedPitch.h b/tweak/Sources/Shared/Player/SpeedPitch.hindex f862f55d..434cd0fc 100644--- a/tweak/Sources/Shared/Player/SpeedPitch.h+++ b/tweak/Sources/Shared/Player/SpeedPitch.h@@ -4,7 +4,8 @@//// SpeedPitchMenu.x the expandable row and its two sliders, put into Spotify's context menu, and under// the redesign the Animated artwork switch under them-// SpeedPitch.x speed and pitch done to Spotify's audio, between its mixer and its speaker unit+// SpeedPitch.x speed and pitch done to Spotify's audio, between its mixer and its speaker unit, and+// Spotify's outputs kept apart, one of them the music's (SGPlayerMusicOutput)// SGTimePitch.m Apple's time and pitch unit, pulling the mixer or working in place//// Speed and pitch last until Spotify quits; neither is stored.@@ -52,7 +53,24 @@ BOOL SGPlayerMenuAnimatedArtwork(void);void SGPlayerMenuSetAnimatedArtwork(BOOL on);// A stage between Spotify's mixer and the rest of the chain (Sing's look-ahead, Shared/Sing): it fills the// chain's buffers, pulling the mixer through `pull` as much as it likes. NULL passes the mixer straight on.-// Called on the render thread, and only while Spotify's connection is taken over (SGPlayerSpeedAllowed).+// Called on the render thread, and only on the music's output (below) while Spotify's connection to it is taken+// over (SGPlayerSpeedAllowed). The buffers are in SGPlayerMusicClientFormat's format.typedef OSStatus (*SGPlayerPull)(void *context, UInt32 frames, AudioBufferList *data);typedef OSStatus (*SGPlayerStage)(UInt32 frames, AudioBufferList *data, SGPlayerPull pull, void *context);void SGPlayerSetStage(SGPlayerStage stage);++// The music's output: of the RemoteIO units Spotify runs at once (a chain per sample rate, and voice search's),+// the one that carries every processor of its sound (speed and pitch, Sing's stage, the audio effects, Music+// Haptics), NULL until Spotify connects or starts one. Any thread; the render thread compares it with a render+// notify's unit to process the music's output alone.+AudioUnit SGPlayerMusicOutput(void);+// The format Spotify hands the music's output (its input scope, element 0), the one the stage's buffers are+// in. NO when there is no such output. Not on the render thread.+BOOL SGPlayerMusicClientFormat(AudioStreamBasicDescription *format);+// `watcher` is called with the music's output each time it changes (NULL when there is none any more), Spotify+// starts it again, or a format of it changes: the time to read its format, add a render notify to it and start+// over what was held. Called on Spotify's audio thread or a queue of Shared/Player's, under a lock a dispose+// waits for, so the unit stays alive through the call; it must not wait on the main thread. NO when+// Spotify's output cannot be reached at all. Register from a %ctor; up to four.+typedef void (*SGPlayerOutputWatcher)(AudioUnit output);+BOOL SGPlayerWatchMusicOutput(SGPlayerOutputWatcher watcher);diff --git a/tweak/Sources/Shared/Player/SpeedPitch.x b/tweak/Sources/Shared/Player/SpeedPitch.xindex 64bf4bed..1ae8f223 100644--- a/tweak/Sources/Shared/Player/SpeedPitch.x+++ b/tweak/Sources/Shared/Player/SpeedPitch.x@@ -1,4 +1,5 @@-// Speed and Pitch (SpeedPitchMenu.x draws them), both done on Spotify's audio, under either look.+// Speed and Pitch (SpeedPitchMenu.x draws them), both done on Spotify's audio, under either look, and the+// record of Spotify's outputs that every processor of its sound follows (SpeedPitch.h).//// Spotify's player takes a speed only for podcasts: for songs its restrictions refuse it (device test,// 2026-09-18: the slider read "Unavailable here"), its own music speed being a per track setting kept on@@ -7,13 +8,33 @@//// Spotify's audio (AudioUnitDriver2 in the binary) is a chain of units it wires with MakeConnection:// converter (fed by its decoder through a render callback), EQ, mixer, RemoteIO. Its import of-// AudioUnitSetProperty is rebound (Core/SGRebind.h), and the one call connecting the mixer to the RemoteIO-// unit's input is answered by a render callback of this file's instead, which pulls the mixer itself. At-// normal speed and pitch the callback passes the mixer's sound straight through. Otherwise it renders the-// time and pitch unit, which pulls the mixer for rate times the frames it hands back, so Spotify's decoder-// is drained that much faster: the song plays faster or slower, at its own pitch unless Pitch moves it.-// Switching the unit in or out skips or repeats its 93 ms, so it stays in for a moment after both return-// to normal, and a finger dragging across normal does not switch it back and forth.+// AudioUnitSetProperty is rebound (Core/SGRebind.h), and the call connecting a mixer to a RemoteIO unit's+// input is answered by a render callback of this file's instead, which pulls the mixer itself. At normal+// speed and pitch the callback passes the mixer's sound straight through. Otherwise it renders the time and+// pitch unit, which pulls the mixer for rate times the frames it hands back, so Spotify's decoder is drained+// that much faster: the song plays faster or slower, at its own pitch unless Pitch moves it. Switching the+// unit in or out skips or repeats its 93 ms, so it stays in for a moment after both return to normal, and a+// finger dragging across normal does not switch it back and forth.+//+// Spotify keeps a chain per sample rate: a local file at another rate gets a second one, and both can be+// alive and running at once. So every RemoteIO unit has its own record (Output): the mixer and bus feeding+// it, that mixer's largest slice, a sample time of its own, and its two formats. Each unit's callback pulls+// only its own mixer; one pulling another's would drain it twice as fast, and the song would speed up. The+// processors (this file's unit, Sing's stage, the audio effects, Music Haptics) are on one output only, the+// music's: the one Spotify started or connected last, since a new chain is started for the song about to+// play. A unit Spotify never connected (one it feeds with a callback of its own, such as voice search) gets+// them only when no connected one runs. And an output that has had no sound for a second gives them up to+// a connected one that has: a chain left running and fed again without a new start (going back to a+// streamed song after a local file, or the end of a crossfade) is still found. AudioOutputUnitStop and+// AudioComponentInstanceDispose are rebound too: a stopped unit gives the processors up, and a disposed one+// is forgotten, after its render in progress is over, so nothing ever pulls a disposed mixer.+//+// The callback stands in for Spotify's connection only when it can: Spotify's side of the unit float, a+// buffer per channel, 32-bit, one or two channels, and the mixer's output the same rate, layout and+// channels. Otherwise Spotify's own connection is put back and its sound passes untouched (a mixer at+// another rate than the unit would play fast or slow through the callback, where Spotify's own connection+// refuses it). This is checked when Spotify connects, starts and changes a format, and the callback takes+// over again once the formats agree.//// Spotify's clock keeps running at its own speed between the player's reports: -[SPTPlayerState position]// is positionAsOfTimestamp minus timeIntervalSinceNow times [self playbackSpeed] (disassembly,@@ -21,18 +42,19 @@// screen move with the sound. That bets the player's reported positions follow what the decoder handed// over, which is what it counts.//-// When the connection is never seen, pitch falls back to the way it first shipped: a render notify on the-// RemoteIO unit (after Music Haptics' own rebinding of AudioOutputUnitStart) runs each finished buffer-// through a unit working in place; speed is then unavailable. Those buffers are in the unit's output format,-// the hardware's, not the one Spotify hands the unit (harness/audio-effects/sim), so the fallback's unit is made-// for that one.+// When the music's output was never connected, pitch falls back to the way it first shipped: a render notify+// on the RemoteIO unit runs each finished buffer through a unit working in place; speed is then unavailable.+// Those buffers are in the unit's output format, the hardware's, not the one Spotify hands the unit+// (harness/audio-effects/sim), so the fallback's unit is made for that one.//// Speed and pitch last until Spotify quits.//-// Threading: the render callback and the notify run on the render thread and touch only atomics and the-// units; Spotify sets its properties and starts its unit on its audio thread; everything else is main-// thread.+// Threading: the render callbacks and the notify run on each unit's render thread and touch only atomics,+// their own output's record and the units. Spotify connects, starts, stops and disposes on its audio thread;+// the record changes under sg_outputsLock, there and on sg_outputsQueue (format changes, the silence check).+// A change waits for a render in progress to end; a render never waits. Everything else is main thread.#import <AudioToolbox/AudioToolbox.h>+#import <mach/mach_time.h>#import <pthread.h>#import <stdatomic.h>#import "Core/SGCore.h"@@ -43,34 +65,70 @@// The unit stays in this long after speed and pitch both came back to normal.static const double kOffAfter = 1.5;+// An output silent this long gives the processors up to a connected one that is not; one started or connected+// this recently counts as having sound.+static const double kSilentFor = 1;+// How often the outputs are checked for that while two or more run.+static const double kCheckEvery = 0.5;++enum { kMaxOutputs = 8, kMaxWatchers = 4 };#pragma mark - shared between the threadsstatic float sg_speed = 1, sg_semitones; // main threadstatic atomic_uint sg_speedBits; // sg_speed for SPTPlayerState, read on any thread-// The chain as Spotify wired it: the unit and bus feeding its RemoteIO unit (NULL until the-// connection was taken over), pulled in chunks no larger than Spotify's own maximum slice.-static _Atomic(AudioUnit) sg_source;-static UInt32 sg_sourceBus;-static atomic_uint sg_chunk = 1024;-static Float64 sg_sourceTime; // render thread only--// The unit in use and whether the render thread runs it: in the chain (pull), else in place (pitch only).-static _Atomic(SGTimePitch *) sg_pull, sg_inPlace;-static atomic_bool sg_engaged, sg_busy;-static pthread_mutex_t sg_buildLock = PTHREAD_MUTEX_INITIALIZER;--// The formats when Spotify started its output: the one it hands the RemoteIO unit, which the chain's unit-// feeds, and the unit's output side, the hardware's, which the in place fallback's notify gets.typedef struct {atomic_uint_fast64_t rateBits;atomic_uint flags, channels, bytes;} Format;-static Format sg_client, sg_hardware;+// A RemoteIO unit of Spotify's. A slot whose unit is NULL is free; slots are used again, never freed, since a+// render thread may hold one.+typedef struct {+ _Atomic(AudioUnit) unit;+ // What Spotify connected to it, NULL when nothing is; `taken` while this file's callback stands in for that+ // connection, pulling it in chunks no larger than its own largest slice.+ _Atomic(AudioUnit) source;+ UInt32 sourceBus;+ atomic_bool taken;+ atomic_uint chunk;+ Float64 sourceTime; // its render thread only+ // Spotify's side (input scope, element 0), which the callback fills, and the hardware's (output scope),+ // which render notifies get.+ Format client, hardware;+ atomic_bool running, busy;+ atomic_uint_fast64_t loudAt; // host time of its last rendered buffer with sound+ // Under sg_outputsLock: when Spotify last started or connected it, as an order and as a host time,+ // and whether its notify and listener are on.+ uint64_t order, eventAt;+ BOOL listened;+} Output;++static Output sg_outputs[kMaxOutputs];+static _Atomic(Output *) sg_music; // the output carrying the processors+static pthread_mutex_t sg_outputsLock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;+static dispatch_queue_t sg_outputsQueue;+static SGPlayerOutputWatcher sg_watchers[kMaxWatchers];+static BOOL sg_reachable; // Spotify's AudioOutputUnitStart could be rebound++// The unit in use and whether the render thread runs it: in the music's chain (pull), else in place (pitch only).+static _Atomic(SGTimePitch *) sg_pull, sg_inPlace;+static atomic_bool sg_engaged;+static pthread_mutex_t sg_buildLock = PTHREAD_MUTEX_INITIALIZER;+static _Atomic(SGPlayerStage) sg_stage;++static double sg_secondsPerTick;+static OSStatus (*sg_setProperty)(AudioUnit, AudioUnitPropertyID, AudioUnitScope, AudioUnitElement, const void *, UInt32);++static Output *music(void) {+ return atomic_load(&sg_music);+}++// Whether the music's output is fed through this file's callback.static BOOL tapped(void) {- return atomic_load(&sg_source) != NULL;+ Output *output = music();+ return output && atomic_load(&output->taken);}static double rateOf(Format *format) {@@ -93,13 +151,22 @@ static void storeFloat(atomic_uint *slot, float value) {atomic_store(slot, bits);}+static double seconds(uint64_t ticks) {+ return ticks * sg_secondsPerTick;+}+#pragma mark - the render thread: the chain-// The source's next `frames` frames into `data`, in chunks of at most sg_chunk frames, each with a sample-// time of its own, so Spotify's units never see a time twice (an AU renders a time it has seen from cache).-static OSStatus pullSource(AudioUnit source, const AudioTimeStamp *outputTime, UInt32 frames, AudioBufferList *data) {+static void silence(AudioBufferList *data) {+ for (UInt32 b = 0; b < data->mNumberBuffers; b++) if (data->mBuffers[b].mData) memset(data->mBuffers[b].mData, 0, data->mBuffers[b].mDataByteSize);+}++// The output's mixer's next `frames` frames into `data`, in chunks of at most its largest slice, each with a+// sample time of the output's own, so Spotify's units never see a time twice (an AU renders a time it has+// seen from cache).+static OSStatus pullSource(Output *output, AudioUnit source, const AudioTimeStamp *outputTime, UInt32 frames, AudioBufferList *data) {enum { kMaxBuffers = 8 };- UInt32 chunk = atomic_load_explicit(&sg_chunk, memory_order_relaxed);+ UInt32 chunk = atomic_load_explicit(&output->chunk, memory_order_relaxed);if (data->mNumberBuffers > kMaxBuffers) chunk = frames;for (UInt32 b = 0; b < data->mNumberBuffers; b++) if (!data->mBuffers[b].mData) chunk = frames;UInt32 bytesPerFrame[kMaxBuffers];@@ -118,48 +185,50 @@ static OSStatus pullSource(AudioUnit source, const AudioTimeStamp *outputTime, Utarget = &part.list;}AudioTimeStamp time = outputTime ? *outputTime : (AudioTimeStamp){0};- time.mSampleTime = sg_sourceTime;+ time.mSampleTime = output->sourceTime;time.mFlags |= kAudioTimeStampSampleTimeValid;AudioUnitRenderActionFlags flags = 0;- OSStatus status = AudioUnitRender(source, &flags, &time, sg_sourceBus, count, target);- sg_sourceTime += count;+ OSStatus status = AudioUnitRender(source, &flags, &time, output->sourceBus, count, target);+ output->sourceTime += count;if (status != noErr) return status;done += count;}return noErr;}-static _Atomic(SGPlayerStage) sg_stage;-void SGPlayerSetStage(SGPlayerStage stage) {atomic_store(&sg_stage, stage);}typedef struct {+ Output *output;AudioUnit source;const AudioTimeStamp *time;} MixerPull;static OSStatus pullMixer(void *context, UInt32 frames, AudioBufferList *data) {MixerPull *mixer = context;- return pullSource(mixer->source, mixer->time, frames, data);+ return pullSource(mixer->output, mixer->source, mixer->time, frames, data);}-// The mixer's sound, through the stage when one is set.-static OSStatus pullChain(AudioUnit source, const AudioTimeStamp *time, UInt32 frames, AudioBufferList *data) {+// The music's mixer's sound, through the stage when one is set.+static OSStatus pullChain(Output *output, AudioUnit source, const AudioTimeStamp *time, UInt32 frames, AudioBufferList *data) {SGPlayerStage stage = atomic_load_explicit(&sg_stage, memory_order_acquire);- if (!stage) return pullSource(source, time, frames, data);- MixerPull mixer = {source, time};+ if (!stage) return pullSource(output, source, time, frames, data);+ MixerPull mixer = {output, source, time};return stage(frames, data, pullMixer, &mixer);}+// The time and pitch unit's input. It renders only on the music's output, and a change of music takes the+// unit out first (disengage), so the music here is the output rendering it.static OSStatus pullForUnit(void *context, UInt32 frames, AudioBufferList *data) {- AudioUnit source = atomic_load(&sg_source);+ Output *output = music();+ AudioUnit source = output ? atomic_load(&output->source) : NULL;if (!source) {- for (UInt32 b = 0; b < data->mNumberBuffers; b++) if (data->mBuffers[b].mData) memset(data->mBuffers[b].mData, 0, data->mBuffers[b].mDataByteSize);+ silence(data);return noErr;}- return pullChain(source, NULL, frames, data);+ return pullChain(output, source, NULL, frames, data);}static BOOL fitsUnit(const AudioBufferList *data, UInt32 frames, SGTimePitch *unit) {@@ -170,24 +239,29 @@ static BOOL fitsUnit(const AudioBufferList *data, UInt32 frames, SGTimePitch *unreturn YES;}-// The RemoteIO unit's input, in place of Spotify's connection from the mixer.+// A RemoteIO unit's input, in place of Spotify's connection from its mixer. `refCon` is its Output.static OSStatus feed(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,UInt32 frames, AudioBufferList *data) {- AudioUnit source = atomic_load(&sg_source);+ Output *output = refCon;+ atomic_store(&output->busy, true);+ AudioUnit source = atomic_load(&output->source);+ OSStatus status = noErr;if (!source) {- for (UInt32 b = 0; b < data->mNumberBuffers; b++) if (data->mBuffers[b].mData) memset(data->mBuffers[b].mData, 0, data->mBuffers[b].mDataByteSize);+ silence(data);*flags |= kAudioUnitRenderAction_OutputIsSilence;- return noErr;- }- atomic_store(&sg_busy, true);- OSStatus status = -1;- SGTimePitch *unit = atomic_load(&sg_pull);- // A unit made for another rate passes the sound as it is, until the main thread makes one for the new rate.- if (atomic_load(&sg_engaged) && unit && fitsUnit(data, frames, unit) && SGTimePitchSampleRate(unit) == rateOf(&sg_client)) {- status = SGTimePitchRender(unit, frames, data);+ } else if (output != music()) {+ // Another chain plays as Spotify made it.+ status = pullSource(output, source, timestamp, frames, data);+ } else {+ status = -1;+ SGTimePitch *unit = atomic_load(&sg_pull);+ // A unit made for another rate passes the sound as it is, until the main thread makes one for the new rate.+ if (atomic_load(&sg_engaged) && unit && fitsUnit(data, frames, unit) && SGTimePitchSampleRate(unit) == rateOf(&output->client)) {+ status = SGTimePitchRender(unit, frames, data);+ }+ if (status != noErr) status = pullChain(output, source, timestamp, frames, data);}- if (status != noErr) status = pullChain(source, timestamp, frames, data);- atomic_store(&sg_busy, false);+ atomic_store(&output->busy, false);return status;}@@ -218,9 +292,9 @@ static inline void writeSample(void *data, UInt32 index, float value, UInt32 byt}}-static void shiftInPlace(SGTimePitch *unit, AudioUnitRenderActionFlags *flags, UInt32 frames, AudioBufferList *data) {- UInt32 formatFlags = atomic_load_explicit(&sg_hardware.flags, memory_order_relaxed);- UInt32 bytes = atomic_load_explicit(&sg_hardware.bytes, memory_order_relaxed);+static void shiftInPlace(SGTimePitch *unit, Format *hardware, AudioUnitRenderActionFlags *flags, UInt32 frames, AudioBufferList *data) {+ UInt32 formatFlags = atomic_load_explicit(&hardware->flags, memory_order_relaxed);+ UInt32 bytes = atomic_load_explicit(&hardware->bytes, memory_order_relaxed);UInt32 channels = SGTimePitchChannels(unit);BOOL isFloat = (formatFlags & kAudioFormatFlagIsFloat) != 0;BOOL split = (formatFlags & kAudioFormatFlagIsNonInterleaved) != 0;@@ -254,18 +328,40 @@ static void shiftInPlace(SGTimePitch *unit, AudioUnitRenderActionFlags *flags, U*flags &= ~kAudioUnitRenderAction_OutputIsSilence;}+// Whether a buffer in `format` holds sound: float over -80 dB, so a mixer's noise floor is not taken for+// music, and in any other format anything but zeros.+static BOOL hasSound(Format *format, AudioUnitRenderActionFlags flags, const AudioBufferList *data) {+ if (flags & kAudioUnitRenderAction_OutputIsSilence) return NO;+ BOOL floats = (atomic_load_explicit(&format->flags, memory_order_relaxed) & kAudioFormatFlagIsFloat)+ && atomic_load_explicit(&format->bytes, memory_order_relaxed) == 4;+ for (UInt32 b = 0; b < data->mNumberBuffers; b++) {+ const uint32_t *words = data->mBuffers[b].mData;+ UInt32 count = words ? data->mBuffers[b].mDataByteSize / sizeof *words : 0;+ for (UInt32 i = 0; i < count; i++) {+ if (floats ? fabsf(((const float *)words)[i]) > 1e-4f : words[i] != 0) return YES;+ }+ }+ return NO;+}++// On every started output, `refCon` its Output: notes when it has sound, and shifts the pitch on the music's+// when it is not fed by the callback.static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,UInt32 frames, AudioBufferList *data) {if (!(*flags & kAudioUnitRenderAction_PostRender) || bus != 0 || !data || !data->mNumberBuffers || !frames) return noErr;- if (tapped() || !atomic_load(&sg_engaged)) return noErr;- atomic_store(&sg_busy, true);+ Output *output = refCon;+ if (hasSound(&output->hardware, *flags, data)) atomic_store_explicit(&output->loudAt, mach_absolute_time(), memory_order_relaxed);+ if (output != music() || atomic_load(&output->taken) || !atomic_load(&sg_engaged)) return noErr;+ atomic_store(&output->busy, true);SGTimePitch *unit = atomic_load(&sg_inPlace);- if (atomic_load(&sg_engaged) && unit && SGTimePitchSampleRate(unit) == rateOf(&sg_hardware)) shiftInPlace(unit, flags, frames, data);- atomic_store(&sg_busy, false);+ if (atomic_load(&sg_engaged) && output == music() && unit && SGTimePitchSampleRate(unit) == rateOf(&output->hardware)) {+ shiftInPlace(unit, &output->hardware, flags, frames, data);+ }+ atomic_store(&output->busy, false);return noErr;}-#pragma mark - Spotify's audio thread+#pragma mark - the outputs (sg_outputsLock)static BOOL isRemoteIO(AudioUnit unit) {AudioComponentDescription description = {0};@@ -273,123 +369,369 @@ static BOOL isRemoteIO(AudioUnit unit) {return description.componentType == kAudioUnitType_Output && description.componentSubType == kAudioUnitSubType_RemoteIO;}-static OSStatus (*sg_setProperty)(AudioUnit, AudioUnitPropertyID, AudioUnitScope, AudioUnitElement, const void *, UInt32);--static OSStatus setProperty(AudioUnit unit, AudioUnitPropertyID property, AudioUnitScope scope, AudioUnitElement element,- const void *data, UInt32 size) {- if (property == kAudioUnitProperty_MaximumFramesPerSlice && data && size >= sizeof(UInt32)) {- UInt32 frames = *(const UInt32 *)data;- if (frames >= 256) atomic_store(&sg_chunk, frames);+static Output *outputOf(AudioUnit unit) {+ for (int i = 0; unit && i < kMaxOutputs; i++) if (atomic_load(&sg_outputs[i].unit) == unit) return &sg_outputs[i];+ return NULL;+}++static Output *outputFor(AudioUnit unit) {+ Output *output = outputOf(unit);+ for (int i = 0; !output && i < kMaxOutputs; i++) {+ if (atomic_load(&sg_outputs[i].unit)) continue;+ output = &sg_outputs[i];+ atomic_store(&output->source, NULL);+ atomic_store(&output->taken, false);+ atomic_store(&output->running, false);+ atomic_store(&output->chunk, 1024);+ atomic_store(&output->loudAt, 0);+ output->sourceTime = 0;+ output->order = output->eventAt = 0;+ output->listened = NO;+ atomic_store(&output->unit, unit);}- if (property != kAudioUnitProperty_MakeConnection || scope != kAudioUnitScope_Input || element != 0 || !data- || size < sizeof(AudioUnitConnection) || !isRemoteIO(unit)) {- return sg_setProperty(unit, property, scope, element, data, size);- }- const AudioUnitConnection *connection = data;- if (!connection->sourceAudioUnit) {- atomic_store(&sg_source, NULL);- AURenderCallbackStruct none = {0};- sg_setProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &none, sizeof none);- SGLog(@"redesign speed: Spotify disconnected its output");- return sg_setProperty(unit, property, scope, element, data, size);+ if (!output) {+ static int logged;+ if (logged++ < 3) SGLog(@"audio: more than %d outputs at once, %p is left as Spotify made it", kMaxOutputs, unit);}- sg_sourceBus = connection->sourceOutputNumber;- atomic_store(&sg_source, connection->sourceAudioUnit);- AURenderCallbackStruct callback = {feed, NULL};- OSStatus status = sg_setProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback);- SGLog(@"redesign speed: Spotify's mixer feeds its output through the menu's unit now (status %d)", (int)status);- if (status == noErr) return noErr;- atomic_store(&sg_source, NULL);- return sg_setProperty(unit, property, scope, element, data, size);+ return output;}-static OSStatus (*sg_startOutput)(AudioUnit unit);+// Waits for the output's render in progress, if any, to end.+static void waitFor(Output *output) {+ for (int i = 0; i < 400 && atomic_load(&output->busy); i++) usleep(250);+}-// One side of the RemoteIO unit's element 0 into `into`; a side that is not linear PCM is left as it was.-static BOOL readScope(AudioUnit unit, AudioUnitScope scope, Format *into, AudioStreamBasicDescription *format) {+// Stops the render threads using the unit, and returns once none is.+static void disengage(void) {+ atomic_store(&sg_engaged, false);+ for (int i = 0; i < kMaxOutputs; i++) waitFor(&sg_outputs[i]);+}++static void readScope(AudioUnit unit, AudioUnitScope scope, Format *into, AudioStreamBasicDescription *format) {UInt32 size = sizeof *format;OSStatus status = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, scope, 0, format, &size);- if (status != noErr || format->mFormatID != kAudioFormatLinearPCM || format->mSampleRate <= 0) return NO;+ if (status != noErr || format->mFormatID != kAudioFormatLinearPCM || format->mSampleRate <= 0) {+ *format = (AudioStreamBasicDescription){0};+ }uint64_t bits;memcpy(&bits, &format->mSampleRate, sizeof bits);atomic_store(&into->rateBits, bits);atomic_store(&into->flags, format->mFormatFlags);atomic_store(&into->channels, format->mChannelsPerFrame);atomic_store(&into->bytes, format->mBitsPerChannel / 8);- return YES;}-static void readFormat(AudioUnit unit) {- AudioStreamBasicDescription client = {0}, hardware = {0};- BOOL clientRead = readScope(unit, kAudioUnitScope_Input, &sg_client, &client);- BOOL hardwareRead = readScope(unit, kAudioUnitScope_Output, &sg_hardware, &hardware);- static int logged;- if (!clientRead || !hardwareRead) {- if (logged++ < 6) SGLog(@"redesign speed: the output is not linear PCM (Spotify's side %@, the hardware's %@)", clientRead ? @"is" : @"is not", hardwareRead ? @"is" : @"is not");- if (!clientRead) return;+static NSString *formatText(const AudioStreamBasicDescription *format) {+ if (format->mFormatID != kAudioFormatLinearPCM) return @"not linear PCM";+ return [NSString stringWithFormat:@"%.0f Hz, %u ch, %u-bit %@%@", format->mSampleRate, (unsigned)format->mChannelsPerFrame,+ (unsigned)format->mBitsPerChannel, (format->mFormatFlags & kAudioFormatFlagIsFloat) ? @"float" : @"integer",+ (format->mFormatFlags & kAudioFormatFlagIsNonInterleaved) ? @" split" : @" interleaved"];+}++// Why the callback cannot stand in for the connection to the client format `client`, nil when it can.+static NSString *refusal(Output *output, const AudioStreamBasicDescription *client) {+ BOOL canonical = client->mFormatID == kAudioFormatLinearPCM && (client->mFormatFlags & kAudioFormatFlagIsFloat)+ && (client->mFormatFlags & kAudioFormatFlagIsNonInterleaved) && client->mBitsPerChannel == 32+ && client->mChannelsPerFrame >= 1 && client->mChannelsPerFrame <= kSGTimePitchMaxChannels;+ if (!canonical) return [NSString stringWithFormat:@"Spotify's side is %@, not float split 1 or 2 ch", formatText(client)];+ AudioStreamBasicDescription mixer = {0};+ UInt32 size = sizeof mixer;+ AudioUnit source = atomic_load(&output->source);+ if (AudioUnitGetProperty(source, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, output->sourceBus, &mixer, &size) != noErr) return nil;+ UInt32 layout = kAudioFormatFlagIsFloat | kAudioFormatFlagIsNonInterleaved;+ if (mixer.mSampleRate != client->mSampleRate || (mixer.mFormatFlags & layout) != (client->mFormatFlags & layout)+ || mixer.mChannelsPerFrame != client->mChannelsPerFrame || mixer.mBitsPerChannel != client->mBitsPerChannel) {+ return [NSString stringWithFormat:@"its mixer gives %@ for %@", formatText(&mixer), formatText(client)];+ }+ return nil;+}++// Reads both formats and the mixer's slice, and puts in the callback or Spotify's own connection, whichever+// the formats allow. Answers why Spotify's connection is kept, nil when the callback feeds the output.+static NSString *settle(Output *output, AudioStreamBasicDescription *client, AudioStreamBasicDescription *hardware) {+ AudioUnit unit = atomic_load(&output->unit);+ readScope(unit, kAudioUnitScope_Input, &output->client, client);+ readScope(unit, kAudioUnitScope_Output, &output->hardware, hardware);+ AudioUnit source = atomic_load(&output->source);+ if (!source) return @"not connected";+ UInt32 slice = 0, size = sizeof slice;+ if (AudioUnitGetProperty(source, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &slice, &size) == noErr && slice >= 256) {+ atomic_store(&output->chunk, slice);+ }+ NSString *why = refusal(output, client);+ BOOL take = !why;+ if (take == atomic_load(&output->taken)) return why;+ OSStatus status;+ if (take) {+ AURenderCallbackStruct callback = {feed, output};+ status = sg_setProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback);+ } else {+ // Its sound passes as Spotify made it; the callback's render in progress, if any, ends first.+ AudioUnitConnection connection = {source, output->sourceBus, 0};+ status = sg_setProperty(unit, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &connection, sizeof connection);+ waitFor(output);+ }+ if (status == noErr) atomic_store(&output->taken, take);+ SGLog(@"audio: output %p %@ (status %d)%@", unit, take ? @"fed through the mod's callback" : @"given Spotify's own connection back",+ (int)status, why ? [@": " stringByAppendingString:why] : @"");+ return atomic_load(&output->taken) ? nil : why ?: @"the callback could not be set";+}++static void markEvent(Output *output) {+ static uint64_t order;+ output->order = ++order;+ output->eventAt = mach_absolute_time();+}++static NSString *describe(Output *output) {+ if (!output) return @"none";+ return [NSString stringWithFormat:@"%p (%.0f Hz)", atomic_load(&output->unit), rateOf(&output->client)];+}++static void tellWatchers(void) {+ Output *output = music();+ AudioUnit unit = output ? atomic_load(&output->unit) : NULL;+ for (int i = 0; i < kMaxWatchers && sg_watchers[i]; i++) sg_watchers[i](unit);+}++static void applyToFormat(void);++// The output that should carry the processors, Spotify's newest of the best kind: running and connected+// with sound in the last second, then running and connected, then running and fed by Spotify itself, then+// connected but not started, so speed can be chosen before Spotify starts it.+static Output *choose(void) {+ uint64_t now = mach_absolute_time();+ Output *best = NULL;+ int bestRank = -1;+ for (int i = 0; i < kMaxOutputs; i++) {+ Output *output = &sg_outputs[i];+ if (!atomic_load(&output->unit)) continue;+ BOOL connected = atomic_load(&output->source) != NULL, running = atomic_load(&output->running);+ if (!running && !connected) continue;+ BOOL sounds = seconds(now - MAX(atomic_load(&output->loudAt), output->eventAt)) < kSilentFor;+ int rank = running * 4 + connected * 2 + (running && connected && sounds);+ if (rank > bestRank || (rank == bestRank && output->order > best->order)) {+ best = output;+ bestRank = rank;+ }}- if (logged++ < 6) SGLog(@"redesign speed: Spotify's output is %.0f Hz, %u channels, %u bits, flags 0x%x, into the hardware's %.0f Hz, %u channels, %u bits, flags 0x%x, slices of %u, %@",- client.mSampleRate, (unsigned)client.mChannelsPerFrame, (unsigned)client.mBitsPerChannel, (unsigned)client.mFormatFlags,- hardware.mSampleRate, (unsigned)hardware.mChannelsPerFrame, (unsigned)hardware.mBitsPerChannel, (unsigned)hardware.mFormatFlags,- atomic_load(&sg_chunk), tapped() ? @"fed through the menu's unit" : @"not taken over");+ return best;}-static void apply(void);+// Hands the processors to the output that should have them; the watchers are told when they moved, or when+// `always` (a start of the music's output, a format change on it).+static void reselect(BOOL always, NSString *why) {+ Output *previous = music(), *next = choose();+ if (next != previous) {+ disengage();+ // The newest now, so it keeps the processors through a tie with the one it took them from.+ if (next) markEvent(next);+ atomic_store(&sg_music, next);+ SGLog(@"audio: the processors move from %@ to %@%@", describe(previous), describe(next), why ? [@", " stringByAppendingString:why] : @"");+ }+ if (next != previous || always) {+ tellWatchers();+ applyToFormat();+ }+}-// A speed or pitch chosen before the output started, or kept across a new format, applies now: apply()-// makes the unit again when the rate or the channels changed.-static void applyToFormat(void) {- dispatch_async(dispatch_get_main_queue(), ^{- if (sg_speed != 1 || sg_semitones != 0) apply();- });+static void checkSilence(void) {+ pthread_mutex_lock(&sg_outputsLock);+ int running = 0;+ for (int i = 0; i < kMaxOutputs; i++) running += atomic_load(&sg_outputs[i].unit) && atomic_load(&sg_outputs[i].running);+ if (running > 1) reselect(NO, [NSString stringWithFormat:@"its output silent for %.0f s while another has sound", kSilentFor]);+ pthread_mutex_unlock(&sg_outputsLock);}-// Either side of element 0 changing under a running unit: the hardware's on a route to a device at-// another rate, Spotify's when it hands the unit another format without starting it again.static void formatChanged(void *refCon, AudioUnit unit, AudioUnitPropertyID property, AudioUnitScope scope, AudioUnitElement element) {if (property != kAudioUnitProperty_StreamFormat || element != 0) return;if (scope != kAudioUnitScope_Input && scope != kAudioUnitScope_Output) return;- readFormat(unit);- applyToFormat();+ // Off the thread setting it: settling may set the unit's connection, which is not done from inside its own listener.+ Output *output = refCon;+ dispatch_async(sg_outputsQueue, ^{+ pthread_mutex_lock(&sg_outputsLock);+ if (atomic_load(&output->unit) == unit) {+ AudioStreamBasicDescription client, hardware;+ settle(output, &client, &hardware);+ SGLog(@"audio: output %p's format changed: Spotify's side %@, the hardware's %@", unit, formatText(&client), formatText(&hardware));+ reselect(output == music(), nil);+ }+ pthread_mutex_unlock(&sg_outputsLock);+ });+}++#pragma mark - Spotify's audio thread++// A format or slice Spotify sets on a mixer feeding an output: settled again, the output's own listener+// covering its side.+static void sourceChanged(AudioUnit unit) {+ pthread_mutex_lock(&sg_outputsLock);+ for (int i = 0; i < kMaxOutputs; i++) {+ Output *output = &sg_outputs[i];+ AudioUnit outputUnit = atomic_load(&output->unit);+ if (!outputUnit || atomic_load(&output->source) != unit) continue;+ dispatch_async(sg_outputsQueue, ^{+ pthread_mutex_lock(&sg_outputsLock);+ AudioStreamBasicDescription client, hardware;+ if (atomic_load(&output->unit) == outputUnit && atomic_load(&output->source) == unit) {+ settle(output, &client, &hardware);+ if (output == music()) applyToFormat();+ }+ pthread_mutex_unlock(&sg_outputsLock);+ });+ }+ pthread_mutex_unlock(&sg_outputsLock);+}++static OSStatus setProperty(AudioUnit unit, AudioUnitPropertyID property, AudioUnitScope scope, AudioUnitElement element,+ const void *data, UInt32 size) {+ if (property != kAudioUnitProperty_MakeConnection || scope != kAudioUnitScope_Input || element != 0 || !data+ || size < sizeof(AudioUnitConnection) || !isRemoteIO(unit)) {+ OSStatus status = sg_setProperty(unit, property, scope, element, data, size);+ if (status == noErr && (property == kAudioUnitProperty_StreamFormat || property == kAudioUnitProperty_MaximumFramesPerSlice)) sourceChanged(unit);+ return status;+ }+ const AudioUnitConnection *connection = data;+ pthread_mutex_lock(&sg_outputsLock);+ Output *output = outputFor(unit);+ if (!output) {+ pthread_mutex_unlock(&sg_outputsLock);+ return sg_setProperty(unit, property, scope, element, data, size);+ }+ if (!connection->sourceAudioUnit) {+ BOOL wasTaken = atomic_exchange(&output->taken, false);+ atomic_store(&output->source, NULL);+ waitFor(output);+ if (wasTaken) {+ AURenderCallbackStruct none = {0};+ sg_setProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &none, sizeof none);+ }+ SGLog(@"audio: Spotify disconnected output %p", unit);+ OSStatus status = sg_setProperty(unit, property, scope, element, data, size);+ reselect(NO, @"its output disconnected");+ pthread_mutex_unlock(&sg_outputsLock);+ return status;+ }+ // A new mixer: the old one's render, if any, ends first, and the new one's time starts at 0.+ atomic_store(&output->taken, false);+ atomic_store(&output->source, NULL);+ waitFor(output);+ output->sourceBus = connection->sourceOutputNumber;+ output->sourceTime = 0;+ atomic_store(&output->source, connection->sourceAudioUnit);+ markEvent(output);+ AudioStreamBasicDescription client, hardware;+ // Spotify's connection is made too only when the callback cannot stand in for it.+ NSString *why = settle(output, &client, &hardware);+ OSStatus status = why ? sg_setProperty(unit, property, scope, element, data, size) : noErr;+ SGLog(@"audio: Spotify connects mixer %p (bus %u) to output %p, %@%@", connection->sourceAudioUnit, (unsigned)connection->sourceOutputNumber,+ unit, formatText(&client), why ? [@"; its own connection kept: " stringByAppendingString:why] : @"; fed through the mod's callback");+ reselect(NO, @"Spotify connected it last");+ pthread_mutex_unlock(&sg_outputsLock);+ return status;+}++static OSStatus (*sg_startOutput)(AudioUnit unit);++// The silence check, a couple of times a second from Spotify's first start; it returns at once unless two+// outputs run.+static void startChecking(void) {+ static dispatch_once_t once;+ static dispatch_source_t timer; // kept, or it stops with its last reference+ dispatch_once(&once, ^{+ timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, sg_outputsQueue);+ dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), (uint64_t)(kCheckEvery * NSEC_PER_SEC), NSEC_PER_SEC / 10);+ dispatch_source_set_event_handler(timer, ^{+ checkSilence();+ });+ dispatch_resume(timer);+ });}static OSStatus startOutput(AudioUnit unit) {- if (unit && isRemoteIO(unit)) {- readFormat(unit);- AudioUnitRemoveRenderNotify(unit, rendered, NULL);- AudioUnitAddRenderNotify(unit, rendered, NULL);- AudioUnitRemovePropertyListenerWithUserData(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);- AudioUnitAddPropertyListener(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);- applyToFormat();+ if (!isRemoteIO(unit)) return sg_startOutput(unit);+ pthread_mutex_lock(&sg_outputsLock);+ Output *output = outputFor(unit);+ if (output) {+ startChecking();+ AudioStreamBasicDescription client, hardware;+ NSString *why = settle(output, &client, &hardware);+ markEvent(output);+ atomic_store(&output->running, true);+ if (!output->listened) {+ output->listened = YES;+ AudioUnitAddRenderNotify(unit, rendered, output);+ AudioUnitAddPropertyListener(unit, kAudioUnitProperty_StreamFormat, formatChanged, output);+ }+ // Every start of the music's output is told, so what holds sound from before the pause starts over.+ reselect(music() == output, @"Spotify started it last");+ AudioUnit source = atomic_load(&output->source);+ SGLog(@"audio: output %p started: Spotify's side %@, the hardware's %@, %@; the processors are on %@", unit, formatText(&client),+ formatText(&hardware), !source ? @"fed by Spotify itself" : why ? [NSString stringWithFormat:@"mixer %p through Spotify's connection (%@)", source, why]+ : [NSString stringWithFormat:@"mixer %p through the mod's callback", source], music() == output ? @"this one" : describe(music()));}+ pthread_mutex_unlock(&sg_outputsLock);return sg_startOutput(unit);}-#pragma mark - engaging the unit+static OSStatus (*sg_stopOutput)(AudioUnit unit);-// Stops the render thread using a unit, and returns once it no longer is.-static void disengage(void) {- atomic_store(&sg_engaged, false);- for (int i = 0; i < 200 && atomic_load(&sg_busy); i++) usleep(250);+static OSStatus stopOutput(AudioUnit unit) {+ OSStatus status = sg_stopOutput(unit);+ pthread_mutex_lock(&sg_outputsLock);+ Output *output = outputOf(unit);+ if (output && atomic_exchange(&output->running, false)) {+ reselect(NO, @"its output stopped");+ SGLog(@"audio: output %p stopped (Spotify's side %.0f Hz); the processors are on %@", unit, rateOf(&output->client), describe(music()));+ }+ pthread_mutex_unlock(&sg_outputsLock);+ return status;+}++static OSStatus (*sg_dispose)(AudioComponentInstance unit);++// Every output fed by the unit loses it, and the unit's own output is forgotten, before it goes; renders in+// progress end first.+static OSStatus disposeUnit(AudioComponentInstance unit) {+ pthread_mutex_lock(&sg_outputsLock);+ BOOL changed = NO;+ for (int i = 0; i < kMaxOutputs; i++) {+ Output *output = &sg_outputs[i];+ AudioUnit outputUnit = atomic_load(&output->unit);+ if (!outputUnit) continue;+ if (outputUnit == unit) {+ if (output == music()) disengage();+ atomic_store(&output->running, false);+ atomic_store(&output->source, NULL);+ waitFor(output);+ atomic_store(&output->unit, NULL);+ SGLog(@"audio: output %p disposed (Spotify's side %.0f Hz)", unit, rateOf(&output->client));+ changed = YES;+ } else if (atomic_load(&output->source) == unit) {+ atomic_store(&output->source, NULL);+ waitFor(output);+ SGLog(@"audio: mixer %p disposed, output %p plays silence until Spotify connects another", unit, outputUnit);+ changed = YES;+ }+ }+ if (changed) reselect(NO, @"a unit disposed");+ // Under the lock, so its slot is not used again while its last render may still be running.+ OSStatus status = sg_dispose(unit);+ pthread_mutex_unlock(&sg_outputsLock);+ return status;}-// The unit for the output's format and the way in use, made when there is none or the format changed. A+#pragma mark - engaging the unit++// The unit for the music's format and the way in use, made when there is none or the format changed. A// replaced one is never freed: the render thread may still hold it, and a format change is rare.static SGTimePitch *unitForFormat(void) {- BOOL pull = tapped();- Format *format = pull ? &sg_client : &sg_hardware;+ Output *output = music();+ if (!output) return NULL;+ BOOL pull = atomic_load(&output->taken);+ Format *format = pull ? &output->client : &output->hardware;double rate = rateOf(format);UInt32 channels = atomic_load(&format->channels);- if (pull) {- // In the chain the unit hands its buffers to the RemoteIO unit as they are: float, one per channel.- UInt32 flags = atomic_load(&format->flags);- BOOL canonical = (flags & kAudioFormatFlagIsFloat) && (flags & kAudioFormatFlagIsNonInterleaved) && atomic_load(&format->bytes) == 4;- if (!canonical) {- static int logged;- if (logged++ < 3) SGLog(@"redesign speed: the output is not float per channel (flags 0x%x), speed cannot apply", (unsigned)flags);- return NULL;- }- }if (rate <= 0 || channels < 1 || channels > kSGTimePitchMaxChannels) return NULL;_Atomic(SGTimePitch *) *slot = pull ? &sg_pull : &sg_inPlace;pthread_mutex_lock(&sg_buildLock);@@ -445,7 +787,7 @@ static void apply(void) {SGTimePitch *unit = unitForFormat();if (!unit) {static int logged;- if (!normal && logged++ < 3) SGLog(@"redesign speed: Spotify's output has not started, nothing to change yet");+ if (!normal && logged++ < 3) SGLog(@"redesign speed: Spotify's output has not started, or is in a format the unit does not take; nothing to change yet");return;}SGTimePitchSetRate(unit, tapped() ? sg_speed : 1);@@ -458,7 +800,16 @@ static void apply(void) {switchIfAsked(unit);}-#pragma mark - the menu's calls+// A speed or pitch chosen before the output started, or kept across a new format or another output, applies+// now: apply() makes the unit again when the rate or the channels changed, and puts it back in, reset, after+// a change of output took it out.+static void applyToFormat(void) {+ dispatch_async(dispatch_get_main_queue(), ^{+ if (sg_speed != 1 || sg_semitones != 0) apply();+ });+}++#pragma mark - the callsdouble SGPlayerSpeed(void) {return sg_speed;@@ -480,7 +831,7 @@ float SGPlayerPitch(void) {}void SGSetPlayerPitch(float semitones) {- if (!sg_startOutput && !tapped()) return;+ if (!sg_reachable && !tapped()) return;sg_semitones = semitones;apply();}@@ -497,7 +848,57 @@ void SGSetPlayerPitchFollowsSpeed(BOOL follows) {}BOOL SGPlayerPitchAvailable(void) {- return sg_startOutput != NULL || tapped();+ return sg_reachable || tapped();+}++AudioUnit SGPlayerMusicOutput(void) {+ Output *output = music();+ return output ? atomic_load(&output->unit) : NULL;+}++BOOL SGPlayerMusicClientFormat(AudioStreamBasicDescription *format) {+ pthread_mutex_lock(&sg_outputsLock);+ AudioUnit unit = SGPlayerMusicOutput();+ UInt32 size = sizeof *format;+ BOOL read = unit && AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, format, &size) == noErr;+ pthread_mutex_unlock(&sg_outputsLock);+ return read;+}++static void rebind(void) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ mach_timebase_info_data_t timebase;+ mach_timebase_info(&timebase);+ sg_secondsPerTick = (double)timebase.numer / timebase.denom / 1e9;+ sg_outputsQueue = dispatch_queue_create("spotifyglass.outputs", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0));+ if (!SGRebindImport("AudioUnitSetProperty", setProperty, (void **)&sg_setProperty) || !sg_setProperty) {+ sg_setProperty = NULL;+ SGLog(@"redesign speed: Spotify does not import AudioUnitSetProperty, the menu offers pitch only");+ }+ sg_reachable = SGRebindImport("AudioOutputUnitStart", startOutput, (void **)&sg_startOutput) && sg_startOutput;+ if (!sg_reachable) {+ SGLog(@"audio: Spotify does not import AudioOutputUnitStart, its output cannot be reached");+ return;+ }+ if (!SGRebindImport("AudioOutputUnitStop", stopOutput, (void **)&sg_stopOutput) || !sg_stopOutput) sg_stopOutput = AudioOutputUnitStop;+ if (!SGRebindImport("AudioComponentInstanceDispose", disposeUnit, (void **)&sg_dispose) || !sg_dispose) {+ sg_dispose = AudioComponentInstanceDispose;+ SGLog(@"audio: Spotify does not import AudioComponentInstanceDispose, a disposed output is not seen");+ }+ });+}++BOOL SGPlayerWatchMusicOutput(SGPlayerOutputWatcher watcher) {+ rebind();+ pthread_mutex_lock(&sg_outputsLock);+ for (int i = 0; i < kMaxWatchers; i++) {+ if (sg_watchers[i]) continue;+ sg_watchers[i] = watcher;+ break;+ }+ pthread_mutex_unlock(&sg_outputsLock);+ return sg_reachable;}#pragma mark - Spotify's clock@@ -512,14 +913,7 @@ BOOL SGPlayerPitchAvailable(void) {%ctor {storeFloat(&sg_speedBits, 1);- if (!SGRebindImport("AudioUnitSetProperty", setProperty, (void **)&sg_setProperty) || !sg_setProperty) {- sg_setProperty = NULL;- SGLog(@"redesign speed: Spotify does not import AudioUnitSetProperty, the menu offers pitch only");- }- if (!SGRebindImport("AudioOutputUnitStart", startOutput, (void **)&sg_startOutput) || !sg_startOutput) {- sg_startOutput = NULL;- SGLog(@"redesign speed: Spotify does not import AudioOutputUnitStart");- }+ rebind();%init;SGRequireClasses(@[@"SPTPlayerState"]);}