Android's sqflite reads each result row through a cursor window of about
2 MB, so a saved queue whose media_json passes it (roughly 4,000 to 6,000
songs) could not be read back: cold start, Android Auto start and Resume
did not restore it, the Home mixes hint failed, and Library cover pruning
was skipped while such a session existed.
Readers now select the text only when it fits 512 KB, as one read as
before. Longer text is read in one transaction as 512 KB pieces of
substr(CAST(text AS BLOB)), joined, and decoded (UTF-8 or the database's
UTF-16) together with its JSON on another isolate. This covers the active
session, the Resume archive and the cover reference scan. The stored data
is unchanged, so every build still reads and writes it.
A queue write with 64 or more new songs encodes them on another isolate.
If that isolate could not start, every such write failed, and so did each
retry. The writer now encodes those songs on this isolate instead.
A dismissal reset the stored queue revision as soon as it was requested,
so a position save queued before it rewrote the whole row just before the
row was archived. The revision now resets when the dismissal runs, and that
position save stays a scalar update.
The Android background playback integration test's session store takes
the new savePlaybackSession signature, which it no longer matched.
Every queue change built a map per song and ran jsonEncode over the whole
saved queue on the UI isolate, then sent the text through the sqflite
channel as a string. In a 5,000-song queue one added song encoded all
5,001 songs (1.6 MB); 20,000 songs took about 100 ms of JSON encoding per
edit on a desktop host.
The writer now keeps each song's encoded JSON (songs are immutable) and
joins the cached bytes into the same media_json text. A single-song change
encodes one song (298 bytes in the 5,000-song test), and a remove, move or
shuffle encodes none. A new or restored queue with 64 or more songs to
encode does it on another isolate. The list reaches SQLite as UTF-8 bytes
stored as the same TEXT through CAST, so earlier builds read it unchanged
and the channel carries one copy instead of a string conversion.
A queue write that has not started yet takes the newest snapshot, so rapid
edits store once. A position save now applies only to the row of its own
queue, so a failed queue write no longer leaves the older queue paired
with the newer index.
With FFmpegKit now loaded on the first Dart call, a download that
finalizes before any Dart FFmpeg use is the usual order. The finalizer's
complete-callback filter then read a null callback and forwarded to
nothing, and the plugin's later registration replaced the filter. If the
read and the write straddled the registration, the filter forwarded to
null until the process restarted.
The plugin now exposes ensureGlobalCallbacksRegistered(), which registers
the global callbacks on the calling thread (loading FFmpegKit if needed),
waits for a registration already in progress and throws a load failure
to its first caller. The background load uses it too, and the finalizer
calls it before wrapping, so the filter always wraps the plugin callback
and is never replaced. The finalizer runs on worker threads, so the main
thread still never waits for the load.
The host-JVM main looper stand-in is now a thread named main that the
tests post calls through, and replies are checked against it: draining
the waiting calls on the loader thread instead of posting them, removing
the registration lock, or making the new method a no-op each fail a
test. No startup cost change; the ST1 gain is unchanged.
The FFmpegKit plugin registered its global callbacks in
onAttachedToEngine. The first FFmpegKitConfig access runs its static
initializer, which loads libffmpegkit.so and its dependencies (20.6 MB
for arm64-v8a, libavcodec.so alone 11.5 MB, measured in the 2.2.3 AAR).
So every Android cold start, media button start and Android Auto start
mapped and relocated them on the main thread while the shared engine
attached plugins, before Dart main, although most launches never use
FFmpeg.
The first method call of any engine now starts the registration on the
plugin's executor. Calls that arrive before it finishes wait in arrival
order and then run on the main thread with the callbacks registered, so
they get the same replies; the main thread never waits for the load. A
failed load answers every call with notImplemented, the same
MissingPluginException Dart got from the channel without a handler that
the failed attach left, and is logged once.
Starting the load at attach on a background thread would not help: the
registrant attaches JniPlugin a few plugins later, and its static
initializer calls System.loadLibrary on the main thread, which waits for
Runtime.loadLibrary0's lock and bionic's dlopen lock while FFmpegKit
loads.
Host JUnit tests (stand-ins for four Android classes, one JVM per test
class) fail on the old code: attach loaded FFmpegKit on the attaching
thread, and a failed load threw out of attach. The cold start gain needs
a release build on a device; the unit report describes how to measure it.
The Windows media session sent setStatus and setTimeline through
flutter_rust_bridge into WinRT for every playback state, twice a
second while playing, although the status rarely changes and Microsoft
suggests the timeline about every 5 s plus on state changes.
SmtcAudioService now skips a status the controls already have, and
sends the timeline when the status or speed changes, on a seek or jump
(the position departs from the last timeline advanced at its speed by
more than 1 s, as in MPRIS), on any paused position change, with every
media item, and otherwise every 5 s while playing (owner-approved
DESKTOP D6 c). A failed status or timeline update is sent again with
the next state.
Twelve seconds of 500 ms states with one media item: setStatus calls
go from 25 to 1, setTimeline from 26 to 4. Between updates the flyout
shows the last timeline or advances it itself.
The darwin plugin read the cover file into a new image and a new
MPMediaItemArtwork on every setMediaItem (two to four per song), and
updateNowPlayingField counted a null field (the app sends no isLive,
and some songs no album) as changed on every call, so every media item,
even an unchanged one, reassigned MPNowPlayingInfoCenter's info: an
IPC to the system media daemon and a Control Center redraw.
setMediaItem now reuses the artwork while the art file keeps its path,
device, inode, size and modification time; a null value equals a
missing field; and stopService empties the retained fields with the
center, so the next update sends them all again.
A macOS harness driving this file against the FlutterMacOS framework,
counting setNowPlayingInfo: calls: a media item, a state and three
identical media items went from 5 publishes to 2, with the artwork
object reused; a duration change, a rewritten cover and the same item
after stopService still publish once each. Artwork reuse alone kept 5;
without the stopService reset the item after a stop published nothing.
Applies to iOS and macOS. Recorded in MORNYE_PATCHES.md.
audio_service kept every decoded cover in an LruCache sized one eighth
of the Java heap (16 to 64 MB) that only onDestroy emptied, so a long
shuffle session filled it after 8 to 15 covers and held it through
background playback. Its decode used a power-of-two sample size toward
512 px, so an 800 px Library thumbnail stayed 2.4 MiB and a 1000 px
cover 3.8 MiB, although the session only takes 512 px copies.
The service now keeps the current cover and the two before it
(RecentArtCache), and onTrimMemory at TRIM_MEMORY_RUNNING_LOW or above
(UI_HIDDEN and BACKGROUND on Android 14 and later) drops all but the
current one. Eviction never recycles, so the notification and session
keep what they show. Each decoded cover is scaled to 512 px with the
same createScaledBitmap call the session copy made, so the session's
512 px copies keep their pixels; the 256 px notification icon is now
scaled from 512 px (owner-approved).
Retained art goes from up to 16 to 64 MB to at most three 1 MiB
bitmaps, one after a trim. Recorded in MORNYE_PATCHES.md; JUnit
RecentArtCacheTest, and the instrumented MediaControlMetadataTest
covers the 512 px bound.
The Material full-screen cover (the default) faded into its blurred
surface through one ShaderMask over the whole cover box. A shader mask
layer renders its children offscreen at the size of their paint bounds,
so every raster of the frame, 30 times a second while playing, drew the
whole cover (about 1.4 MP on a 1080 x 2340 phone) into an offscreen
target and composited it back, although the gradient is pure white over
the top 72% of the box.
The Hero now holds two copies of the same artwork (one provider, one
decode). The rows above the fade are clipped and drawn directly; the
band from one device pixel above the first faded row down goes through
a mask layer whose rect is that band, with the same gradient laid over
the whole box and the copy clipped to the band. Both copies stay inside
the Hero and the lyrics AnimatedOpacity, so the opening flight and the
lyrics fade keep their look and timing.
Measured in the layer tree at 1080 x 2340, 2.625x: the masked rect drops
from 411 x 499 dp to 411 x 140 dp (28.1% of the box, 72% less offscreen
area). Captures against the old tree at four sizes and dprs, three covers
(opaque, noise, translucent noise), through opening, drag, settle,
lyrics fade and both closes stay within one level per channel, except
two levels during the 300 ms lyrics fade, where the opacity now reaches
the upper rows directly instead of through an 8-bit offscreen copy.
If the isolate that reads the cover index could not start, the read
counted as a corrupt file: the index started empty and the next save
replaced a valid file with only the new rows, orphaning the cached
covers. The read now runs inline when no worker can start. A file that
exists but cannot be read at all (an I/O error) is reported and left as
it is, with this session's changes kept in memory, so nothing is saved
before a successful read. A file that was read but is corrupt is still
reported and replaced, as flutter_cache_manager does.
The media session's art cache sent covers to the temporary default
cache until the app shell initialized the cover cache, while the rest of
the app already used the cover cache, so a cover shown by both in that
window was downloaded twice. It now always uses the cover cache on
Android, iOS and macOS (Windows and Linux keep audio_service's default),
and drops its own file check on memory hits, which the cover cache now
does itself.
The 15 minute byte budget sweep deletes cover files behind the cache
manager. Lookups through the index already check that the file exists,
but getFileFromMemory does not, so audio_service could pass the system
media session a path to a deleted cover (no art on the notification or
lock screen), and the index kept rows for the deleted files until each
was looked up again.
A memory hit now counts only while its file exists, and after a sweep
that deleted files the cache re-checks each index entry whose file is
gone (the existence check runs in a worker), which drops it from the
index and the memory cache unless a download has replaced it since.
The cover cache now keeps its index in CoverCacheInfoRepository, at the
same <support>/null.json, so a scroll over cached covers no longer
rewrites the whole index on the UI isolate per cover (see the previous
commit for numbers). Pending changes are written when the app pauses or
detaches, before a desktop quit (as an exit-request listener that always
allows the exit), after Clear cache, and on dispose.
Until the app shell's post-frame initialize() finished, instance
returned DefaultCacheManager and logged on every call, so a cover drawn
in that window (a cached Explore feed, a restored web cover, the home
widget) opened a second index and downloaded the image again into the
temporary directory (STARTUP ST8). instance is now the one cover cache
from its first use: its directory and index resolve on first use,
without delaying the first frame, and the index read runs in a worker.
initialize() was idempotent only sequentially: two overlapping calls (the
app shell and a player init) made two managers over one index, each
overwriting the other's entries. It now shares one call, and a failed
call can be retried as before.
flutter_cache_manager's JsonCacheInfoRepository re-encodes and rewrites
the whole index on the UI isolate for every touch, insert and delete,
and scans every entry per lookup. A scroll that shows covers touches one
entry per cover, so it keeps a chain of full rewrites going.
CoverCacheInfoRepository keeps the same file and JSON format (rows in id
order, the same bytes for the same rows, the same .tmp and rename), so
older and newer builds read each other's index. It reads the file in a
worker isolate, looks entries up by key, keeps each row's encoded JSON
until the row changes, and saves 1 s after an insert, delete or content
update and 30 s after a touch, or at once on flush and close.
Host numbers (JIT, test mode): a scroll over 200 cached covers in a
600-entry index rewrote the index 160 times (about 96,000 rows encoded);
now it writes nothing until the flush, which writes once and encodes the
200 touched rows. 20 inserts: 20 writes, now 1. A full rewrite of 1,000
rows held the UI isolate 2.5 to 3.5 ms; a save now takes 0.1 to 0.4 ms
there. Opening a 1,000-entry index held it 3 to 6 ms, now under 1 ms.
1,000 lookups took 6.4 ms at 20 entries, 15.6 ms at 1,000 and 450 ms at
20,000; now about 3 ms at every size.
DynamicColorBuilder asked for the wallpaper palette (or the desktop
accent) in its first build, so the first frame used the seed scheme and
MaterialApp then animated the whole theme for 300 ms into the palette,
rebuilding every Theme.of dependent about 18 times during the busiest
part of startup. The owner approved building the first frame with the
final theme, which removes that launch fade.
main now asks once the Activity attaches, alongside the other startup
calls, and waits at most 100 ms for the answer before runApp; it is
normally in by then. The wrapper builds its first frame with that answer
through a provider override; a late answer still applies with the fade,
and without a launch request the wrapper asks itself as before. The
request keeps DynamicColorBuilder's order and schemes.
Every Material launch also ran a second, invisible 300 ms fade: the
custom font provider's first answer rebuilt the wrapper, and two builds of
the same settings never give equal ThemeData. The wrapper now watches only
the font family it reads.
Host test with MaterialApp's 300 ms theme animation: the first frame now
has the palette, with 1 theme build and 1 Theme.of reader build instead
of 2 and 20 over 21 frames; with no dynamic color 1 and 1 instead of 2 and
20. Theme changes after launch still animate.
Before runApp, main awaited Android TV detection, then the orientation,
then the preference load, then the install marker, one after another,
each a round trip that queues on the Android main looper behind the
Activity's own startup.
The preference load now starts right after the binding, before the
Activity attaches: shared_preferences_android answers from an IO thread
without an Activity, as the media browser start already relies on. TV
detection and the orientation run alongside the preference load and the
install marker and are awaited just before runApp, so isAndroidTv is
still known for the first frame and iOS and desktop still apply the
orientation first.
Android phones no longer send the startup orientation: MainActivity's
onCreate sets SCREEN_ORIENTATION_PORTRAIT, which is what [portraitUp]
maps to, and the router's orientation observer sends it again on the
first page. TV keeps the call (onCreate sets fixed landscape, the call
user landscape), as do iOS, where the Info.plist allows landscape, and
desktop.
A simulated main looper (2 ms per call idle, 12 ms busy) puts runApp
12 to 92 ms earlier when the preference load had not started before
attachment, and 2 to 12 ms earlier (none on a busy TV) when the media
browser check in main had already started it.
CustomFontService.restore read the stored font, validated it and
compared its SHA-256 with the id on the UI isolate, at launch, for a
font of up to 10 MB. Import did the same for the picked file. Both now
run in Isolate.run; restore reads the file there too and gets the bytes
back without a copy.
Host test, 10 MB font: the longest UI isolate stall during restore went
from 110 ms (the whole 123 ms hash) to 5 to 11 ms. Ids, stored files and
the fallback to the theme font when a file is missing, too large or
damaged are unchanged.
A 304 answers for the image found at the start of the check. When a
prune or a Link reconcile removed that file meanwhile, the failed touch
was ignored and a missing path returned; before the ETag change the
byte comparison threw and the row got no cover until the next scan.
The lookup now throws again in that case.
Also removes saveCover, which nothing calls since cachedCover reads
covers through _saveCover directly.
Network rows have no file time, so the Library's latest sort, the
Mornye Library overview and Home Recently added order a Link source by
scannedAt, which every full scan stamps in processing order. The album
walk put the alphabetically last album on top; the search3 sync would
have put the desktop's oldest song on top, since the desktop exports
newest first.
On the search3 path each row is now stamped with the scan start minus
its index in milliseconds, so the phone shows the desktop's newest
songs first (orchestrator decision for subsonic-sync in UNITS.md).
20,000 songs span 20 seconds. Other servers keep the album walk and
its stamps.
A forced full scan of a shuffled library on a warm cache now proves
the larger cover map: 160 cover downloads for 160 cover ids, where the
old 128-entry map downloaded 230.
The Mornye search3 sync treated a page shorter than 500 songs as the
last one, so a desktop that ever capped pages lower would have synced
a truncated Library to the phone. The offset now advances by the
number of entries each page returned and only an empty page ends the
catalog, at the cost of one extra request per sync (5 instead of 4 for
the 1,200-song fixture, 1 album page and 4 song pages).
A non-empty page that brings no new id still fails the scan, so a
server that ignores songOffset cannot loop or publish a partial
Library. Video ids count as progress, so a last page holding only
videos ends normally.
The daily cover check downloaded every stale Subsonic cover in full
and compared it with the cached file byte by byte, although the Link
desktop (and many servers) send an ETag and answer If-None-Match with
304. The first rescan of a day fetched all 500 album covers of a Link
library at original size.
The ETag of a downloaded cover is now kept beside it in
<cover>.etag together with the image length. A stale check sends
If-None-Match; a 304 keeps the path and touches the modification
time, like an unchanged download did, without reading a body. A 200
follows the existing rules (same bytes keep the path, changed bytes
get a new path behind .current) and stores the new ETag. A forced
refresh, a validator for other bytes, older caches and servers
without ETags behave as before.
The validator survives restarts. The Library cover prune (Dart and
Rust) keeps it with a referenced Subsonic cover, as it keeps the
.current pointer, and the song metadata cover cache still keeps 32
covers, each with its ETag, instead of counting ETags as covers.
Older builds ignore the files and their prune removes them.
A Link rescan walked the desktop album by album: getAlbumList2 pages
of 200, then one getAlbum per album, all serial, so 500 albums cost
503 round trips. Every response of a Mornye desktop says
type "mornye", and its search3 with an empty query pages every song
with the same song objects as getAlbum (contract section 4).
The first getAlbumList2 page now decides: a Mornye desktop is read
through search3 pages of 500 songs (the isVideo filter, id dedup,
500,000 cap and "pagination did not advance" guard are kept), any
other server keeps the album walk with the same requests as before.
search3 keeps no album's songs together, so the scanner remembers
the cover of every cover id of the scan (up to 20,000) instead of
the last 128, and still asks for each cover once.
Fixture library of 1,200 songs in 120 albums: 4 requests (one album
page and three song pages) instead of 121, the same Library rows,
and 160 cover requests for 160 cover ids in shuffled song order.
Material phone and tablet collection headers (album, playlist, local and
downloaded album, folder, extension and mix pages) blurred a 1.5 MP cover
with sigma 32 on every composited frame: every scroll frame while the
header collapses and 30 frames a second while music plays, since the
mini player wave keeps drawing. The blur input never changes between
those frames; the pinned flexible space only moves it.
The header now wraps its background in SettledBlur: the first frame and
the unchanged one after it blur live as before, then a quarter
resolution image (about 0.4 MB at 1080 x 2340) is drawn until the cover,
theme, size or pixel ratio changes. Scrims, gradient and content are
unchanged.
Host test on a 411 x 891 dp phone with a ticking mini player: 91 frames
including 30 collapse frames composite the live blur 2 times instead of
91. Settled page against the live blur: mean channel difference 0.09
(light) and 0.07 (dark), largest 7 out of 255.
Impeller has no raster cache, so an ImageFiltered blur runs its offscreen
pass on every composited frame even when nothing under it changed. The
new widget blurs live on the frame its child changes, then rasterizes the
blurred child once at a quarter of the physical resolution (owner
approved for wide blurs) and draws that image until an input changes.
A frame settles it only when the live layer was retained unchanged, so a
fade or opacity animation inside a nested layer, which never reports a
repaint upward, keeps it live until it ends. A new child widget, sigma,
resolution, device pixel ratio, size or any repaint below drops the image.
Textures and platform views stay live. Images are disposed on change,
detach and dispose. It adds no frames on a still screen beyond the one
that swaps in the image.
Host tests: one image per settled input across 60 frames of movement and
a ticking sibling; each input change re-settles; a 500 ms fade settles
only after it ends; mean channel difference to the live blur 0.37 (1x)
and 0.26 (3x) out of 255, against 9.8 for a quarter smaller sigma.
The visible history membership of an open album, playlist or artist
page rebuilt on every history state change (each completion, each
coalesced index bump, each count refresh) and re-derived, for every
track, the Spotify ID candidates (a set, a lowercase pass and a URI
parse), the trimmed ISRC, the title and artist key and the lookupKey
string. Desktop pages rebuilt the lookupKey list again per build.
The request snapshot now caches its lookupKeys, the visible-membership
notifier derives each track's in-memory index keys once per request,
and it returns its previous set when neither the lookup items (which
own the indexes) nor the persisted keys changed. DownloadHistoryState
exposes its title and artist key and an index read by that key. Album,
playlist and artist pages read the cached keys.
Same sets as before: tests compare against a copy of the old per-track
matching over tricky IDs, ISRCs, case and 300 random rounds. Host, a
1,000-track page with 100 history items: a change of the lookup items
went from about 990 us to 185 us, a count or revision change from
about 990 us to 22 us, and 31 history changes read no track field.
Every AppLifecycleState.resumed reloaded the newest 100 history rows
and bumped loadedIndexVersion even when nothing had changed. On desktop
resumed follows every return of window focus, so each app switch
invalidated every DB-derived Library view (queue unions, grouped
counts, per-row exists checks, album pages) and scheduled a full Link
catalog export.
The resume handler now calls refreshFromStorage. It reads the same
snapshot but publishes it only when the count, the loaded items or the
lookup items differ in any persisted field, or a migration ran. The
native download finalizer, the only writer that runs while Flutter is
suspended, inserts its row at the top of that page, so a finished
download still publishes. reloadFromStorage keeps publishing for the
callers that reload after their own writes (conversion, Link library
jobs, batch edits, restore), which can change rows outside the loaded
page. A refresh joins a pending reload; a reload never joins a pending
refresh.
Host, 100 rows: a no-op refresh costs about 220 us (mostly row
parsing) and notifies nobody; a reload costs about 310 us plus the
Library and catalog work its revision bump triggers.
A track page or a search that was the first shadow read after a write
waited for the whole snapshot build: 124 to 440 ms on the host's Android
fixture, against 1.6 ms for a 60-song page with the per-row check. Home's
recently added shelf, the Library tab, Android Auto and Link read pages
on their own, so those reads got slower. They now use the snapshot only
when it is already current and otherwise keep the per-row check at its
old cost, without building. A page with an album completeness filter
assesses every album, so it still builds.
A failed build is now tried again only after the stamp moves, so a
persistent failure no longer costs a pairs query on every read. Its
warning, like a new one for a failing snapshot query, is logged once per
connection.
album_completeness.dart and library_search.dart need only the shadow
table name and the shadow predicate, but imported all of
sqlite_helpers.dart (dart:io, path_provider, the sqflite FFI factory)
for them. Both now live in library_shadow_sql.dart, which
sqlite_helpers.dart re-exports, so the sqlite.libraryShadowTable and
sqlite.libraryNotShadowedSql names stay the same. No behavior change.
Every Library load and summary refresh copied each ISRC and match key of
the Library to Dart again, even when nothing had been written since the
last copy, as after a reload or a History-only change.
getLookupIndex now reads PRAGMA main.data_version and total_changes()
first and returns the previous index when both, and the connection, are
the same. Any write on the Library connection or a commit by another one
fetches it again; close() drops it.
15,000 songs over FFI on the host: a fetch takes 144 ms, a reuse 0.6 ms.
Every Library read over scanned songs checked, row by row, whether a
download holds the same file: each of the row's path keys (about 40 per
song on Android) was probed against History. That check was most of the
cost of the tab counts, the album and artist pages, the Folders index,
search, the Home mix pages and the Autoplay sample, and the album
completeness filters also scanned the whole Library once per download.
LibraryDatabase now keeps the matching pairs of Library and History rows
in a connection-local TEMP table. It is rebuilt only after PRAGMA
data_version of either database (a commit by another connection) or
total_changes() (a write on this one) has moved, with DDL only, so the
rebuild itself writes no rows. Each read checks the stamp again after
its query and repeats the query with the per-row check if anything was
written in between, so results equal today's SQL. Without a stamp the
per-row check stays in use; the default SQL is unchanged.
Android key profile, 15,000 scanned songs and 5,000 downloads (host
SQLite 3.54): tab counts 302 -> 13 ms, album page 309 -> 22 ms, artist
page 250 -> 15 ms, Folders 869 -> 65 ms, Home mix pages 2.7 s -> 0.19 s,
Autoplay sample 2.2 s -> 0.40 s, Incomplete albums over 60 s -> 0.33 s.
A rebuild costs about 0.44 s there (0.02 s on the desktop profile) and
runs once per write.
macOS uses the same Darwin plugin as iOS, so its Now Playing advances a
playing state's position on its own and gains the same filter: the
local player stops sending it a full state every 600 ms. The scenario
test now checks a macOS view as well, which is the iOS one without the
foreground refresh only iOS asks for.
The app cover cache now serves media session art on Android, iOS and
macOS only, where the plugin reads the file as each song arrives. The
Windows and Linux sessions pass the file path to other programs that
read it later, and the cover cache's sweep or Clear cache can delete an
old file while its song still plays, so they keep audio_service's
default cache as before. The unused cache parameter is gone.
audio_service was initialized without a cache manager, so it made its
own DefaultCacheManager: every web cover the notification or lock
screen showed was downloaded again and stored again in the temporary
directory, beside the copy the app's cover cache already held, and its
memory never had the cover the player had just drawn, so the session
first got the song without art and again after the download.
MediaSessionArtCache resolves the app's cover cache on each call once
it is ready, and the default cache before that, so a session that
starts before the app shell (Android Auto) behaves as before. Awaiting
CoverCacheManager.initialize() in the player init instead would race
the app shell's own call and could create two managers over one cover
index. The cover cache's byte budget deletes files its memory cache
still lists, so a memory hit whose file is gone counts as a miss and
the cover is fetched again instead of reaching the OS as a dead path.
Test: with the app's cover already cached, the session's media item
carries that file and the server sees one request, not two; after the
file is deleted under the memory entry, the session fetches it again
and gets a file that exists. Same bytes, same pixels.
While a song plays, the player publishes a position update about every
600 ms, and each one went to the OS session in full: a channel message
decoded on the merged main thread, then on Android a PlaybackState
binder call to system_server fanned out to System UI, Bluetooth, Android
Auto and Wear, and on iOS a whole Now Playing dictionary over XPC. Every
client already advances the position from the last state's position,
update time and speed, so these updates told it nothing.
MediaSessionFilter sits in front of the audio_service platform on
Android and iOS. A state goes out when anything but the position
changed (playing, processing state, speed, queue index, repeat,
shuffle, errors, buffered position, captions, controls by value), when
the position is off what the OS shows by 500 ms or more while playing,
or when it changed at all while paused. The app's own listeners still
see every update. Desktop sessions are unchanged.
Apple's Now Playing takes a position only when it changes and
republishes each media item with the last state's raw position. So a
media item first sends the newest held back state and lets the next one
through, and a playing state that repeats the previous position (a load
turning ready, a stall) lets the next one through. A scenario test
feeding the same player events to a filtered and an unfiltered session
shows both the Android and the Apple view within 500 ms of today's at
every update, and exact while paused.
Measured in that 12 minute scenario (play, pause, seek, AutoMix speed,
a stall, two track changes, media items, ten minutes in the
background): 1,209 states reached the OS before, 28 now.
AudioService.synchronizePlaybackState completes at once for a held
back state and still waits for the OS on the ones it sends.
AutoMix, gapless playback and Autoplay each answer whether a position
tick would make them act by repeating the early returns of onPosition or
fill. The compiler cannot catch a branch added to one side only, so each
doc comment now says to keep the two in step.
The timer stopped after a flush that found nothing playing and nothing
pending. If another caller (statistics, Rewind, Home, mixes, Link sync)
had taken the last seconds and its write was still in flight, and that
write then failed, the batch went back to pending with no timer left to
retry it until the next playback change. The old always-on timer retried
within 10 s, so a kill in that window lost those seconds.
The recorder now counts writes in flight and is idle only when none is
left, so the timer survives until the other write settles and its next
tick retries a failure. The new test fails without the count (one write
of two) and passes on the base code and with it.
The USB direct-path test waited only 60 ms before checking that no
position was read, so the old hard-coded 200 ms poll passed it too. It
now waits 300 ms with ticks declined and expects at least three reads in
150 ms once they are wanted, which only the 10 ms interval can make. Each
half fails on its own against the old behaviour (1 read, expected 0; 1
read, expected at least 3).
The handler tick tests drove ticks with a fresh delay after each one, so
on a loaded machine the spacing grew past 225 ms and the fixed bound of
27 queries failed although the code was right. Both now bound the queries
by the measured time: at most one per 300 ms plus the first tick and the
saves. The base code still fails them (55 queries for a bound of 40, 30
for 22).
The handler flushed listening statistics every 10 s for its whole life,
so an idle app woke up six times a minute to find nothing to write. The
timer now starts when playback starts and stops after a flush that finds
nothing playing and nothing pending.
The flush keeps its 10 s rhythm while playing and still runs once more
after a pause, stop or song change to write the last seconds, so every
minute is written once, at most 10 s after it was played, as before. A
write that fails keeps the timer until a retry lands. Dispose and the iOS
lifecycle flush are unchanged.
Measured in the host test: 0 flushes over 60 s idle (6 before), 0 over
the 60 s after each pause, and the same written total (35 s, then 40 s
after a failed write is retried).
The handler polled the engine position every 200 ms, but its broadcast
gate publishes a position only once 500 ms have passed, so two of every
three platform round trips were discarded. Decks now take a `wanted`
predicate: a tick it declines is skipped without asking the platform.
The handler wants a tick when the gate would publish it (timed from when
the engine read the last published position, with 50 ms for the reply),
when the 10 s session save is due, right after any forced broadcast, and
whenever AutoMix, gapless playback or Autoplay would act on it. The tick
grid stays 200 ms, so every published position, save, AutoMix start and
gapless preparation lands on the same tick as before. Updates the plugin
requests itself (load, seek, pause, stop) still read the engine.
Measured in the host test of 55 ticks of steady playback: 20 engine
queries instead of 55 (about 1.7/s instead of 5/s), with the same
published positions and saves.
The media_kit deck started its position timer when the handler created it
and kept it until dispose, checking inside each tick whether it was
playing. On Windows and Linux (and macOS exclusive output) the music deck,
every prepared gapless deck and the desktop preview deck therefore woke
the UI isolate five times a second while paused, stopped or holding
nothing, for the whole life of the app.
The deck now remembers the interval and keeps the timer only while its
state is playing. Positions are emitted exactly as before (they were only
ever added while playing); an idle deck has no timer at all. The new test
records the periodic timers the deck creates and fails on the old code,
which had an active timer before the first source was even loaded.
The server sends catalog.changed only to phones with an open WebSocket,
and a phone closes its socket in the background. Before the skip of
unchanged catalogs the next desktop focus return pushed again and healed
such a phone within seconds; now a phone that was away when a real
change was pushed (an album downloaded on the desktop while the phone
was in a pocket) never rescanned until the next real change.
The host now remembers the phones each push reached: those connected
both before and after linkSetCatalog. When a phone connects without
having been reached, or connected during the push, the host sends
catalog.changed to that phone only ({"songs"}; phones read the type),
and remembers it. A phone that was reached and reconnects gets nothing,
so a phone going to the background and back rescans no more than once
per catalog change; one that connects after a server start rescans
once, as a focus return did before.
Applying a peer's listening totals looked up each song this device has
no key for with its own awaited query inside the statistics write
transaction (DATA-11). A first sync of a year of listening, about 3,000
songs, made about 3,000 sequential round trips while holding the write
lock the 10 s listening flush waits on.
The songs are now looked up 200 at a time with a VALUES list and the
same correlated query per song (NOCASE title and artist, newest day
first, first row), so each keeps the key it got before. The lookups
still run before the batch writes, against the same totals. Songs
without a title no longer query at all; they keep the author's key as
before.
Measured on the host (FFI, isolate, M-series Mac): 3,000 lookups took
237 to 2,016 ms one at a time and 8 to 111 ms in batches, with identical
results; the new test's apply reads 7 statements instead of 459. The
plan still searches idx_listening_title_artist per song.
Every export handed its catalog to the server, which bumps the version
and sends catalog.changed to every phone, and each phone then rescans
the whole desktop Library (NET-1). Most exports change nothing: each
return of window focus reloads history and bumps the Library revision,
and each phone song commit rescans that phone's source on the desktop,
whose network rows the exporter leaves out anyway.
The exporter now returns a SHA-256 of the song lines without the header
(generatedMs is new every time). The mapping isolate hashes each line
and the export hashes those 32-byte digests, so rows left out moving
page starts do not change it, and the UI isolate hashes about 0.6 MB
instead of the 14 MB catalog for 20,000 songs (about 4 ms instead of
95 ms on an M-series Mac). The digest covers every field the server
reads, coverPath and webCoverPath included, so a web cover copy that
arrives still reaches phones.
The host skips setCatalog when the digest equals the one the current
server read; the index, web cover prune and fetch, and phone source
rescans still run, and player.state is not re-sent for unchanged song
ids. Every started or adopted server counts as a new run, so a restart,
a rename or a server started while the last one took a catalog always
gets it.
Measured with the host tests: a Library revision bump that exports an
equal catalog calls setCatalog 0 times instead of 1, which saves each
connected phone a full rescan.
The connection editor checks a connection with a listing before saving
it. With shared SMB sessions that listing reused a live session with the
same login, and SMB sessions survive a password change on the server, so
Save could pass a check that never logged on. The editor now calls
`verify`, which retires the connection's sessions before listing; reads
in flight finish on the old session.
After a network failure, dart_smb2 caches a refused reconnect for five
minutes and repeats it for every call without asking the server. A
refusal at session or tree connect can have a path-level type
(BAD_NETWORK_NAME as notFound, NETWORK_ACCESS_DENIED as accessDenied,
INSUFF_SERVER_RESOURCES as inUse), so the session was kept and every
read of the connection failed at once while calls kept it alive. Path
answers always carry their path and connect failures carry none, so a
failure without a path now retires the session and the next call logs
on, as before shared sessions.
Tests: verify with a live session and a refused logon throws the same
exception after a second logon; path-less notFound, accessDenied and
inUse failures replace the session while the same types with a path keep
it. All four cases fail without the fix.
Every SMB listing and every proxied byte range opened its own dart_smb2
pool: a worker isolate, a TCP connect, negotiate and NTLM session setup,
then a logoff, each under the app-wide native lock. A scan reads two to
four ranges per file, so playback chunks and covers queued behind one
handshake per range request.
Listings, tag and playback reads and cover downloads now lease a session
kept per connection and login. It closes 20 s after its last lease ends,
when the connection is saved or removed (reads in flight finish on it),
when a call on it fails in a way the session may have caused
(connection, timeout, logon, state, io or unknown errors; the next call
logs on again, as before), and on dispose. Errors reach callers as they
did. Concurrent first calls share one logon and a failed logon is not
kept. Uploads, folder creation and deletes keep a session of their own.
Fake transport test: a scan of four files with two tag ranges each,
eight parallel ranges, three listings and a cover took 24 logons before
and 1 after, with never more than one native call in flight.
Loopback Samba fixture (SMB 3.1.1, encryption required), a 200-file scan
with two tag ranges per file and a 64 KiB seek every 20 ms, host under
load: before 139 s per scan, 631 worker isolates, seek median 486 ms,
max 12.7 s; after 6 to 11 s per scan, one worker for three scans, seek
median 24 to 45 ms, max 0.1 to 1.9 s.
LibraryDirectoryView rebuilt a TrackTableRow, a quality label and the id
map for every song of the open folder on each build, and an id set for
pruning the selection, so a click in a flat folder with thousands of
files walked all of them.
The view now keeps the rows and the id map while the folder's song list
and the quality label mode stay the same, and the id set while the list
stays the same. The artwork widget reads its colors from the theme, so
a theme change still repaints it.
Measured with a 3,000-song folder (widget test): a selection click
re-created 3,000 rows before and none now; a quality label change or a
reload still rebuilds them all.
QueueTab built a TrackTableRow for every loaded song on every build:
two quality-label regex parses, a Duration, a cover widget and a
playback key per row, plus the id map and the swipe-navigation lists
over all rows. The Library loads 300 songs per page, so a scrolled table
holds thousands, and a selection click, a resize frame, an inspector or
rail animation frame and every page load paid for all of them. The new
list also missed SliverTrackTable's identity cache, so the table
recomputed its ordered ids too.
Per Library mode, QueueTab now keeps the table rows and their id map
while the songs list, the quality label mode and the color scheme stay
the same, and a new list (another page loaded) reuses the rows of the
songs it keeps. The swipe-navigation lists are kept per songs list and
pinned downloads, and the songs without the pinned download rows and
the loaded ids per songs list and pinned ids, so a batch download no
longer defeats the caches. The cover widgets keep their own
embedded-cover listener, and selection and the playing row still reach
each row through selectedIds and its playback provider.
Measured with 3,000 loaded rows (new widget test): a selection click or
a resize re-created 3,000 rows before and none now; loading the tenth
page re-created 3,000 and now 300. At about 1.2 us per label (AOT) the
labels alone cost about 3.6 ms per rebuild at 3,000 rows and 24 ms at
20,000.
buildLibraryAudioQualityLabel, the grid label and the badge highlight
constructed their RegExp objects on every call. The patterns are now
top-level finals with the same sources and flags.
The Dart VM already caches compiled patterns by source, so this only
saves the per-call cache lookup: on this Mac (AOT, best of six
interleaved runs) a 20,000-row label pass went from 24.9 to 23.6 ms in
bit-depth-only mode and from 25.3 to 23.9 ms in bit-depth mode. A
comparison of the old and new policy over 435,516 inputs (modes, stored
qualities, formats, paths, bitrates, bit depths, sample rates) found no
differing label.
Before the menu items were kept between builds, every rebuild sent a
new menu, so a hot reload that edited the menu code showed the edit
right away. The kept items would otherwise stay until something they
show changed. Hot reload now drops them, as it did before.
_OrientationFade built a new CurvedAnimation on every build, and each
one adds a status listener to the fade controller that nothing removes.
The fade depends on the window size to see the rail breakpoint, so it
rebuilds on every resize frame and a live resize left one more listener
(and its CurvedAnimation) on the controller per frame for the life of
the app, each one called on every later fade.
The curve is now created once and disposed with the controller. The
opacity is the same curve of the same controller, so the fade looks the
same.
test/desktop_menu_bar_rebuild_test.dart: 20 resize frames now keep the
same opacity animation (a new one per frame before), and crossing the
rail breakpoint still fades in.
The MaterialApp builder read MediaQuery.of to copy displayFeatures and
navigationMode, a full MediaQuery dependency, so every resize frame
(60 to 120 Hz during a live resize, and every frame of the mini player
window animation) reran it and rebuilt the drop target, playback
feedback, scaffold messenger and the desktop shortcut layer. On macOS
that rebuilt the menu bar too.
The copy now lives in a small widget that reads MediaQuery in its own
build and wraps the glass preparation and the UI scaler as before, so
those two rebuild on the same changes as before while the app content
passes through unchanged.
The shortcut layer also read the window width with MediaQuery.sizeOf
from its commands. Called outside build, that still registers a
dependency, so after the first Escape or Back every resize rebuilt the
layer. It now reads the nearest MediaQuery without depending on it,
the same value at call time.
Measured in test/desktop_menu_bar_rebuild_test.dart (host): 10 resize
frames plus 10 mini player frames sent 20 menus before and 0 now, and
the shortcut layer keeps its Shortcuts widget across them on macOS,
Windows and Linux.