This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Architecture

The layering, the domain models, and the rule every feature follows.

The shape of it

Orpheus is organised by feature, and each feature by layer. There is no models/, services/, widgets/ split — a change to how lyrics work touches one directory, not four.

flowchart TD
    P["presentation<br/><small>widgets, screens</small>"]
    A["application<br/><small>controllers, state</small>"]
    D["domain<br/><small>models, interfaces</small>"]
    DA["data<br/><small>files, tags, network</small>"]
    DI{{"core/di/providers.dart<br/><small>the single composition root</small>"}}

    P --> A
    A --> D
    DA -.implements.-> D
    DI -.binds.-> DA
    DI -.binds.-> A

    classDef pure fill:#4a6fa5,stroke:#2c4368,color:#fff
    classDef edge fill:#7a5c9e,stroke:#4a3560,color:#fff
    classDef root fill:#3f6b4f,stroke:#264530,color:#fff
    class D pure
    class DA edge
    class DI root

The rule that matters: domain has no Flutter and no IO. It is models and interfaces. data implements those interfaces at the outward edges — the filesystem, the tag reader, the playback engine, the network. Nothing in domain knows any of them exist.

That is what makes the whole test suite run without a real audio engine, a real filesystem or a real network: every outward dependency is an interface bound in one place, and a test overrides the binding.

The features

FeatureWhat it owns
libraryRegistering folders, scanning them, the catalog, cover art
playbackThe queue, the engine, the player screen, the spectrum bars
lyricsFinding a track’s words, and reading along with them
statsThe play threshold, the history, and the rankings
shellThe frame: navigation, the playback bar, preferences

The library model

What a scan produces, and what every screen in the music area reads from.

classDiagram
    class MusicCatalog {
        +List~MusicEntry~ entries
        +DateTime? scannedAt
        +bool isStale
        +Map~String, MusicEntry~ byPath
        +bool isEmpty
        +entryFor(AudioFile) MusicEntry
        +entryAt(String path) MusicEntry?
    }

    class MusicEntry {
        +AudioFile file
        +TrackMetadata metadata
        +String? albumArtistOfRecord
        +String? album
        +String? artist
        +String? albumArtist
    }

    class AudioFile {
        +String path
        +int sizeInBytes
        +DateTime modifiedAt
    }

    class TrackMetadata {
        +String? title
        +String? artist
        +String? albumArtist
        +String? album
        +List~String~ genres
        +int? track
        +int? disc
        +int? year
        +Duration? duration
        +String? coverId
    }

    MusicCatalog "1" *-- "many" MusicEntry
    MusicEntry "1" *-- "1" AudioFile
    MusicEntry "1" *-- "1" TrackMetadata

Three things in that model are worth explaining, because each exists to fix a real bug rather than to be tidy.

byPath is built once and lazily. The player asks “what is this file?” for every track it opens and every frame the bar draws, and a linear search of the whole library per frame is what that becomes without an index.

isStale marks a catalog read back from a document another version wrote. It is refused rather than half-read, so it holds nothing, and startup scans it whether or not the owner asked for a scan at every launch — otherwise an upgrade that changed the document would leave that owner with an empty library.

albumArtistOfRecord is how a compilation stays one record. Half-tagged libraries are the norm, so where a file carries no album-artist tag the answer is worked out across the whole record rather than falling through to the performer — which is what keeps a rap album with a guest on every track out of the artist list twelve times over.

The outward edges

Every one of these is an interface in domain with an implementation in data and a binding in the composition root. The right-hand column is what a test gets instead.

classDiagram
    direction LR

    class CatalogStore {
        <<interface>>
        +read() Future~MusicCatalog~
        +write(MusicCatalog) Future~void~
        +clear() Future~void~
    }
    class MediaPlayer {
        <<interface>>
        +Stream~PlaybackStatus~ status
        +open(String path, Duration startAt) Future~void~
        +play() Future~void~
        +pause() Future~void~
        +seek(Duration) Future~void~
        +setVolume(double) Future~void~
    }
    class LibraryScanner {
        <<interface>>
        +scan(List~String~ folders) Stream~ScanEvent~
    }
    class MediaSession {
        <<interface>>
    }

    JsonCatalogStore ..|> CatalogStore
    InMemoryCatalogStore ..|> CatalogStore
    MediaKitPlayer ..|> MediaPlayer
    FakeMediaPlayer ..|> MediaPlayer
    IsolateLibraryScanner ..|> LibraryScanner
    ScriptedScanner ..|> LibraryScanner
    AudioServiceMediaSession ..|> MediaSession
    SilentMediaSession ..|> MediaSession

SilentMediaSession is not only a test double. It is the honest answer on the two desktop targets, which have no notification and no lock screen — the Android session sits behind the same interface and is bound only there.

The flows

1 - Finding a track's words

The flow that reaches a lyrics service, and the order that governs it.

The order is the feature

It never varies, and every part of it is a rule written down in the specifications rather than a decision made in code:

  1. What this machine holds. A .lrc beside the track, then the track’s ID3 SYLT frame, then its lyrics text tag. Whatever these hold is the answer, and nothing else is asked.
  2. Only then, a lookup — and only if the owner has left it on.
  3. A sheet that came back is written beside the track as a .lrc, so the next launch finds it at step 1 and asks nobody anything.

