jukebox
All repositories: gitoria
17.7 KB
# jukebox — a network media player for the music on loreanacaramboleyo's idea (ticket jukebox#1): a player that runs directly on loreana, opens a web interface and plays the audio there. It watcheslibrary folders, scans them, keeps every tag in an mpackdb for fast browsing, shows the album cover, orders by artist, album and song,searches, plays playlists and shuffles, and can pick only the songs that were played often.**Done so far:** the scanner, the database and the JSON API (mission JB1), and **the library screens with playing in the browser (mission JB2)**:Songs, Artists, Albums, an artist, an album, Search, a Favourites filter and a player bar at the bottom. Shuffle, the now-playing overlay and counting new plays came with JB3 (see below). Not yet: playlists, keyboard keys (a Hybriel gap), a login (home network only; the server binds 127.0.0.1 unless `HL_HOST=0.0.0.0` is set).## The screens (JB2)Phone first (390 px), then desktop (1280 px), on the WorldAPI layouts theme (dark): the layouts header with the main menu (the phone's sidebar behind the toggle).- **Songs** (`/`): all 13,449 songs in one list. Sort by artist, title, album or most played; the **Favourites** button keeps the songs played at least N times(N is a field next to it, default 5) and the line under the toolbar says how many songs that is ("4,572 songs").- **Artists** (`/artists`) and **Albums** (`/albums`): by name, with a small cover. **An artist** (`/artists/<id>`) has a switch between their albums and their songs;**an album** (`/albums/<id>`) shows the cover large on top and the songs in track order.- **Search** (`/search`): one field, results while you type (the search waits 250 ms after the last key): artists and albums (at most 10 each) above, the songs below.- **Playing:** a tap on a song plays it in the media player at the bottom (a compact bar: seek line, small cover, title and artist, Shuffle, previous, play/pause, next, Repeat (JB19, no 10 s buttons); thetimes on desktop). The list the song was tapped in is the queue: the shell asks the server for the next 40 songs of that list and refills before they run out; when a songends the next one starts. The bar belongs to the shell, so the music goes on while you open other screens.- **Long lists:** the lists are the **virtual list** (`components/virtual-list`, a new shared component, README there): fixed row height 56 px, only the rows near the viewportexist (about 35), the rows come from the server 100 at a time as you scroll; the whole 13,449 rows scroll without lag. Thumbnails are 96 px pictures made once by ffmpeg(`/api/thumb/<cover id>`) and loaded lazily.- **Audio route** `GET /stream/<song id>` (`lib/stream.hl`): HTTP Range (206 with Content-Range, 416 past the end, one answer at most 1 MiB, so `bytes=0-` gets the firstmegabyte and the browser asks for the next as it plays), the content type from the format, the bytes read with hl:fs `readBytes(path, offset, length)` and `stat(path)`(hybriel#233, since Hybriel set-day27b). The id is looked up in the songs table; the path comes from the database, never from the URL.A request without a Range header is answered like `bytes=0-`.## Read onlyThe music library is never changed. The scanner lists folders and reads files (`listDir`, `changeTime` of hl:fs, and the programs `head`,`tail` and `ffprobe` on a file). Everything the app writes lives under `storage/` of this project: the database (`storage/mpackdb/`), the covercache (`storage/covers/`) and the settings (`storage/settings.json`). The gate checks that the files of a library copy have the same bytes, sizesand times after a scan; the full scans of the real library were followed by `find -cnewer` and found nothing changed (reports/JB1-jukebox-scanner.md).## Run it```./bin/hybriel project.hl # the server, port 8700 (JUKEBOX_PORT), storage in ./storage (JUKEBOX_STORAGE)JUKEBOX_STORAGE=/abs/path ./bin/hybriel tools/scan.hl [/library/path ...] # one scan from the command line, prints the numbersnode tests/make-fixtures.mjs # rebuilds tests/fixtures with ffmpegnode tests/gate.mjs # the scanner and API gate (fixtures scan + the API over HTTP, port 8701)node tests/ui.mjs # the screens' gate: a generated database of 13,450 songs, a real headless Chrome, 390 and 1280 px (server 8710, Chrome 8700-8709)node tests/real.mjs # one check on a COPY of the real database (see the file's head): scroll, search, play 5 stools/sync-components.sh [46fefaa] # sync pinned icons, player (c96709c) and virtual list (e5b98ec); --check verifies all three (components/SOURCE)JUKEBOX_STORAGE=/abs/storage ./bin/hybriel tools/make-test-db.hl song.mp3 cover.jpg # the generated test database````bin/` is not in git (the vendored binary is described below). The first start compiles the app (cold 10–40 s).Environment: `JUKEBOX_PORT`, `JUKEBOX_STORAGE`, `JUKEBOX_WATCH=0` (no dev watcher), `JUKEBOX_AUTOSCAN=0` (no timed scans), `HL_HOST`.## Settings`storage/settings.json`: `{ "libraryPaths": ["/media/SLOW1TB1/Musik"], "rescanMinutes": 30 }` (these are the defaults). Read and changed through `GET/POST /api/settings`.## Scanning- The server starts a scan about 2 seconds after it started, then every `rescanMinutes` after the last scan ended, and whenever `POST /api/rescan` asks.No inotify: a 75 GB library on a slow disk is cheaper to compare by change time than to watch.- **The scan runs in a child process** (`tools/scan.hl`, under `nice -n 19 ionice -c3`). A scan inside the server stopped it from answering for the whole scan(measured); the child lets the server answer all the time, and the server shows the child's progress in `/api/stats`.- A file is skipped when its path, size and `changeTime` equal the database record. A rescan of an unchanged library reads no tag.New and changed files are read again, files that vanished are removed, but only under a library path that could be listed (an unmounted disk removes nothing).- Files taken: mp3, m4a, mp4, m4v, ogg, oga, opus, flac, aac, wav, ape, wma, mkv, webm.- **mp3**: our own ID3 reader (`lib/id3.hl`). ID3v2.2, 2.3 and 2.4; unsynchronisation (whole tag, or per frame in 2.4); extended header; frame flags(grouping, data length; compressed or encrypted frames are skipped); text frames in Latin-1 (UTF-8 inside Latin-1 is recognised), UTF-16, UTF-16BE, UTF-8;POPM of every owner; PCNT; APIC (the front cover wins); ID3v1 at the end of the file when the ID3v2 tag has no title, artist and album. The duration comes fromthe Xing/Info/VBRI header or the first frame (`lib/mpeg.hl`). The first bytes of a file are read with hl:fs `readBytes(path, 0, n)`and the last 128 with `stat` and `readBytes` (hybriel#233, set-day27b); no process per file any more.- **Everything else** (ogg, m4a, flac, ...): one `ffprobe` process per file (format and stream tags, duration). Pictures inside those files are not extracted; the folder cover is used.- Normalising: genre numbers and "(13)" forms become names (the ID3v1 list with the Winamp extensions); track and disc "11/21" become number and total; the year comes fromTDRC, TYER, TORY or TDOR; texts are trimmed; a missing artist is "Unknown artist", a missing album "Unknown album", a missing title is the file name.- **Play count** = the highest of all POPM counters and the PCNT counter in the file (Banshee and Guayadeque both hold the same plays, so they are not added); each owner'srating and count stay in `popm`. **Rating** = the highest POPM rating (0–255), `stars` maps it to 0–5 (1–31 → 1, 32–95 → 2, 96–159 → 3, 160–223 → 4, 224–255 → 5, so Banshee's 64/128/192/255 are 2/3/4/5).- **Covers**: the APIC picture, else `folder.jpg|jpeg|png`, `cover.*`, `front.*`, `AlbumArt*.jpg` in the file's folder. The picture is copied to `storage/covers/<first 32 hex of the SHA-256 of its content>.<ext>`,one file however many songs use it. A folder cover is looked at only when a file of that folder is read, so a cover added later shows when a song of the folder changes (or after deleting `storage/`).## Database (mpackdb)Tables in `storage/mpackdb/`, all opened in `lib/db.hl` (the one file that knows mpackdb):| table | key | indexes | what ||---|---|---|---|| songs | `@id` | `!path`, folder, albumKey, artistKey, sortArtist, sortAlbum, sortTitle, playCount | one record per file || albums | `id` (digest of albumKey) | `!key`, artistKey, sortName | derived: name, albumArtist, year, songCount, duration, playCount, coverId, folder || artists | `id` (digest of artistKey) | `!key`, sortName | derived: name, songCount, albumCount, playCount, coverId || covers | `hash` | – | ext, mime, size of a cached cover || scans | `@id` | at | one record per finished scan: seconds, seen, added, updated, removed, unreadable |**An index key may hold no comma** (an mpackdb bug: such a key is lost when the table is reopened, repro in the report), so `albumKey`, `artistKey` and the sort keys have commas turned into character 2 (`safeKey`), and `path` and `folder` are not indexed.A song record: `path folder title artist albumArtist album track trackTotal disc discTotal year genre duration format kind size changeTime playCount popm[{owner,rating,count}] rating stars coverId addedAt`and the browse fields `albumKey` (= album artist or artist, folded, + album name folded + folder), `artistKey`, `search` (lower case, accents folded: artist, title, album, genre) and the sort keys`sortArtist` (artist, album, disc, track, title), `sortAlbum`, `sortTitle` (folded, parts separated by character 1 so that "alt" sorts before "alt lied").Albums and artists are rebuilt from the songs after a scan that changed something; their ids are stable. The song ids are mpackdb's own and stay when a file is re-read.Browsing is fast because the sort orders come from the indexes: the server keeps, per order, the list of song ids with their play count in memory (built from the sorted index once, dropped when a scan changed songs),and a page is a slice of that list plus one lookup per row.### mpackdb versionThe brief asked for mpackdb 1.0.10, which Nemesis was to release; **no 1.0.10 release was found** (no tag in the hybriel repository, no newer plugin copy in any app). The plugin `plugins/mpackdb` is the newest one on loreana, the copy ofgitoria's vendor (hybriel master c1b1010f, on-disk format of the JS mpackdb 1.0.7). All use of it is in `lib/db.hl` (tables) and the calls `put fetch find range iterate update delete count` in the topic files, so a switch is a copy of the plugin folder.## The API (JSON, nothing is sent whole: default 50 rows, at most 200, `offset` for the next page)| request | answer ||---|---|| `GET /api/stats` | `library` (songs, artists, albums, covers, songsWithCover, videos, playedAtLeast1, playedAtLeast5, totalSeconds, totalBytes), `scan` (running, phase, seen, added, updated, removed, unreadable, lastSeconds, lastError, queued), `lastScan`, `settings` || `GET /api/songs?sort=title\|artist\|album\|plays&offset&limit` | `{ total, offset, limit, items }`; optional `minPlays=N` (only songs played at least N times), `artist=<artist id>`, `album=<album id>`; default sort artist || `GET /api/artists?offset&limit` | page of artists by name || `GET /api/albums?offset&limit[&artist=<id>]` | page of albums by name || `GET /api/search?q=&offset&limit` | `{ q, songs: page, artists: [≤10], albums: [≤10] }`; every word must match (case and accents ignored) || `GET /api/shuffle?minPlays=5&count=50` | `count` random songs (no repeats) among the songs with at least `minPlays` plays; `total` = how many qualify || `GET /api/cover/<coverId>` | the picture, cached for a year (the id is the content hash); 404 when unknown || `GET /api/thumb/<coverId>` | the same as a 96 px square jpeg (made once with ffmpeg into `storage/covers/thumbs/`) || `GET /stream/<songId>` | the audio with HTTP Range (see above) || `POST /api/rescan` | 202, `{ started }`; the scan starts within a second || `GET /api/settings`, `POST /api/settings` | `{ libraryPaths, rescanMinutes }` (absolute paths, at least one) |Song items: `id title artist albumArtist album track trackTotal disc year genre duration format kind size playCount rating stars popm coverId path addedAt`.There is no login yet. `sort=plays` is the most played first (a counting sort over the play counts: mpackdb's playCount index orders the numbers as text, 9 before 12).## Files| file | what ||---|---|| `project.hl` | the map: routes, config, the one-second timer || `lib/id3.hl`, `lib/id3-helpers.hl` | the ID3v2/ID3v1 reader; text encodings, unsynchronisation, genre names || `lib/mpeg.hl` | mp3 duration || `lib/tags.hl` | read one file (mp3 or ffprobe) and make the song record || `lib/library.hl`, `lib/scan-state.hl` | the scanner and what it reports; `lib/schedule.hl` when it runs (child process) || `lib/covers.hl` | the cover cache || `lib/db.hl`, `lib/catalog.hl` | the tables; the derived albums and artists || `lib/browse.hl`, `lib/order-cache.hl` | pages, search, shuffle, stats || `lib/api.hl`, `lib/api-helpers.hl`, `lib/jsoncheck.hl` | the JSON routes (jsoncheck is notes' copy: JSON.parse cannot be caught) || `lib/settings.hl`, `lib/util.hl` | settings file, storage folders; text folding, number helpers || `tools/scan.hl` | one scan from the command line (also the child process of the server) || `tests/make-fixtures.mjs`, `tests/fixtures/`, `tests/gate.mjs` | the test mp3s built byte by byte, and the gate || `lib/rows.hl` | what a list row, an artist or album head and a queue item show (the one place that decides how a row reads) || `lib/stream.hl` | the audio route with Range || `components/main.hl` | the shell: header, menu, player bar, the server faces `jbRows` and `jbQueue`, `jbPlay` || `components/songs.hl artists.hl albums.hl artist.hl album.hl search.hl` | the screens || `components/styles.hl` | our CSS (theme inherited; the screen, the toolbar, the album head, the compact player bar) || `components/media-player/`, `virtual-list/`, `icons/`, `SOURCE` | vendored from components.hybriel by `tools/sync-components.sh` (byte-verbatim, never edited here) || `theme/`, `shared/` | the WorldAPI theme (verbatim from layouts.worldapi.org) and the tokens || `tests/ui.mjs`, `tests/real.mjs`, `tests/cdp.mjs`, `tests/ports.mjs` | the screens' gate, the real-library check, the browser driver (copied from components.hybriel) || `tools/make-test-db.hl` | the generated 13,450-song test database |## Hybriel notes- Vendor: Hybriel set-day41 (source 57054d9e11329a5e2cfc83124030b563d4a5276a), binary SHA-256 `e9911159fc2858d78016032fd350c4f4a1b51e51c1830c3949181e7ab3337f59`: `bin/` is the set's `bin/` and `lib/` (not in git); the complete plugin dirs core, crypto, data, fetch, fs, http, http1, math, mpackdb, proc, time, web are copies from that commit, with the set's `.so` files. Set SHA256SUMS verified.Day26: no `list.upsert` and no one-argument `list.remove` anywhere in this code (checked with grep); the only `delete` calls are mpackdb's `delete(key)`.- Found while building (workarounds in the code, no JavaScript): `from` is a reserved word; no semicolons; a `.hl` file is one class (so `scan-state.hl` and `order-cache.hl` are class files); `Bytes.text()` on invalid UTF-8cannot be caught (so the UTF-8 decoder is our own); `String.fromCharCode` takes one argument and refuses surrogates; a scan run inside a timer handler of the server kept it from answering any request until the scan was over (so the scan is a child process).- Since set-day27b (binary a9712e61, Hybriel f5ff97bf) hl:fs has `readBytes(path, offset, length)` and `stat(path)` (hybriel#233); mpackdb rebuilds string indexes with commas once on first open (hybriel#234; `safeKey` stays, it does no harm); `on Error` exits 1 at startup (`e.phase`).## Shuffle, the overlay and counting plays (JB3)- **Albums** are artist + album name; "CD 1", "(Cd2)", "Disc 2" become a disc number, the folder does not matter. **Copies**: the same artist and title with lengths within 2 s are shown once ("2 copies"), with the highest play count.- **Shuffle**: "Shuffle my favourites" (Songs screen; the songs played at least N times, N is the Favourites field, default 5) and "Shuffle" on Songs, an album, an artist and Search. The server holds the seeded order (`lib/queue.hl`), the browser gets 40 songs at a time; every song comes once before any repeats.- **Bar and overlay**: previous / play / next in the bar; a tap on the bar opens the overlay (phone: full screen, desktop: a 24 rem panel at the right): large cover, title, artist, album, previous, back 10 s, play, forward 10 s, next, times, mute, speed, and the song that plays plus the 20 after it. Close with the button or a swipe down. Previous restarts the song after 3 s, else goes back one.- **Counting**: a play counts after half of the song or 4 minutes of real listening (seconds the audio played, a one second timer in the shell), once per play, through the face `jbPlayed` (same function as `POST /api/played/<id>`). The count lives in the jukebox database (table plays); the file is never written. Favourites use file count + jukebox count.- **Lock screen**: the browser's media session shows title, artist, album, cover and has play, pause, previous and next. The keyboard is not done: a Hybriel gap (`reports/JB3b-keyboard-gap.md`).- Gates: `node tests/jb3.mjs` (server 8712, takes about 2 minutes: it waits for a real play to count).Theme and shared tokens are unchanged git-source copies from layouts.worldapi.org `17e0f03ecd09b4427fab17276f646e0094260fd5`.Icons are unchanged copies from components.hybriel `46fefaa`; virtual-list is an unchanged copy from components.hybriel `e5b98ec` (with `centerId`, `scrollTop`, `onScroll`), and media-player is `c96709c` (skip and repeat options; the end of a song only calls onPlay). `tools/sync-components.sh --check` verifies each against its recorded source commit.
Branches
Latest commits
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre
- 89cdabb1Vendor Hybriel day41 (57054d9e): plugin dirs, set .somre
- 1fecd6a7Merge branch 'records-day39' into mainJukebox
- d6b3e068|||PR Records: day39 live (PR #2), mission 011 PR step, statusmre
- 5fa19e89Merge branch 'day39' into mainJukebox
- cfe95440|||PR day39 re-vendor: Hybriel 51e921d7 (bin 6b481aa7), ids kebab-case since hybriel#256: quoted state rule and tests use jb-shuffle / jb-repeatmre
- f3614c9bRe-vendor to Hybriel day39 (51e921d7, bin 6b481aa7)mre
- 9f5c6532Merge branch 'status-22-pr' into mainJukebox
- 5838d6c7|||PR STATUS: #22 pending decision, PR-only rulemre
- 29d2029cRecords: PR-only rule (Kunibert)mre
- adacb0abRecords: neutral ticket rule, #22 decision recordedmre
- b2d6f121Records: #308 hold liftedmre
- 7ab67533Records: day39 on hold (hybriel#308)mre
- 22f21739Records: note rebase before mergemre
- f7368ea3Records: mission 011 day39, waits for lisbethmre
- 9515d2cdRecords: jb20 livemre
- 019f6601ui gate: comment names the open bug components#27 (workaround, not fixed)mre
- 277a2722README: provenance linemre
- 4169ca6aREADME: sync pinmre
- a01f3aa8ui gate: back to the top before the sort checks (the screen reopens where it was left)mre