~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
206 lines · 12.2 KB Raw History
# High startup latency investigation — 2026-09-23

## Checkpoint and scope

Gapless High and its physical listening confirmation were committed first as
`df8155f` (native Opus baseline: `6670cc5`). The initial investigation added DEBUG-only stage timing. The September 24
implementation below adds prewarm, preparation reuse and HTTP-aware public
JavaScript caching. No new package, copied implementation or server component
was added. Baseline sections below are historical measurements.

## Baseline measurements

The installed gapless iPhone build logged two manual selections:

| Milestone from selection | First | Second |
| --- | ---: | ---: |
| Stream resolved | 2,825 ms | 1,524 ms |
| Native asset installed | 2,832 ms | 1,524 ms |
| Native item ready | 2,938 ms | 1,605 ms |
| First verified render progress | 3,312 ms | 1,900 ms |

Native preparation therefore added 106 / 81 ms after asset installation. Most
of the waiting preceded the native decoder. The verification milestone is a
sampled render-clock check, not an acoustic timestamp: the 250 ms monitor and
minimum advancing-clock requirement contribute to its difference from readiness.

A fresh `just simulator-smoke-high` with stage diagnostics passed on iPhone
18 Pro / iOS 27. Its complete High startup was 2,943 ms:

| Resolution stage | Cold | Warm return to High |
| --- | ---: | ---: |
| Session / visitor context | 142 ms | <1 ms |
| Proof creation / token retrieval | 627 ms | <1 ms |
| Initial player response | 263 ms | 258 ms |
| Anonymous watch-page script discovery | 698 ms | 730 ms |
| Player JavaScript download | 229 ms | 220 ms |
| Timestamp-aligned player response | 105 ms | 194 ms |
| Candidate parsing / local deciphering / proof attachment | 279 ms | 34 ms |
| Byte-zero media probe | 87 ms | 16 ms |
| Total resolver attempt, including small parsing overhead | 2,435 ms | 1,456 ms |

The warm case returns to **the same song** after Standard playback, not a
different-song or cold-start measurement. End-to-end verified progress was
1,872 ms on that return, including seek restoration. The first native
preparation took 143 ms, and the second 94 ms. Both media probes returned 206;
the diagnostic passed playback, seeks, pause/resume, and quality switching.
These new per-stage numbers are simulator evidence, not iPhone stage timings.

Both High attempts fetched a 2,597,768-byte script. The discovery pages were
1,309,564 and 1,388,690 bytes. Thus nearly one second and roughly 3.9 MB of
decoded HTTP response bodies were spent discovering/downloading script assets
on each attempt, despite successful reuse of proof and prepared decipher code.
Those byte counts are decoded body sizes, not compressed network usage.

## Why the baseline critical path was long

`InnerTubeMusicService.resolveHighQualityStreamOnce` originally serialized:

1. Prepare session/visitor context and obtain proof.
2. Make an initial authenticated WEB_REMIX player request.
3. Locate its player script. Both observed responses needed the anonymous
   watch-page fallback, followed by the script download.
4. Read the script's timestamp and make a second authenticated player request.
5. Decipher the selected Opus URL and attach streaming proof.
6. Probe one byte of media, then return the URL to the native output layer.

The original `InnerTubeClient` used `urlCache = nil` throughout and stored neither a player
script cache nor a reusable script-discovery result. The decipher actor does
cache one script's prepared solver and bounded challenge results, but only
receives that script after the transport has downloaded it again. Proof
generation is also cached after first use, but starts on first playback.

The six-second native PCM buffer does not hold startup for six seconds: the
engine becomes ready after its first roughly 250 ms decoded chunk and fills
the remaining queue asynchronously. Gapless hides stream resolution by doing
it before an automatic boundary; a manually selected first track has no such
prepared successor.

## Comparison with other clients

Sources consulted are pinned below; their behavior is implementation evidence,
not an official InnerTube API guarantee.

### AuraMusic

Reference commit: `185a77d31733047de06cbec619d40731755a0ec1`.