The sidecar outranks both tags deliberately: it is the one of the three an owner can write, correct and delete with a text editor and no help from this application. Of the two tags, the timed frame outranks the text one, because a file carrying both was written by somebody who put the timed copy in SYLT.

The flow

sequenceDiagram
    autonumber
    actor Owner
    participant Panel as LyricsPanel
    participant Ctrl as LyricsController
    participant Local as FileLyricsSource
    participant Remote as LrclibLyricsSource
    participant Side as FileLyricsSidecar

    Owner->>Panel: presses the lyrics control
    Panel->>Ctrl: build()

    Ctrl->>Local: of(path)
    Note over Local: .lrc beside it →<br/>SYLT frame →<br/>lyrics text tag
    alt this machine has the words
        Local-->>Ctrl: Lyrics
        Ctrl-->>Panel: Lyrics
        Note right of Ctrl: nothing is asked of anybody
    else nothing here
        Local-->>Ctrl: null
        alt the lookup is turned off
            Ctrl-->>Panel: null
            Note right of Ctrl: nothing leaves the machine
        else the lookup is on
            Ctrl->>Ctrl: build a query from the catalog
            Note over Ctrl: artist + title required;<br/>record and length if tagged
            Ctrl->>Remote: find(query)
            Remote->>Remote: exact match, with the length
            opt no exact match
                Remote->>Remote: search, then rank the candidates
            end
            alt a sheet came back
                Remote-->>Ctrl: RemoteLyrics
                Ctrl->>Side: write(path, text)
                Side-->>Ctrl: landed, or refused
                Ctrl-->>Panel: Lyrics
            else nothing found, or the network refused
                Remote-->>Ctrl: null
                Ctrl-->>Panel: null
            end
        end
    end

    Panel-->>Owner: the words, or "no lyrics for this track"

What leaves, and what does not

The query carries the track’s artist and title, with its record and length where the tags give them. That is what is printed on the sleeve.

It does not carry the file’s name, its path, the library, what else is on the machine, or anything that persists between requests — there is no account, no key and no identifier of any kind. The service needs none, which is why it was the one chosen.

A track whose tags do not give both an artist and a title is not looked up at all. A lookup on a title alone is a guess between every recording that shares the name, and a file tagged that poorly is exactly the one whose words would come back belonging to somebody else’s song.

Choosing between answers

The exact endpoint is asked first, with the length — which is what separates the studio take from the live one, since the two share a title and an artist and share nothing about when a line is sung.

Where that misses, a search follows, and its candidates are ranked here rather than taken in the order they arrive:

flowchart LR
    A[candidates] --> B{timed?}
    B -->|yes| C[+4]
    B -->|no| D[+0]
    C --> E{length within 2s?}
    D --> E
    E -->|yes| F[+2]
    E -->|no| G[+0]
    F --> H{artist matches exactly?}
    G --> H
    H -->|yes| I[+1]
    H -->|no| J[+0]
    I --> K[highest score wins]
    J --> K

Getting that ranking wrong is not a cosmetic failure — it puts somebody else’s words on the owner’s track.

Nothing here is ever a failure

A 404, a timeout, a captive portal, a body that is not the JSON it claimed, a refused write: every one of them ends at the panel saying this track has no words. That is where the owner already was, and it is not a thing they can act on. A lookup is a convenience over a track that already had nothing.

The sidecar

The .lrc written beside the track is the only file Orpheus ever writes into a music folder, and the rules around it are what keep that defensible:

  • One file, in the folder the track is already in. The audio file is not even opened.
  • Never a replacement for a .lrc that is already there — that file is the owner’s answer, and this only ever fills a gap.
  • Written through a temporary file and renamed into place, so a process killed mid-write leaves either no sidecar or a whole one, never half of one the parser would read as truncated.
  • A refusal is reported, not thrown. Read-only mounts, network shares and Android’s scoped storage all refuse it, and none of them is a reason to withhold words the panel already has in hand.

On Android that refusal is the ordinary outcome rather than the exception: scoped storage grants read access to media and nothing that would let a process write next to the file it just read. The words show for the session; the saving is lost.

2 - Scanning a library

Why a re-scan of an unchanged library is nearly free.

What a scan is

A scan walks the folders the owner registered, reads the tags out of every audio file it finds, extracts cover art, and writes the result as a single JSON document beside the settings. That document is the library: it is read once at launch and held in memory for the run.

Everything expensive about that is avoided wherever it can be, because on a library of eleven thousand tracks the naive version makes every launch stutter.

sequenceDiagram
    autonumber
    participant App as ScanController
    participant Iso as scan isolate
    participant FS as filesystem
    participant Tags as tag reader
    participant Store as JsonCatalogStore

    App->>Store: read()
    Store-->>App: the catalog from last time
    Note over App: on screen before a scan starts

    App->>Iso: scan(folders, previous catalog)

    loop each registered folder
        Iso->>FS: walk it
        loop each file
            Iso->>FS: stat the file
            alt same size and timestamp as last scan
                Note over Iso: tags carried over
            else new, or rewritten
                Iso->>Tags: read tags and cover
                Tags-->>Iso: TrackMetadata
            end
        end
    end

    Iso-->>App: ScanEvent stream (progress, then the catalog)

    alt the scan changed something
        App->>Store: write(catalog)
    else nothing added, removed or retagged
        Note over App,Store: not rewritten —<br/>encoding megabytes to<br/>produce the file already there
    end

