DevOps by Default Blog

Radiophonia 1.3.0: Home Media Servers, About This Song Without Guessing, and an fMP4 HLS Proxy


Radiophonia 1.3.0 is the release where the app connects to the rest of your music and tells you the story behind what is playing. It adds Home Media Servers (DLNA / UPnP, Subsonic / Navidrome, and Jellyfin) inside the existing Library tab — including on Google TV — adds About This Song notes right over the blurred full-screen cover, teaches the local stream proxy to relay fragmented MP4 (fMP4) HLS streams, and fixes a batch of platform-specific bugs across Intel Macs, iPhone/CarPlay, Android Auto, and Google TV.

Radiophonia 1.3.0 architecture — home media servers and live radio flowing into the shared audio engine, and MusicBrainz/Wikidata/Wikipedia song notes flowing out

The Problem

Giving a listener something worth reading about the track currently playing sounds simple until you try it on real radio metadata:

  1. Name-only search collides constantly. Search Wikipedia for "Sam Phillips" and you get the founder of Sun Records instead of the singer-songwriter behind Martinis & Bikinis. Search for "Nirvana" and you have a coin toss between the 1960s British psychedelic band and Seattle.
  2. Radio metadata is noisy. Stations send "Spandau Ballet - True (Radio Edit)", "Sam Phillips - Same Changes (1994)", or "Phil Collins and Marilyn Martin - Separate Lives". History entries store the full ICY stream title ("Led Zeppelin - Kashmir") in songTitle even when artist is also populated.
  3. MusicBrainz’s top search hit isn’t always the studio recording. When we probed Led Zeppelin - Kashmir live against MusicBrainz, the very first score=100 recording returned was a 2002 Japanese bootleg (The Complete Earls Court Arena Tapes, status: "Bootleg"). Bootleg recordings rarely have a work relation to Wikidata, so picking it caused one of the most famous rock songs in history to miss its Wikipedia article.
  4. Rate-limit errors look like misses if you aren’t careful. MusicBrainz enforces 1 request/second and answers HTTP 503 when busy. Early on, _getMusicBrainzJson returned null after exhausting retries — which the caller treated as “not found” and cached in Hive for 7 days. A single busy-server burst turned into a week of false negatives.

The Solution

