Skip to content

Commit 8fc258a

Browse files
fix(core): assess memory after reduced allocations render
Keep confirmed allocation reductions at their current height until the new generation releases old textures. Continue full budget checks for growth or pending allocations, and preserve visibility-resume checks. Cover marginal headroom, persistent pressure and unknown pending memory.
1 parent b8cf340 commit 8fc258a

7 files changed

Lines changed: 106 additions & 15 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ Avoid blocking work on latency-sensitive threads, unnecessary polling, duplicate
107107

108108
- **Threads** ([ARCHITECTURE §5 *Threads*](docs/ARCHITECTURE.md)): GL thread (`THREAD_PRIORITY_DISPLAY`) owns the projectM handle (create, render, load, settings) and output measurement; `AudioCapture` HandlerThread (`THREAD_PRIORITY_AUDIO`); a native worker for preset indexing and prefetch; a background shader-compile `std::thread` started from the GL thread (`preset_prewarm`); the UI polls status every 500 ms. Other entry points only write atomics or mutex-protected buffers; keep it that way.
109109
- **Visibility and cleanup:** `MainActivity.onPause` stops the track watcher, UI refresh, updater and audio, then calls `visualizerView.onPause()`; `onResume` restarts them and re-checks notification access. `onDestroy` releases projectM on the GL thread (`queueEvent(renderer::release)`); after context loss the next `onSurfaceCreated` cleans up.
110-
- **Frame pacing/quality:** half-refresh-rate pacing uses Choreographer. QualityController always uses Auto up to the detected panel, with FPS hysteresis/CPU-bound probe checks and a live ActivityManager memory budget initialized from application context in ProjectMCore.init. Standard is the Native trails default; Medium/High add the same passes with different gain. No user-facing fixed-resolution/static-RAM controls remain. Use `QualityController.setRenderAllocationSettings(trails, transitionSeconds)` to review the final tuple atomically. Reductions retain resident credit, while net growth and pending/context-recreated allocations require a full review. Managed clients publish dimensions/trails/transition as one generation-tagged rendering configuration; GL holds allocation settings until surface-size acknowledgement. Revalidate preserved/context-recreated resumes, reject stale generations, and base FPS on completed frames tagged with context/size. When an applied size change has `wasLastChangeForMemoryPressure()`, call the existing native pressure hook to flush pooled textures and pause prewarming. Do not claim a universal music-process survival guarantee from heuristic headroom.
110+
- **Frame pacing/quality:** half-refresh-rate pacing uses Choreographer. QualityController always uses Auto up to the detected panel, with FPS hysteresis/CPU-bound probe checks and a live ActivityManager memory budget initialized from application context in ProjectMCore.init. Standard is the Native trails default; Medium/High add the same passes with different gain. No user-facing fixed-resolution/static-RAM controls remain. Use `QualityController.setRenderAllocationSettings(trails, transitionSeconds)` to review the final tuple atomically. After renewing the FPS generation, use `revalidateForAllocationChange(growing)`: confirmed reductions defer memory sampling until the new tuple renders and releases old textures, while net growth and pending allocations require a full review. Managed clients publish dimensions/trails/transition as one generation-tagged rendering configuration; GL holds allocation settings until surface-size acknowledgement. Use `revalidateForResume` for preserved/context-recreated resumes, reject stale generations, and base FPS on completed frames tagged with context/size. When an applied size change has `wasLastChangeForMemoryPressure()`, call the existing native pressure hook to flush pooled textures and pause prewarming. Do not claim a universal music-process survival guarantee from heuristic headroom.
111111
- **No measured universal frame-time or memory bound is defined. Automatic memory uses documented conservative footprint/reserve estimates; see `docs/superpowers/specs/2026-10-05-native-trails.md`.** Compare before/after on the same TV, preset, render height and audio (PR template).
112112
- **Measurement tools:** profile build + simpleperf ([docs/PROFILING.md](docs/PROFILING.md)); pin a preset with `adb shell setprop debug.projectmtv.preset '<name prefix>'` and clear it afterwards (`debug.projectmtv.update_from` also exists); `tools/tv-diagnostics.sh <tv-ip>:5555 --no-install --duration 180` ([docs/DIAGNOSTICS.md](docs/DIAGNOSTICS.md); profile builds require `--package nl.neerdael.projectmtv.profile` with a matching `--apk` or `--no-install`; build/`--release` modes reject alternate package IDs before connecting); Record actual Auto render sizes and compare target-FPS/trails workloads rather than forcing a resolution sweep. Preset Lab provides offline rendering comparisons (desktop timings do not establish TV performance).
113113
- **Documented device coverage:** NVIDIA SHIELD TV 2019 (`sif`, 2 GB, 32-bit) and SHIELD TV Pro 2019 (`mdarcy`, 3 GB), Android 11; Ugoos AM6 (Amlogic S922X, Mali-G52 MP6, Android 9). No emulator configuration is committed.