The two savings

An unchanged file is carried over, not read. Every scan stats every file — the one at startup included — and a file with the same size and the same timestamp as last time keeps the tags the catalog already holds, so only the files that are new or were rewritten go to the tag reader. The stat is the cheap part, and it is what makes a file a tagger rewrote in place show up: that changes the file’s own timestamp and not its folder’s, and it is the change an owner makes most.

The catalog is not rewritten when nothing changed. A scan that added, updated and removed nothing carries every entry over from the stored document, so writing it back encodes several megabytes to produce a file identical to the one on disk.

Off the interface’s isolate

Encoding and decoding happen on an isolate. This costs more work in total — spawning is not free, and the entries are copied back — and the point is where the work lands. The interface’s isolate pays for the message rather than for the parse, and goes on drawing through it.

Startup is never gated on a scan

The library from the last scan is on screen before a new scan is started. A first launch shows an empty library and an invitation to add a folder; every launch after that shows what was there last time, and the scan updates it underneath.

Cover art

Covers are cached by the hash of their own bytes, in a directory beside the catalog. That makes the cache proportional to distinct pictures rather than to files — a twelve-track album contributes one picture, not twelve — and it means two records that happen to share artwork share one cached file.

3 - Playing something

The states a player can be in, including the two that are about failure.

The queue

Anything playable produces a queue: a track, a record, an artist, or the whole library shuffled. The queue knows what kind of thing it came from, which is what lets the player say what is playing rather than only which file.

classDiagram
    class PlaybackQueue {
        +List~AudioFile~ tracks
        +QueueKind kind
        +String? label
        +int index
    }
    class QueueKind {
        <<enumeration>>
        track
        album
        artist
        playlist
    }
    class QueueRepeat {
        <<enumeration>>
        off
        all
        one
        +next() QueueRepeat
    }
    class AudioPlaybackState {
        +PlaybackQueue queue
        +AudioStage stage
        +PlaybackStatus status
        +QueueRepeat repeat
    }

    AudioPlaybackState *-- PlaybackQueue
    AudioPlaybackState *-- QueueRepeat
    PlaybackQueue *-- QueueKind

label is carried but never worded here. The domain has no localized strings, so what an unnamed record is called is a presentation decision made once, on the way to the screen.

The stages

stateDiagram-v2
    [*] --> idle

    idle --> starting: something is played
    starting --> playing: the engine opened it
    starting --> offeringResume: a resume point exists
    offeringResume --> playing: resume, or start over
    playing --> idle: stopped

    starting --> allFailed: every track refused to decode
    allFailed --> starting: something else is played
    allFailed --> idle: stopped

    note right of offeringResume
        A resume point is per track,
        and it is offered rather than
        applied — landing mid-song
        with no explanation is worse
        than asking.
    end note

    note right of allFailed
        Not "an error". A queue whose
        every file is unplayable is a
        state the screen has to show,
        and a single bad file is
        skipped rather than fatal.
    end note

The stage worth noticing is allFailed. A single file that will not decode is skipped and the queue moves on — a corrupt track in the middle of a record should not end the record. It is only when nothing in the queue could be opened that the player has something to say, and then it says it rather than sitting silently on a stopped transport.

Position, and what it costs

The engine reports its position several times a second. Everything that follows the music is driven from that one stream: the progress bar, the spectrum bars, and the lyric line that is lit.

The lyric lookup for “which line is being sung at this moment” is a binary search rather than a walk, for exactly that reason — it is asked on every position report for as long as a track plays.

The spectrum bars

The bars on the player are not decoration and not a random animation. They are the spectrum of the recording, measured from its own samples by the same engine that plays it, analysed once per track and cached against a key carrying the file’s path, length and modification time.

Until that analysis lands — the second or so after a track starts, and forever for a file that could not be decoded — a stand-in is drawn, derived deterministically from the track’s path so it is stable rather than jittering between frames.

flowchart LR
    A[track opens] --> B{analysed before?}
    B -->|yes| C[read the cached spectrum]
    B -->|no| D[draw the stand-in]
    D --> E[decode and measure, off the interface isolate]
    E --> F[cache it]
    F --> C
    C --> G[bars follow the music]
    D --> G

Keeping playing on Android

A foreground service is the only way Android lets a process keep making noise once it is no longer on screen. Orpheus asks for it with the type that says what for — mediaPlayback — and the notification and lock-screen controls come with it, carrying the sleeve and the transport buttons.

Audio focus arrives through the same seam: the phone call that should pause playback, and the headphones pulled out of the socket that should too.

Both sit behind the MediaSession interface, with a silent implementation bound on the two desktops — which have no such thing, and where a silent answer is the honest one rather than a stub.