- [`YTPlayerUtils.kt`](https://github.com/TeamAuraMusic/AuraMusic/blob/185a77d31733047de06cbec619d40731755a0ec1/app/src/main/kotlin/com/auramusic/app/utils/YTPlayerUtils.kt):
  its audio flow obtains a main-client proof/player response, then tries a
  bounded series of stream clients, including guests. It can reuse the main
  response and probes candidate media before selecting it. It does not use
  Hydraulophone's mandatory initial-plus-timestamp-aligned audio requests.
- [`NewPipe.kt`](https://github.com/TeamAuraMusic/AuraMusic/blob/185a77d31733047de06cbec619d40731755a0ec1/innertube/src/main/kotlin/com/auramusic/innertube/pages/NewPipe.kt):
  keeps a long-lived NewPipe wrapper and delegates script/timestamp/signature
  work to `YoutubeJavaScriptPlayerManager`. This wrapper alone is not evidence
  of a particular downstream script-cache lifetime.

Hydraulophone's second request is a deliberate adaptation: earlier live iPhone
and simulator probes rejected unaligned WEB_REMIX URLs with 403. Replacing it
with Aura's audio sequence without new evidence risks the working High path.

### Metrolist and its InnerTubeX dependency

Metrolist commit: `28fa8f042bfabb880bdecc0d9fa37e86cf72b90e`.
Its pinned InnerTubeX `v0.7.0` resolves to
`cc74e737b6ae2875343fb2e31c7283e39e1cf72e`.

- [`App.kt`](https://github.com/MetrolistGroup/Metrolist/blob/28fa8f042bfabb880bdecc0d9fa37e86cf72b90e/app/src/main/kotlin/com/metrolist/music/App.kt):
  launches background prewarming after settings initialization, a 2.5-second
  delay, and a bounded wait for visitor context.
- [`InnerTubeXPlayer.kt`](https://github.com/MetrolistGroup/Metrolist/blob/28fa8f042bfabb880bdecc0d9fa37e86cf72b90e/app/src/main/kotlin/com/metrolist/music/utils/InnerTubeXPlayer.kt):
  retains an extraction bundle by transport generation and persists public
  remote cipher configuration with timestamp/source/ETag metadata.
- [`InnerTubeExtractor.kt`](https://github.com/MetrolistGroup/innertubex/blob/cc74e737b6ae2875343fb2e31c7283e39e1cf72e/src/commonMain/kotlin/com/metrolist/innertubex/extraction/InnerTubeExtractor.kt):
  prewarms config, player code/EJS, and optional proof. Some independent work
  runs concurrently. Its 30-minute player-config cache separates authenticated
  and unauthenticated configurations, checks session identity, and falls back
  to fresh configuration when cached extraction fails. The prewarm video is
  a fixed implementation detail, not a requirement for our app.
- [`YouTubeCipherService.kt`](https://github.com/MetrolistGroup/innertubex/blob/cc74e737b6ae2875343fb2e31c7283e39e1cf72e/src/commonMain/kotlin/com/metrolist/innertubex/cipher/YouTubeCipherService.kt):
  maintains player-URL-keyed code/solver caches and coalesces code fetches;
  exposes player-code/EJS preparation ahead of playback.
- [`StreamUrlCache.kt`](https://github.com/MetrolistGroup/Metrolist/blob/28fa8f042bfabb880bdecc0d9fa37e86cf72b90e/app/src/main/kotlin/com/metrolist/music/playback/StreamUrlCache.kt)
  and [`MusicService.kt`](https://github.com/MetrolistGroup/Metrolist/blob/28fa8f042bfabb880bdecc0d9fa37e86cf72b90e/app/src/main/kotlin/com/metrolist/music/playback/MusicService.kt):
  reuse URLs and associated headers until expiry. Per-entry generations reject
  stale asynchronous writes after invalidation; 403/410 handling invalidates
  the stream and can request a cipher-config refresh. Such a URL cache helps
  repeat selections, not a genuinely cold first selection.

The transferable approach is to prepare reusable state before playback, cache
by the correct identity, and retain bounded fresh-discovery recovery. Neither
client comparison proves that a particular cache TTL or guest profile will
work with our current iPhone session and proof flow.

## Recommended implementation order

1. **Prewarm after authenticated session restoration when High is selected.**
   Prepare the proof generator and player code/solver using cancellable shared
   tasks. Avoid background work blocking a first selection; it should join a
   compatible task or continue normal resolution. Clear session-bound state
   on session change/sign-out. Keep public script source separate from tokens.
2. **Introduce bounded, identity-aware player state reuse.** Cache script bytes
   and prepared solver by exact player version/URL, keep timestamp paired with
   that script, and invalidate discovery on relevant rejection. Start with
   fresh-discovery fallback intact and compare cold/warm starts separately.
   The earlier ten-minute cache skipped initial discovery and caused reported
   reliability regressions; it must not simply be reinstated. That earlier
   report does not establish the precise cache failure mechanism.
3. **Overlap genuinely independent cold work.** Proof preparation and anonymous
   player discovery can potentially overlap. Evaluate eliminating the initial
   player request only when the same fresh discovery supplies a matching
   timestamp and all authentication/availability checks remain on the aligned
   request. This changes protocol sequencing and needs a bounded live comparison.
4. **Consider reusing the liveness read as initial media bytes.** The current
   one-byte probe and native 64 KiB head are separate requests/sessions. A
   validated bounded head could serve both, retaining 403 refresh and strict
   Content-Range checks. The observed 16–87 ms probe is lower priority than
   discovery and cold proof/decipher preparation.

No latency reduction is claimed from this investigation alone. A successful
change must improve measured startup while retaining seek/gapless/native-media
behavior and the fresh-proof/player recovery path on a physical iPhone.

## Verification and deferred briefs

`just lint`, `git diff --check`, and the existing `just simulator-smoke-high`
passed. No package, hosted-app or UI test suites were added or run. The iPhone
retains the confirmed gapless build; this diagnostic-only build ran in the
simulator. Proposed coverage is in
[`high-startup.md`](../test-briefs/high-startup.md).

Diagnostics log only random per-attempt IDs, fixed phase labels, monotonic
elapsed times, and byte counts. No account/track IDs, cookies, proof material,
script source, or media URLs are logged. Reference source was read for behavior;
no third-party implementation was copied.

## Implemented September 24

Authenticated High preparation starts after a 300 ms shell delay. Proof and
anonymous script preparation overlap; the exact timestamp/script/profile pair
is reusable while fresh, capped at 30 minutes. The aligned authenticated player
request and media probe remain in every fresh resolution. Session generations
reject late preparation, and rejection discards proof/preparation and forces
fresh discovery once. Public code is independent of session credentials.

A dedicated anonymous URLSession now has an 8 MiB memory / 64 MiB disk URLCache.
It uses `useProtocolCachePolicy` for public allowlisted JavaScript only. HTTP
Cache-Control, Expires, validators and revalidation determine disk reuse;
no-cache/no-store/Set-Cookie/Vary:* prohibit prepared-state freshness. Headers
also cap the in-memory reuse deadline. Watch discovery remains uncached and
runs again after restart; code URLs are discovered afresh. An explicit stale
script recovery bypasses the HTTP cache. This follows Apple's
[URLCache guidance](https://developer.apple.com/documentation/foundation/accessing-cached-data)
and [RFC 9111](https://www.rfc-editor.org/rfc/rfc9111.html).

Simulator sample after prewarm: first verified progress **1.686 s** (baseline
2.943 s), warm return to High **0.571 s** (baseline 1.872 s). Warm resolution was
about 282 ms. These are individual samples, not latency percentiles or device
claims. The High canary retained unbuffered far seeks, pause/resume and profile
switching. On a subsequent new app process, diagnostics reported
`player_script http_cache_hit=true`; that High canary also passed.

Encoded track caching and explicit downloads are described in ADR 0007.
A completed High download played and sought from its local file with Offline
Only enabled, with local artwork and catalog restoration confirmed. Formal
tests remain deferred, and no new phone deployment was performed overnight.