‎README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,10 @@ static-RAM inputs normalize to Auto. Standard trails is the Android core default
228228
Medium and High add more trail detail with the same extra passes. Managed clients
229229
review trails/transition together with `setRenderAllocationSettings`, publish
230230
budget-approved dimensions/settings coherently, and acknowledge fresh memory checks
231-
on context recreation. Reducing allocations retains resident credit; net growth
232-
and pending allocations receive a full review. See [architecture](docs/ARCHITECTURE.md),
231+
on context recreation. Call `revalidateForAllocationChange` after invalidating the
232+
old FPS generation: confirmed reductions wait for the new tuple to render before
233+
sampling memory pressure; net growth and pending allocations receive a full review.
234+
Visibility resumes still use `revalidateForResume`. See [architecture](docs/ARCHITECTURE.md),
233235
[release workflow](docs/RELEASING.md) and [profiling](docs/PROFILING.md).
234236

235237
### projectM

‎app/src/main/java/com/example/projectm/visualizer/MainActivity.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,9 +357,9 @@ private void publishRenderConfiguration(int height) {
357357
budgetedDetailAllocation = detail;
358358
budgetedBlendAllocation = blend;
359359
// Invalidate queued FPS for every topology change. Growth needs a full review;
360-
// reductions keep resident credit unless an earlier allocation is still pending.
360+
// confirmed reductions defer pressure sampling until GL releases the old textures.
361361
renderBudgetGeneration = ProjectMJNI.requireRenderBudget();
362-
quality.revalidateForResume(growing); // The listener publishes its chosen height.
362+
quality.revalidateForAllocationChange(growing); // The listener publishes its chosen height.
363363
return;
364364
}
365365
visualizerView.setRenderConfiguration(display.widthForHeight(height), height,

‎core/src/main/java/nl/neerdael/projectm/core/QualityController.java‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -152,12 +152,7 @@ public void setMode(int height, int lastAutoHeight) {
152152
public void revalidateForResume(boolean contextRecreated) {
153153
if (contextRecreated) fullAllocationPending = true;
154154
memorySnapshot = sampleMemory();
155-
healthyMemorySamples = 0;
156-
fpsBeforeLowering = 0;
157-
loweredFrom = -1;
158-
cpuBoundPreset = -1;
159-
lastChangeForMemoryPressure = false;
160-
resetCounters(SETTLE_MS);
155+
resetAllocationProbe();
161156
int to = current;
162157
if (memorySnapshot == null || !memorySnapshot.isValid()) {
163158
// Missing data cannot authorize reusing/rebuilding an expensive saved allocation.
@@ -180,6 +175,30 @@ public void revalidateForResume(boolean contextRecreated) {
180175
}
181176
}
182177

178+
/**
179+
* Publish a changed allocation tuple after the host invalidates its old FPS generation.
180+
* Growth and unconfirmed allocations require a fresh budget. A confirmed reduction keeps
181+
* its height until GL releases the old textures; the next completed-generation FPS sample
182+
* then checks actual available memory. Visibility resumes still use revalidateForResume.
183+
*/
184+
public void revalidateForAllocationChange(boolean growing) {
185+
if (growing || fullAllocationPending) {
186+
revalidateForResume(growing);
187+
} else {
188+
resetAllocationProbe();
189+
listener.onApplyRenderHeight(currentHeight());
190+
}
191+
}
192+
193+
private void resetAllocationProbe() {
194+
healthyMemorySamples = 0;
195+
fpsBeforeLowering = 0;
196+
loweredFrom = -1;
197+
cpuBoundPreset = -1;
198+
lastChangeForMemoryPressure = false;
199+
resetCounters(SETTLE_MS);
200+
}
201+
183202
/** Standard=0, Medium=1, High=2. Medium and High allocate the same detail textures. */
184203
public void setNativeTrailsLevel(int level) {
185204
setRenderAllocationSettings(level, (int) (transitionMs / 1000L));

‎core/src/test/java/nl/neerdael/projectm/core/QualityControllerTest.java‎

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -662,11 +662,67 @@ public void confirmedAllocationReductionsPreserveResidentHeight() throws Excepti
662662
q.onFpsSample(60);
663663
memory.snapshot = new MemorySnapshot(2L << 30, 700L << 20, 128L << 20, false);
664664
q.setRenderAllocationSettings(removeTrails ? 0 : 2, removeTrails ? 10 : 0);
665-
q.revalidateForResume(false);
665+
q.revalidateForAllocationChange(false);
666666
assertEquals("freeing resident allocations must not debit a full replacement", 2160, applied);
667667
}
668668
}
669669

670+
@Test
671+
public void confirmedReductionWaitsForTexturesToBeReleasedBeforeSamplingPressure() throws Exception {
672+
for (boolean removeTrails : new boolean[]{true, false}) {
673+
FakeMemory memory = new FakeMemory();
674+
QualityController q = withMemory(memory, 2048);
675+
q.setRenderAllocationSettings(2, 10);
676+
q.setMode(0, 2160);
677+
q.onFpsSample(60);
678+
// Below the reserve while the old, larger native allocation is still resident.
679+
memory.snapshot = new MemorySnapshot(2L << 30, 400L << 20, 128L << 20, false);
680+
q.setRenderAllocationSettings(removeTrails ? 0 : 2, removeTrails ? 10 : 0);
681+
int reads = memory.reads;
682+
q.revalidateForAllocationChange(false);
683+
assertEquals("publish the cheaper tuple before assessing pressure", 2160, applied);
684+
assertEquals("pre-release memory cannot judge the reduced allocation", reads, memory.reads);
685+
// The host now applies the tuple and accepts only its completed-generation FPS.
686+
memory.snapshot = new MemorySnapshot(2L << 30, 700L << 20, 128L << 20, false);
687+
q.onFpsSample(60);
688+
assertEquals(reads + 1, memory.reads);
689+
assertEquals("the release itself restored the reserve", 2160, applied);
690+
}
691+
}
692+
693+
@Test
694+
public void pressureRemainingAfterAConfirmedReductionStillLowersResolution() throws Exception {
695+
FakeMemory memory = new FakeMemory();
696+
QualityController q = withMemory(memory, 2048);
697+
q.setRenderAllocationSettings(2, 10);
698+
q.setMode(0, 2160);
699+
q.onFpsSample(60);
700+
memory.snapshot = new MemorySnapshot(2L << 30, 300L << 20, 128L << 20, true);
701+
q.setRenderAllocationSettings(0, 0);
702+
q.revalidateForAllocationChange(false);
703+
assertEquals(2160, applied);
704+
q.onFpsSample(60); // New tuple rendered, but its release did not relieve pressure.
705+
assertTrue("pressure is checked even while the FPS probe settles", applied < 2160);
706+
assertTrue(q.wasLastChangeForMemoryPressure());
707+
}
708+
709+
@Test
710+
public void allocationGrowthAndUnconfirmedReductionStillSampleBeforePublishing() throws Exception {
711+
for (boolean growing : new boolean[]{true, false}) {
712+
FakeMemory memory = new FakeMemory();
713+
QualityController q = withMemory(memory, 2048);
714+
q.setRenderAllocationSettings(growing ? 0 : 2, growing ? 0 : 10);
715+
q.setMode(0, 2160);
716+
if (growing) q.onFpsSample(60);
717+
q.setRenderAllocationSettings(growing ? 2 : 0, growing ? 10 : 0);
718+
memory.snapshot = null;
719+
int reads = memory.reads;
720+
q.revalidateForAllocationChange(growing);
721+
assertEquals(reads + 1, memory.reads);
722+
assertTrue("unknown RAM cannot authorize a pending allocation", applied < 2160);
723+
}
724+
}
725+
670726
@Test
671727
public void oppositeSettingsChangesReviewTheirFinalNetReduction() throws Exception {
672728
FakeMemory memory = new FakeMemory();
@@ -676,7 +732,7 @@ public void oppositeSettingsChangesReviewTheirFinalNetReduction() throws Excepti
676732
q.onFpsSample(60);
677733
memory.snapshot = new MemorySnapshot(2L << 30, 650L << 20, 128L << 20, false);
678734
q.setRenderAllocationSettings(2, 0);
679-
q.revalidateForResume(false);
735+
q.revalidateForAllocationChange(false);
680736
assertEquals("High without blending is cheaper than Standard with blending", 2160, applied);
681737
}
682738

@@ -688,10 +744,10 @@ public void pendingReductionsAndRapidGrowthDoNotInventResidentCredit() throws Ex
688744
q.setMode(0, 2160); // No confirmed rendered sample yet.
689745
memory.snapshot = new MemorySnapshot(4L << 30, 1300L << 20, 128L << 20, false);
690746
q.setRenderAllocationSettings(2, 0);
691-
q.revalidateForResume(false);
747+
q.revalidateForAllocationChange(false);
692748
assertEquals("an unrendered reduction still needs the full remaining allocation", 1800, applied);
693749
q.setRenderAllocationSettings(0, 10);
694-
q.revalidateForResume(true);
750+
q.revalidateForAllocationChange(true);
695751
assertEquals("rapid growth cannot credit the unrendered intermediate tuple", 1440, applied);
696752
}
697753

‎docs/ARCHITECTURE.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,13 @@ The GL surface buffer is resized with `SurfaceHolder.setFixedSize(w, h)`. The di
174174

175175
On the historical2GB SHIELD, 1440p-and-above rendering caused Android’s low-memory killer to close SoundCloud and other processes. That observation motivates proactive headroom checks and cache/prewarm cleanup; it does not prove that any reserve guarantees survival under every vendor policy. Live music-process and memory validation remains necessary.
176176

177+
Managed hosts review trails/transition settings atomically, invalidate the old FPS generation,
178+
then call `revalidateForAllocationChange(growing)`. A confirmed reduction publishes its current
179+
height before sampling memory: the next new-generation rendered-frame sample observes the
180+
texture release and still lowers resolution if pressure persists. Growth and unconfirmed
181+
allocations require a fresh full budget. Visibility/context resumes independently use
182+
`revalidateForResume` and always sample current memory before rendering.
183+
177184
### Frame pacing
178185
Full rate renders continuously (`RENDERMODE_CONTINUOUSLY`). Half rate switches to `RENDERMODE_WHEN_DIRTY` and a `Choreographer` callback calls `requestRender()` on every second vsync: 30 fps at 60 Hz, 25 fps at 50 Hz. A steady half rate looks smoother than an uneven 40–50 fps and leaves the GPU room for heavy presets. projectM animates on wall-clock time, so the speed of the visuals doesn't change.
179186

‎docs/superpowers/specs/2026-10-05-native-trails.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ releasing the first-frame guard, and confirms an actual preset frame before FPS
147147
data can count as resident allocation. Pending initial allocations retain full
148148
budget accounting if settings change before that first rendered sample.
149149

150+
For a confirmed allocation reduction, the host invalidates old FPS and calls
151+
`revalidateForAllocationChange(false)` to publish the cheaper tuple at the current
152+
height. Memory pressure is reassessed by the next completed-generation FPS sample,
153+
after native code releases the old textures. This avoids reducing resolution based
154+
on memory still occupied by the pending release. Growth or unconfirmed allocations
155+
retain fresh full-budget review; persistent pressure still lowers resolution.
156+
150157
A preserved-context resume also samples current memory before rendering resumes.
151158
The controller resets stale growth credit and always republishes a chosen height
152159
for acknowledgement, even unchanged. These integration paths must be exercised

0 commit comments

Comments
 (0)