SongNotesService never performs a bare Wikipedia title search. Every lookup goes through a strict MusicBrainz ID chain, with a hard confidence gate (score >= 85, normalised artist + cleaned title match):

  1. Search & canonical ranking: Queries /ws/2/recording (limit=15) after stripping edition suffixes ((Radio Edit), (2012 Remaster), (1994), feat. ...) without harming real parentheticals like (I Can't Get No) Satisfaction. Candidates are ranked by release quality: Official studio albums and singles score well above Bootleg, Live, Compilation, and video recordings.
  2. Single-round-trip recording fetch: Fetches /ws/2/recording/{id}?inc=work-rels+work-level-rels+artist-rels+place-rels+url-rels+artists+releases+genres. That single call brings back the linked MusicBrainz work (and its Wikidata QID), the best studio release-group, the artist MBID, and all CC0 track credits/genres/recording studios.
  3. Fallback chain: song (work) → album (release-group) → artist → CC0 MusicBrainz Track Facts. For Wikipedia steps, Wikidata’s compact wbgetentities&props=sitelinks&sitefilter=${lang}wiki|enwiki (~170 bytes) resolves the listener’s device language first with English fallback, then MediaWiki prop=extracts|info&explaintext=1 fetches the full article and strips trailing boilerplate (References, External links, See also) and empty table-only sections (Charts, Certifications).
  4. Wikimedia Commons inset photos: A best-effort call to Wikipedia’s REST page/media-list/{title} endpoint fetches article photos, filters strictly to showInGallery: true and /wikipedia/commons/ (skipping fair-use local uploads like single covers already shown behind the panel, plus .svg/.gif UI icons), remaps section_id past stripped empty sections, and renders them as compact inset cards inside the matching section.
  5. Zero-extra-call CC0 fallback: When neither song, album, nor artist has a Wikipedia article (common for deep cuts and indie releases), _buildMusicBrainzFacts formats the already-fetched recording credits — original album, release year, duration, top genres, writers, producers, performers with instruments, engineers, and recording studio — into a clean From MusicBrainz, CC0 · Track facts card (requiring at least 2 distinct facts so sparse records still return notFound).
  6. Honest error handling: Persistent MusicBrainz 503/429 throws _TransientErrorException, returning SongNotesResult.error() (uncached, with a Try again button) instead of poisoning the 7-day notFound cache. A v2| cache-key bump automatically bypassed any stale pre-fix misses.
  7. Privacy by default: Lookups run only when the listener presses “i” (on Now Playing, the full-screen cover, or History). An opt-in, device-local setting (Check for notes on each track, off by default) checks each track automatically and shows “i” only when notes exist.

About This Song on Android — blurred full-screen cover behind the dark translucent reading panel, disambiguating singer-songwriter Sam Phillips via MusicBrainz ID

The Lesson

An entity-lookup pipeline is only as honest as its failure modes. Fixing bootleg ranking and stopping 503s from being cached as notFound took our live hit rate on real radio logs from 50% to 100% — without adding a single paid API or key.

Home Media Servers: Three Protocols Behind One Queue

The Problem

Listeners with music on a home NAS or self-hosted server don’t all run the same stack: some run DLNA / UPnP (MiniDLNA, Plex, Jellyfin DLNA), some run Subsonic / OpenSubsonic (Navidrome, Airsonic), and some run Jellyfin. Each has a completely different discovery, auth, and browsing model — UDP SSDP multicast + SOAP/DIDL-Lite XML for DLNA, salted MD5 token auth for Subsonic, and API-key user views for Jellyfin.

Two platform constraints complicated things further:

  • iOS multicast gating: Sending UDP SSDP discovery packets on iOS requires Apple’s com.apple.developer.networking.multicast entitlement (requested from Apple; pending approval). Until approved, iOS must cleanly allow adding servers by address without failing silently.
  • Transient network handoffs: A phone stepping from one Wi-Fi access point to another (or briefly onto mobile data) loses reachability to a LAN server for a few seconds. Treating the first failed request as fatal killed the entire queue with "Cannot play from…".

The Solution

Every protocol sits behind one MediaServerClient interface (media_server_dlna.dart, media_server_subsonic.dart, media_server_jellyfin.dart), managed by MediaServerService and persisted in a device-local media_servers Hive box (never synced).

  • One-shot credential exchange: Subsonic and Jellyfin passwords are used once at sign-in to obtain a token and are never stored. Because media-server stream URLs carry auth tokens, AppLogger.mask scrubs tokens before anything reaches the console or the in-app debug log.
  • Reusing the Library queue: A remote server track is just a LocalTrack with streamUrl set (filePath becomes an identity URI, mediaserver://<server>/<item>). That gave us Now Playing, lock-screen controls, shuffle, repeat, full-screen covers, and History logging (with album and release year) for free.
  • 30-second server wait: When a remote track fails to load due to a transient network change, the player now waits up to 30 seconds for the server to become reachable again before failing — while still failing promptly when the host is up and refuses the connection.
  • Google TV Library tab: Previously hidden on TV because TVs have no local file picker, the Library tab now appears on Google TV showing the Network source, and LocalMediaScreen swaps touch-only drag handles and Dismissible swipes for a D-pad-focusable Track actions menu (Move up, Move down, Remove from queue).

The Lesson

Protocol adapters are cheap when they terminate at an existing domain model. Making a server track a LocalTrack with a streamUrl avoided duplicating the entire playback, queue, and history pipeline.

fMP4 HLS in StreamProxyService: When .ts Assumptions Break

The Problem

Our localhost stream proxy (StreamProxyService) already relayed HLS radio streams — assuming MPEG-TS (.ts) segments that can be concatenated cleanly at segment boundaries. Modern AAC HLS radio streams increasingly ship fragmented MP4 (fMP4): playlists declare #EXT-X-MAP:URI="init.mp4" followed by .m4s media fragments.

Without the ftyp/moov initialisation segment prepended, decoders reject .m4s fragments outright; late-joining sockets (or reconnects) miss the init segment entirely; segments larger than 512 KB were truncated by a fixed buffer cap; and teeing .m4s into an .aac recording produced an unplayable file.

The Solution

  • Parsed #EXT-X-MAP in the HLS relay and cached each init segment per sequence.
  • Updated the progressive pump to prepend init.mp4 to both the first client and every late-joining playback socket, handle >512 KB fragments intact, and pace live fragments smoothly.
  • Added transient HTTP 502 segment retry so error bodies are never cached as audio.
  • Updated RecordingService to tee init.mp4 followed by whole .m4s fragments into .m4a files.
  • Verified with 15/15 unit & emulator tests on an Android API 35 emulator.

The Lesson

Fragmented MP4 is stateful at the byte-stream boundary: every new reader — whether a playback socket or a recording file — needs its own init.mp4 header before the first fragment.

Platform Rough Edges: Intel Macs, Audio Focus, and D-pad Focus Traps

A few nasty platform-specific issues surfaced and were pinned down with regression tests:

  • Intel Mac Impeller smearing: On Intel Mac GPUs (reproduced on a 2019 16-inch MacBook Pro, UHD 630 + Radeon Pro 5300M), Flutter’s Impeller renderer smeared text and icons into long diagonal streaks across Settings and Podcasts while repainting continuously. Radiophonia now opts Intel (x86_64) macOS builds back into Skia while keeping Impeller on Apple silicon.
  • iOS / CarPlay & Android Auto audio focus: iOS used to claim the audio session at launch (stopping whatever the car radio was playing) and ignored untyped interruption-began notifications, leaving the UI showing “playing” over silence after a call or Siri. On Android, a refused audio-focus request was retained as “granted” forever in audio_session, leaving Android Auto silent until another app played; and Bluetooth speakers disconnecting their HFP call profile seconds after A2DP paused music the listener had just resumed. All three are fixed and covered by tests.
  • Tapping a playing item shouldn’t stutter the stream: Tapping an already-playing station or podcast episode in a list used to call play() again, tearing down and reconnecting the stream. On touch and desktop, selectStation and PodcastEpisodeTile now open full-screen Now Playing via NowPlayingBar.showNowPlayingNotifier instead (Android TV retains the centre-button play/pause toggle per TV-PC).
  • Three Google TV D-pad traps caught by widget tests:
    1. Adding "i" below Sleep Timer and Equaliser in artwork-side-actions caused a 12 px vertical RenderFlex overflow in 16:9 landscape/TV mode — fixed by replacing the fixed SizedBox height with ConstrainedBox(minHeight: ...).
    2. SongNotesOverlay._handleKey unconditionally consumed arrowDown/arrowUp even when !_scrollController.hasClients, blocking D-pad focus from reaching the Try again button in error/offline states. Now arrow keys are only consumed when a scrollable article is mounted, and _tryAgainFocusNode requests focus automatically on TV error states.
    3. Closing the notes overlay with Back left focus dangling on the full-screen cover (because Focus(autofocus: !showingNotes) doesn’t re-fire on an already-mounted widget). An explicit _coverFocusNode.requestFocus() in _closeNotes() restores focus so Select immediately closes the cover.

By the Numbers

  • 1,624 Flutter unit & widget tests passing (up from 1,035 in v1.0.0), zero analyzer issues
  • 3 home media server protocols (DLNA / UPnP, Subsonic, Jellyfin) behind 1 MediaServerClient interface and the existing LocalTrack queue
  • 1 MusicBrainz recording call carrying both the work’s Wikidata link and CC0 track credits/genres/studios
  • 0 new API keys or paid backends required for About This Song
  • 30 s transient network-handoff grace period for home media server tracks
  • 7 direct-download artifacts (Android APK, Windows MSIX + Portable, macOS universal DMG, Linux x64 + ARM64 AppImage, Web bundle) plus 3 app stores (Google Play, App Store / Mac App Store, Microsoft Store)

Lessons

  1. Test the failure path as hard as the happy path. Both the MusicBrainz 503-cached-as-notFound bug and the Google TV "Try again" focus trap only showed up when things failed.
  2. Focus is state, not a one-time autofocus flag. On Google TV, every overlay transition (loading → error, error → loaded, notes → cover) needs an explicit focus handoff.
  3. One canonical domain model scales better than parallel pipelines. Routing DLNA, Subsonic, and Jellyfin tracks through LocalTrack meant every surface — Now Playing, History, lock screen, CarPlay/Android Auto metadata, and Google TV — worked together from day one.

Radiophonia 1.3.0 is available from radiophonia.app (including the updated web app at radiophonia.app/live/). Direct-download artifacts are published on the Radiophonia v1.3.0 release page.