diff --git a/.gitignore b/.gitignore
index 539fdcf..048042b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,3 @@
-/build/
+build/
__pycache__/
.DS_Store
diff --git a/Makefile b/Makefile
index 32d96f0..fa9d5ae 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,8 @@
# SPDX-License-Identifier: GPL-3.0-only
SDK ?= ../osos-lab/rvx-sdk
OUT ?= build
-extensions := balance crossfeed dsp night-shift playback-log
+extensions := album-artists balance clicker-modes crossfeed dsp equalizer eu-volume-limit \
+ file-info homebrew iap-auth-bypass night-shift playback-log playback-queue
.PHONY: all $(extensions)
all: $(extensions)
@@ -13,9 +14,12 @@ $(extensions):
.PHONY: check
check:
+ $(PYTHON) extensions/album-artists/tests/run.py "$(abspath $(SDK))"
$(PYTHON) extensions/balance/tests/run.py "$(abspath $(SDK))"
$(PYTHON) extensions/crossfeed/tests/run.py "$(abspath $(SDK))"
$(PYTHON) extensions/dsp/tests/run.py "$(abspath $(SDK))"
+ $(PYTHON) extensions/equalizer/tests/run.py "$(abspath $(SDK))"
+ $(PYTHON) extensions/file-info/tests/run.py "$(abspath $(SDK))"
@mkdir -p "$(OUT)"
$(CC) $(TEST_FLAGS) extensions/night-shift/test.c -o "$(OUT)/test-night-shift"
"$(OUT)/test-night-shift"
diff --git a/NOTICE b/NOTICE
index 8f60e86..9dac7e2 100644
--- a/NOTICE
+++ b/NOTICE
@@ -4,7 +4,22 @@ Balance, Crossfeed, DSP and the Night Shift scheduling and gamma code are from
RevolaOS extensions, revision 36d197b180e55a304ea0468de4330c0d07fe715f.
Night Shift derives from kayboll’s RepriseOS work. Playback Log derives from
the work of brilliant-alien and lgreitis in osos-lab. Its Settings artwork is
-from osos-lab commit 10485fa. The original RevolaOS notice follows.
+from osos-lab commit 10485fa. Album Artists, File Info and Playback Queue are
+from RevolaOS extensions, revision 900d5c4ea61e31834d85f9b62c353ce48e58419a,
+and derive from the RepriseOS core: Album Artists by lgreitis, File Info by
+lgreitis and paviro, Play Next and Play Last by lgreitis and brilliant-alien,
+and Up Next by Alex Ball. Their Settings icons are Cupertino Icons glyphs
+(MIT), see the LICENSE.cupertino-icons beside each. Equalizer, Clicker Modes,
+iAP Auth Bypass and EU Volume Limit are from RevolaOS extensions, revision
+509cd1630325a53495798541c170e72854bbb17e. Equalizer, Clicker Modes and iAP
+Auth Bypass derive from the RepriseOS core: Custom EQ by lgreitis and paviro,
+clicker modes by Alex Ball and lgreitis, iAP auth bypass by RaduTek; EU Volume
+Limit is by paviro. Equalizer's Settings icon is the core's own settings-eq
+art; the other three are Cupertino Icons glyphs (MIT), see the
+LICENSE.cupertino-icons beside each. Homebrew is from RevolaOS extensions,
+revision 509cd1630325a53495798541c170e72854bbb17e, and derives from the
+RepriseOS core's homebrew patch by lgreitis; its catalog icon is a Cupertino
+Icons glyph (MIT). The original RevolaOS notice follows.
RevolaOS
Copyright (C) 2026 The RevolaOS Authors. GPL-3.0-only.
diff --git a/README.md b/README.md
index c7692aa..472e1a0 100644
--- a/README.md
+++ b/README.md
@@ -5,6 +5,14 @@ This repository hosts the source for these RepriseOS extensions and accepts prop
- [Balance](extensions/balance/) adjusts the volume of the left and right channels independently of the main volume.
- [Night Shift](extensions/night-shift/) warms the display manually or automatically from sunset to sunrise.
- [Playback Log](extensions/playback-log/) records listening history for scrobbling and optional detailed reports.
+- [Album Artists](extensions/album-artists/) lists the library by Album Artist, with the Artist as the fallback.
+- [File Info](extensions/file-info/) shows an item's tags and file properties from its context menu.
+- [Playback Queue](extensions/playback-queue/) adds Play Next, Play Last and an Up Next screen to edit the queue.
- [Crossfeed](extensions/crossfeed/) blends a little of each stereo channel into the other for headphone listening. It uses the included [DSP library](extensions/dsp/).
+- [Equalizer](extensions/equalizer/) runs the EQ presets without distortion and adds a Custom preset with five bands. It uses the included [DSP library](extensions/dsp/).
+- [Clicker Modes](extensions/clicker-modes/) lets Settings > Clicker choose the speaker, the headphones, both or off.
+- [iAP Auth Bypass](extensions/iap-auth-bypass/) lets accessories use authentication-gated iAP commands without an Apple authentication chip.
+- [EU Volume Limit](extensions/eu-volume-limit/) gives an EU iPod the volume behaviour of a non-EU one when its limit switch is off.
+- [Homebrew](extensions/homebrew/) lists apps and games from `/Reprise/Apps` and `/Reprise/Games` under Extras and starts them without an Apple signature.
To add your extension to the catalog, open a PR following the [submission guide](catalog/README.md). Later releases are picked up automatically.
diff --git a/catalog/sources.toml b/catalog/sources.toml
index 1e88372..10f27b3 100644
--- a/catalog/sources.toml
+++ b/catalog/sources.toml
@@ -22,3 +22,43 @@ tag_prefix = "playback-log/v"
repo = "RepriseOS/repriseos-extensions"
path = "extensions/dsp"
tag_prefix = "dsp/v"
+
+[album-artists]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/album-artists"
+tag_prefix = "album-artists/v"
+
+[file-info]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/file-info"
+tag_prefix = "file-info/v"
+
+[playback-queue]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/playback-queue"
+tag_prefix = "playback-queue/v"
+
+[equalizer]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/equalizer"
+tag_prefix = "equalizer/v"
+
+[clicker-modes]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/clicker-modes"
+tag_prefix = "clicker-modes/v"
+
+[iap-auth-bypass]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/iap-auth-bypass"
+tag_prefix = "iap-auth-bypass/v"
+
+[eu-volume-limit]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/eu-volume-limit"
+tag_prefix = "eu-volume-limit/v"
+
+[homebrew]
+repo = "RepriseOS/repriseos-extensions"
+path = "extensions/homebrew"
+tag_prefix = "homebrew/v"
diff --git a/extensions/album-artists/Makefile b/extensions/album-artists/Makefile
new file mode 100644
index 0000000..0266815
--- /dev/null
+++ b/extensions/album-artists/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c fields.c browser.c
+include $(SDK)/rv.mk
diff --git a/extensions/album-artists/README.md b/extensions/album-artists/README.md
new file mode 100644
index 0000000..9d340b6
--- /dev/null
+++ b/extensions/album-artists/README.md
@@ -0,0 +1,21 @@
+# Album Artists
+
+Partly adapted from the RepriseOS core's [Album Artists](https://github.com/RepriseOS/repriseos/blob/bfedd72/payload/album_artists.c) and its [index](https://github.com/RepriseOS/repriseos/blob/bfedd72/payload/album_artists_index.h), by lgreitis.
+
+Adds Album Artists after Artists in Music, and optionally to the main menu, listing the library by the iTunes Album Artist tag with the Artist as the fallback. Opening a group shows its albums with their artists as subtitles and their artwork, on the stock Artists and Albums screens. Settings > Music Menu and Main Menu show or hide the two rows.
+
+| | |
+|---|---|
+| Sort | the Sort Album Artist or Sort Artist tag when iTunes set one; otherwise the name, with Apple's rules for leading articles |
+| Jump letters | from the Sort As text, "#" for digits and symbols |
+| No artist | one "Unknown" group |
+
+Apple's importer discards the Album Artist, Sort Artist and Sort Album Artist tags, so the extension keeps them while the library loads. A song whose Album Artist is its Artist and that carries no Sort As tag is not kept: it lands in the same group either way. File Info shows an Album Artist row for the songs whose Album Artist differs from their Artist.
+
+On first start the two rows take over the Music Menu and Main Menu checkboxes of the Album Artists row that earlier RepriseOS releases built in.
+
+| | |
+|---|---|
+| Default | on |
+| Memory | 20 bytes per song whose Album Artist differs from its Artist or that carries a Sort As tag, plus those strings in Apple's artist cache; up to twice that as the load finishes; the list's rows while the list is open and until Apple's selection and artwork cache let it go |
+| Settings | the two menu visibility flags |
diff --git a/extensions/album-artists/assets/LICENSE.cupertino-icons b/extensions/album-artists/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/album-artists/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/album-artists/assets/settings-album-artists.png b/extensions/album-artists/assets/settings-album-artists.png
new file mode 100644
index 0000000..81097bb
Binary files /dev/null and b/extensions/album-artists/assets/settings-album-artists.png differ
diff --git a/extensions/album-artists/assets/settings-album-artists.svg b/extensions/album-artists/assets/settings-album-artists.svg
new file mode 100644
index 0000000..484ca79
--- /dev/null
+++ b/extensions/album-artists/assets/settings-album-artists.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/album-artists/browser.c b/extensions/album-artists/browser.c
new file mode 100644
index 0000000..a5abadb
--- /dev/null
+++ b/extensions/album-artists/browser.c
@@ -0,0 +1,928 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The Album Artists list reuses the stock Artists screen on a browser of the
+ * extension's own: a child of the shared music browser whose artist rows this
+ * file builds, grouped by the Album Artist of the fields table with the Artist
+ * as the fallback. Apple's readers of the rows, the artist filter, the album
+ * grouping and subtitle, the artwork source and the destructor are hooked and
+ * answer for the owned browsers only; every other browser goes to Apple.
+ *
+ * Up to four browsers share the registry; one context per slot remembers
+ * which are owned. Rows, tokens, jump table and the per-row artwork ids come
+ * from api->alloc and are freed here before Apple's own clear, which frees
+ * them with Heap_Free otherwise.
+ *
+ * Adapted from RepriseOS payload/album_artists.c and album_artists_index.h
+ * (bfedd72) by lgreitis. */
+
+#include "browser.h"
+#include "fields.h"
+#include "shared.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_media.h"
+#include
+#include
+
+/* An artist row of the browser's artists vector, Apple's layout. */
+struct group {
+ uint32_t token, display_token;
+ uint32_t *artwork; /* up to ARTWORK_IDS artwork ids */
+ uint32_t artwork_count, albums;
+};
+
+_Static_assert(offsetof(struct group, artwork) == ArtistGroup_artwork,
+ "ArtistGroup layout");
+_Static_assert(sizeof(struct group) == ArtistGroup_bytes, "ArtistGroup layout");
+#define ARTWORK_IDS 10
+
+/* An album row of the browser's albums vector, Apple's layout. */
+struct album {
+ uint32_t token, artist, display_artist, artwork, tracks, flags;
+};
+
+_Static_assert(sizeof(struct album) == AlbumGroup_bytes, "AlbumGroup layout");
+
+/* One eligible track while the rows are built: its artist token, then the
+ * group it fell into, and its position in the list order. */
+struct track {
+ union {
+ uint32_t token;
+ uint32_t group_index;
+ };
+
+ uint32_t order;
+};
+
+struct context {
+ void *browser, *track_data;
+ void *model_reference; /* non-owning; the model's destructor clears the context */
+};
+static struct context contexts[4];
+
+/* The artwork model the album source of an open list reads through, with a
+ * reference that keeps the owned model alive for as long as Apple's artwork
+ * cache holds the provider. */
+struct artwork_model {
+ uint8_t native[LibraryBrowser_bytes];
+ void *owner_reference;
+};
+
+#define ARTWORK_MODEL_OWNERSHIP 0x80 /* ours; Apple's ownership values stay below */
+static void *artwork_model_reference;
+static unsigned custom_artwork_providers;
+
+static const uint16_t unknown[] = {'U', 'n', 'k', 'n', 'o', 'w', 'n'};
+
+static void *zalloc(uint32_t bytes)
+{
+ return api->alloc(self, bytes);
+}
+
+static void release(void *block)
+{
+ if (block)
+ api->free(self, block);
+}
+
+static struct context *context_for(void *browser)
+{
+ for (unsigned i = 0; i < 4; i++)
+ if (browser && contexts[i].browser == browser)
+ return &contexts[i];
+ return NULL;
+}
+
+static void *browser_of(void *model)
+{
+ return RV_FIELD(model, LibraryBrowser_browser, void *);
+}
+
+static void *track_data_of(void *browser)
+{
+ return RV_FIELD(MediaBrowser_GetOwner(browser), MediaBrowser_track_data, void *);
+}
+
+static void *artist_cache(void *track_data)
+{
+ return (uint8_t *)track_data + TrackData_artist_cache;
+}
+
+static uint32_t token_view(void *track_data, uint32_t token, const uint16_t **text)
+{
+ uint32_t bytes = 0;
+ *text = NULL;
+ if (!token || StringCache_GetTokenView(artist_cache(track_data), token,
+ (void **)text, &bytes))
+ return 0;
+ return bytes / 2;
+}
+
+/* The group a record belongs to: its Album Artist, else its Artist. */
+static uint32_t resolved_artist_token(const void *record)
+{
+ const uint16_t *text;
+ void *track_data = RV_FIELD(record, 0, void *);
+ uint32_t token = fields_token(record);
+ if (token && token_view(track_data, token, &text))
+ return token;
+ token = RV_FIELD(record, MediaRecord_artist, uint32_t);
+ return token && token_view(track_data, token, &text) ? token : 0;
+}
+
+static uint32_t artist_name_view(void *track_data, uint32_t token,
+ const uint16_t **text)
+{
+ uint32_t units = token_view(track_data, token, text);
+ if (!units) {
+ *text = unknown;
+ units = sizeof unknown / sizeof *unknown;
+ }
+ return units;
+}
+
+static int compare_artist_names(void *track_data, uint32_t a, uint32_t b)
+{
+ if (a == b)
+ return 0;
+ const uint16_t *left, *right;
+ uint32_t left_units = artist_name_view(track_data, a, &left);
+ uint32_t right_units = artist_name_view(track_data, b, &right);
+ return SongText_CompareUtf16(NULL, left, left_units, right, right_units);
+}
+
+/* The text a group sorts by: its Sort As, else its name. */
+static uint32_t artist_sort_view(void *track_data, const void *record,
+ const uint16_t **text)
+{
+ uint32_t token = fields_token(record);
+ int has_album_artist = token && token_view(track_data, token, text);
+ uint32_t units =
+ token_view(track_data, fields_sort_token(record, has_album_artist), text);
+ if (units)
+ return units;
+ return artist_name_view(track_data, resolved_artist_token(record), text);
+}
+
+/* Sorting of tracks, with the incoming order as the final tie-breaker. */
+
+typedef int (*track_compare)(void *, const struct track *, const struct track *);
+
+static int compare_tracks(const struct track *a, const struct track *b,
+ track_compare compare, void *context)
+{
+ int result = compare(context, a, b);
+ return result ? result : (a->order > b->order) - (a->order < b->order);
+}
+
+static void sift(struct track *tracks, uint32_t root, uint32_t count,
+ track_compare compare, void *context)
+{
+ while (root < count / 2) {
+ uint32_t child = root * 2 + 1;
+ if (child + 1 < count &&
+ compare_tracks(&tracks[child], &tracks[child + 1], compare, context) < 0)
+ child++;
+ if (compare_tracks(&tracks[root], &tracks[child], compare, context) >= 0)
+ break;
+ struct track swap = tracks[root];
+ tracks[root] = tracks[child];
+ tracks[child] = swap;
+ root = child;
+ }
+}
+
+static void sort_tracks(struct track *tracks, uint32_t count, track_compare compare,
+ void *context)
+{
+ for (uint32_t i = count / 2; i; i--)
+ sift(tracks, i - 1, count, compare, context);
+ for (uint32_t i = count; i > 1; i--) {
+ struct track swap = tracks[0];
+ tracks[0] = tracks[i - 1];
+ tracks[i - 1] = swap;
+ sift(tracks, 0, i - 1, compare, context);
+ }
+}
+
+/* Puts rows into the order `order` lists them, in place. */
+static void reorder(struct group *rows, struct track *order, uint32_t count)
+{
+ for (uint32_t i = 0; i < count; i++) {
+ struct group saved = rows[i];
+ uint32_t current = i;
+ while (order[current].group_index != i) {
+ uint32_t next = order[current].group_index;
+ rows[current] = rows[next];
+ order[current].group_index = current;
+ current = next;
+ }
+ rows[current] = saved;
+ order[current].group_index = current;
+ }
+}
+
+/* Apple's jump table: a count, then (letter, first index) pairs, then a
+ * (0, UINT32_MAX) end marker. */
+static int valid_jumps(const uint32_t *jump, uint32_t tracks)
+{
+ if (!jump || !jump[0] || jump[0] > tracks || jump[2] != 0)
+ return 0;
+ for (uint32_t i = 0; i < jump[0]; i++)
+ if (jump[i * 2 + 2] >= tracks || (i && jump[i * 2 + 2] <= jump[i * 2]))
+ return 0;
+ return 1;
+}
+
+static uint16_t jump_letter(const uint32_t *jump, uint32_t index)
+{
+ uint32_t low = 0, high = jump[0];
+ while (low + 1 < high) {
+ uint32_t middle = low + (high - low) / 2;
+ if (jump[middle * 2 + 2] <= index)
+ low = middle;
+ else
+ high = middle;
+ }
+ return (uint16_t)jump[low * 2 + 1];
+}
+
+static int compare_track_artists(void *track_data, const struct track *a,
+ const struct track *b)
+{
+ return compare_artist_names(track_data, a->token, b->token);
+}
+
+/* Where the tracks come from: the list, through Apple's native Album Artist
+ * order when the import built one, else the album order, which keeps an
+ * album's tracks together so each album is one run. */
+struct source {
+ struct MediaList *list;
+ uint8_t *order; /* a MediaOrder, or NULL */
+};
+
+static struct MediaEntry *source_entry(const struct source *source, uint32_t index)
+{
+ if (source->order)
+ return ((struct MediaEntry **)(source->order + MediaOrder_entries))[index];
+ return MediaList_GetEntryByOrderIndex(source->list, MediaOrderMode_Album, 0, index);
+}
+
+static const void *entry_record(const struct MediaEntry *entry)
+{
+ return RV_FIELD(entry, MediaEntry_song_record, const void *);
+}
+
+struct group_sort {
+ void *track_data;
+ struct group *rows;
+ struct source source;
+};
+
+static int compare_group_order(void *opaque, const struct track *a,
+ const struct track *b)
+{
+ struct group_sort *sort = opaque;
+ if (sort->source.order)
+ return (a->order > b->order) - (a->order < b->order);
+ const uint16_t *left, *right;
+ uint32_t left_units = artist_sort_view(
+ sort->track_data, entry_record(source_entry(&sort->source, a->order)), &left);
+ uint32_t right_units = artist_sort_view(
+ sort->track_data, entry_record(source_entry(&sort->source, b->order)), &right);
+ int result = SongText_CompareUtf16(NULL, left, left_units, right, right_units);
+ return result ? result
+ : compare_artist_names(sort->track_data,
+ sort->rows[a->group_index].token,
+ sort->rows[b->group_index].token);
+}
+
+static uint16_t artist_letter(void *track_data, const void *record)
+{
+ const uint16_t *text;
+ uint32_t units = artist_sort_view(track_data, record, &text);
+ while (units && *text <= ' ') {
+ text++;
+ units--;
+ }
+ if (!units)
+ return '#';
+ for (uint16_t letter = 'A'; letter <= 'Z'; letter++)
+ if (!SongText_CompareUtf16(NULL, text, 1, &letter, 1))
+ return letter;
+ return *text < 0x80 || (*text >= 0xd800 && *text <= 0xdfff) ? '#' : *text;
+}
+
+static struct group *groups_of(void *browser)
+{
+ return RV_FIELD(browser, MediaBrowser_artists, struct group *);
+}
+
+static uint32_t group_count(void *browser)
+{
+ return (uint32_t)(RV_FIELD(browser, MediaBrowser_artists + sizeof(void *),
+ struct group *) -
+ groups_of(browser));
+}
+
+/* Frees the rows and their arrays of an owned browser and leaves the words
+ * Apple's clear would free empty. */
+static void drop_rows(void *browser)
+{
+ struct group *rows = groups_of(browser);
+ uint32_t count = group_count(browser);
+ for (uint32_t i = 0; i < count; i++)
+ release(rows[i].artwork);
+ release(rows);
+ for (unsigned i = 0; i < 3; i++)
+ RV_FIELD(browser, MediaBrowser_artists + i * sizeof(void *), void *) = NULL;
+ release(RV_FIELD(browser, MediaBrowser_artist_tokens, void *));
+ RV_FIELD(browser, MediaBrowser_artist_tokens, void *) = NULL;
+ release(RV_FIELD(browser, MediaBrowser_artist_jump, void *));
+ RV_FIELD(browser, MediaBrowser_artist_jump, void *) = NULL;
+ RV_FIELD(browser, MediaBrowser_artist_count, uint32_t) = 0;
+}
+
+static void clear_groups(void *browser)
+{
+ drop_rows(browser);
+ MediaBrowser_ClearArtists(browser);
+ MediaBrowser_ClearAlbums(browser);
+ MediaBrowser_ClearSongs(browser);
+ /* Apple's clear keeps the albums vector's capacity; an owned browser
+ * releases it too. */
+ Heap_Free(RV_FIELD(browser, MediaBrowser_albums, void *));
+ for (unsigned i = 0; i < 3; i++)
+ RV_FIELD(browser, MediaBrowser_albums + i * sizeof(void *), void *) = NULL;
+}
+
+void browser_invalidate(void *track_data)
+{
+ for (unsigned i = 0; i < 4; i++) {
+ struct context *context = &contexts[i];
+ if (!context->browser || context->track_data != track_data)
+ continue;
+ clear_groups(context->browser);
+ /* The TrackData's destruction has unlinked its lists already. */
+ RV_FIELD(context->browser, MediaBrowser_list, void *) = NULL;
+ context->track_data = NULL;
+ }
+}
+
+/* Building the rows */
+
+static void build_group_rows(void *browser, void *track_data, struct track *tracks,
+ uint32_t used, struct group *rows,
+ const struct source *source)
+{
+ uint32_t group = 0, last_album = 0, previous_token = 0;
+ struct group *row = NULL;
+ void *owner = MediaBrowser_GetOwner(browser);
+ for (uint32_t i = 0; i < used; i++) {
+ struct track track = tracks[i];
+ if (!i || compare_artist_names(track_data, previous_token, track.token)) {
+ row = &rows[group];
+ *row = (struct group){track.token, 0, NULL, 0, 0};
+ /* One representative per group, in the consumed track slots. */
+ tracks[group] = (struct track){.group_index = group, .order = track.order};
+ group++;
+ last_album = 0;
+ }
+ previous_token = track.token;
+ const void *record = entry_record(source_entry(source, track.order));
+ uint32_t album = RV_FIELD(record, MediaRecord_album, uint32_t);
+ if (!album || album == last_album)
+ continue;
+ last_album = album;
+ row->albums++;
+ if (row->artwork_count == ARTWORK_IDS)
+ continue;
+ uint32_t artwork = MediaBrowser_GetRecordArtworkId(owner, (void *)record);
+ if (artwork && !row->artwork)
+ row->artwork = zalloc(ARTWORK_IDS * sizeof *row->artwork);
+ if (artwork && row->artwork)
+ row->artwork[row->artwork_count++] = artwork;
+ }
+}
+
+static void build_group_jumps(void *track_data, const struct group *rows,
+ const struct track *tracks, uint32_t groups,
+ const uint32_t *native_jump, uint32_t *tokens,
+ uint32_t *jump, const struct source *source)
+{
+ jump[0] = 0;
+ for (uint32_t i = 0; i < groups; i++) {
+ tokens[i] = rows[tracks[i].group_index].token;
+ uint16_t letter =
+ native_jump
+ ? jump_letter(native_jump, tracks[i].order)
+ : artist_letter(track_data,
+ entry_record(source_entry(source, tracks[i].order)));
+ if (!jump[0] || (uint16_t)jump[jump[0] * 2 - 1] != letter) {
+ jump[jump[0] * 2 + 1] = letter;
+ jump[jump[0] * 2 + 2] = i;
+ jump[0]++;
+ }
+ }
+ jump[jump[0] * 2 + 1] = 0;
+ jump[jump[0] * 2 + 2] = UINT32_MAX;
+}
+
+/* One track per artist and album run; its first track gives the artwork and
+ * the sort order. Counts when `tracks` is NULL. */
+static uint32_t collect_album_runs(void *browser, const struct source *source,
+ uint32_t count, struct track *tracks,
+ uint32_t capacity)
+{
+ uint32_t used = 0, previous_artist = 0, previous_album = 0;
+ for (uint32_t i = 0; i < count; i++) {
+ struct MediaEntry *entry = source_entry(source, i);
+ const void *record = entry ? entry_record(entry) : NULL;
+ if (!record || !MediaBrowser_EvaluateEntryFilters(browser, entry, NULL))
+ continue;
+ uint32_t artist = resolved_artist_token(record);
+ uint32_t album = RV_FIELD(record, MediaRecord_album, uint32_t);
+ if (used && artist == previous_artist && album == previous_album)
+ continue;
+ if (tracks) {
+ if (used == capacity)
+ return 0;
+ tracks[used] = (struct track){.token = artist, .order = i};
+ }
+ previous_artist = artist;
+ previous_album = album;
+ used++;
+ }
+ return used;
+}
+
+static uint32_t build(void *browser)
+{
+ struct context *context = context_for(browser);
+ if (RV_FIELD(browser, MediaBrowser_artist_tokens, void *))
+ return group_count(browser);
+ void *track_data = track_data_of(browser);
+ context->track_data = track_data;
+ struct MediaList *list = MediaBrowser_GetCurrentList(browser);
+ if (!track_data || !list || !RV_FIELD(list, MediaList_root, void *))
+ return 0;
+ uint32_t count = RV_FIELD(RV_FIELD(list, MediaList_root, uint8_t *),
+ MediaEntry_tracks, uint16_t);
+ if (!count)
+ return 0;
+ /* Apple's Album Artist order exists only when the import built it; there
+ * is no comparator to rebuild it, so it is consumed when complete. */
+ uint8_t *order =
+ RV_FIELD(list, MediaList_order_index + AlbumArtist_order_mode * sizeof(void *),
+ uint8_t *);
+ if (order && (RV_FIELD(order, MediaOrder_count, uint32_t) != count ||
+ RV_FIELD(order, MediaOrder_capacity, uint32_t) < count))
+ order = NULL;
+ const uint32_t *native_jump =
+ order ? RV_FIELD(list,
+ MediaList_jump_index + AlbumArtist_order_mode * sizeof(void *),
+ uint32_t *)
+ : NULL;
+ if (!valid_jumps(native_jump, count))
+ native_jump = NULL;
+ TrackData_AcquireStringCaches(track_data);
+ struct source source = {list, order};
+ uint32_t runs = collect_album_runs(browser, &source, count, NULL, 0);
+ struct track *tracks = runs ? zalloc(runs * sizeof *tracks) : NULL;
+ uint32_t used =
+ tracks ? collect_album_runs(browser, &source, count, tracks, runs) : 0;
+ uint32_t groups = 0;
+ struct group *rows = NULL;
+ uint32_t *tokens = NULL, *jump = NULL;
+ if (!used)
+ goto done;
+ sort_tracks(tracks, used, compare_track_artists, track_data);
+ for (uint32_t i = 0; i < used; i++)
+ if (!i ||
+ compare_artist_names(track_data, tracks[i - 1].token, tracks[i].token))
+ groups++;
+ rows = zalloc(groups * sizeof *rows);
+ tokens = zalloc(groups * sizeof *tokens);
+ jump = zalloc((groups * 2 + 3) * sizeof *jump);
+ if (!rows || !tokens || !jump) {
+ release(rows);
+ release(tokens);
+ release(jump);
+ groups = 0;
+ goto done;
+ }
+ build_group_rows(browser, track_data, tracks, used, rows, &source);
+ struct group_sort sort = {track_data, rows, source};
+ sort_tracks(tracks, groups, compare_group_order, &sort);
+ build_group_jumps(track_data, rows, tracks, groups, native_jump, tokens, jump,
+ &source);
+ reorder(rows, tracks, groups);
+ drop_rows(browser);
+ RV_FIELD(browser, MediaBrowser_artists, struct group *) = rows;
+ RV_FIELD(browser, MediaBrowser_artists + sizeof(void *), struct group *) =
+ rows + groups;
+ RV_FIELD(browser, MediaBrowser_artists + 2 * sizeof(void *), struct group *) =
+ rows + groups;
+ RV_FIELD(browser, MediaBrowser_artist_tokens, uint32_t *) = tokens;
+ RV_FIELD(browser, MediaBrowser_artist_jump, uint32_t *) = jump;
+ RV_FIELD(browser, MediaBrowser_artist_count, uint32_t) = groups;
+done:
+ TrackData_ReleaseStringCaches(track_data);
+ release(tracks);
+ return groups;
+}
+
+/* Hooks */
+
+/* MediaBrowser_BuildArtists on an owned browser builds here. The slot takes
+ * the model, the call sites the browser. */
+uint32_t build_artists(uint32_t browser, const void *next)
+{
+ if (!context_for(ptr(browser)))
+ return api->hook_next(next, browser, 0, 0, 0, 0, 0);
+ return build(ptr(browser));
+}
+
+uint32_t build_artists_slot(uint32_t model, const void *next)
+{
+ void *browser = browser_of(ptr(model));
+ if (!context_for(browser))
+ return api->hook_next(next, model, 0, 0, 0, 0, 0);
+ return build(browser);
+}
+
+/* Apple's clear of an owned browser's rows: ours go first, so its Heap_Free
+ * sees nothing of them. */
+uint32_t clear_artists(uint32_t browser, const void *next)
+{
+ if (context_for(ptr(browser)))
+ drop_rows(ptr(browser));
+ return api->hook_next(next, browser, 0, 0, 0, 0, 0);
+}
+
+/* A group's name as a counted UTF-16 string of at most 255 units, Apple's
+ * status: 0, or -50 for an index outside the rows. */
+static int group_name(void *browser, int index, uint16_t *counted)
+{
+ counted[0] = 0;
+ if (index < 0 || (uint32_t)index >= group_count(browser))
+ return -50;
+ void *track_data = track_data_of(browser);
+ TrackData_AcquireStringCaches(track_data);
+ const uint16_t *text;
+ uint32_t units =
+ artist_name_view(track_data, groups_of(browser)[index].token, &text);
+ if (units > 255)
+ units = 255;
+ if (units && text[units - 1] >= 0xd800 && text[units - 1] <= 0xdbff)
+ units--;
+ counted[0] = (uint16_t)units;
+ for (uint32_t i = 0; i < units; i++)
+ counted[i + 1] = text[i];
+ TrackData_ReleaseStringCaches(track_data);
+ return 0;
+}
+
+static int group_letter(void *browser, int index, uint16_t *counted)
+{
+ counted[0] = 0;
+ if (index < 0 || (uint32_t)index >= group_count(browser))
+ return -50;
+ counted[0] = 1;
+ counted[1] = jump_letter(
+ RV_FIELD(browser, MediaBrowser_artist_jump, const uint32_t *), (uint32_t)index);
+ return 0;
+}
+
+/* Whether the entry is outside the selected group, with the caches pinned by
+ * Apple's filter evaluation. */
+static int outside_selected_group(void *browser, const struct MediaEntry *entry)
+{
+ int index = RV_FIELD(browser, MediaBrowser_selected_artist, int);
+ if (index < 0)
+ return 0;
+ const void *record = entry_record(entry);
+ if ((uint32_t)index >= group_count(browser) || !record)
+ return 1;
+ return compare_artist_names(track_data_of(browser), groups_of(browser)[index].token,
+ resolved_artist_token(record)) != 0;
+}
+
+/* The subtitle of an album row: its artist's name. */
+static void album_artist_subtitle(void *browser, int index, struct NativeString *out)
+{
+ struct album *begin = RV_FIELD(browser, MediaBrowser_albums, struct album *);
+ struct album *end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *);
+ if (index < 0 || index >= end - begin)
+ return;
+ void *track_data = track_data_of(browser);
+ TrackData_AcquireStringCaches(track_data);
+ const uint16_t *text;
+ uint32_t units = artist_name_view(track_data, begin[index].artist, &text);
+ NativeString_AssignUtf16(out, text, (int)units);
+ TrackData_ReleaseStringCaches(track_data);
+}
+
+uint32_t read_artist_name(uint32_t browser, uint32_t index, uint32_t out,
+ const void *next)
+{
+ if (!context_for(ptr(browser)))
+ return api->hook_next(next, browser, index, out, 0, 0, 0);
+ return (uint32_t)group_name(ptr(browser), (int)index, ptr(out));
+}
+
+uint32_t read_artist_jump_label(uint32_t browser, uint32_t index, uint32_t out,
+ const void *next)
+{
+ if (!context_for(ptr(browser)))
+ return api->hook_next(next, browser, index, out, 0, 0, 0);
+ return (uint32_t)group_letter(ptr(browser), (int)index, ptr(out));
+}
+
+/* The artist filter's compare in MediaBrowser_EvaluateEntryFilters: an owned
+ * browser matches the entry against the selected group instead of the artist
+ * text. Nonzero rejects the entry. */
+uint32_t artist_filter_compare(uint32_t browser, uint32_t left, uint32_t left_units,
+ uint32_t right, const void *next, uint32_t right_units,
+ uint32_t entry)
+{
+ if (!context_for(ptr(browser)))
+ return api->hook_next(next, 0, left, left_units, right, right_units, entry);
+ return (uint32_t)outside_selected_group(ptr(browser), ptr(entry));
+}
+
+/* MediaBrowser_BuildAlbums' accumulator, through the literal it loads: an
+ * owned browser groups its albums by the album token, with the resolved
+ * artist for the subtitle. ARM: AlbumGroupVector_Append ends in Apple's
+ * memcpy, which returns with mov pc, lr. */
+RV_ARM int album_group(void *browser, void *callback, uint32_t field_low,
+ uint32_t field_high, uint32_t index, struct MediaEntry *entry,
+ void *record, int first)
+{
+ if (!context_for(browser))
+ return MediaBrowser_AccumulateAlbumGroup(
+ browser, callback, field_low, field_high, index, entry, record, first);
+ struct album *begin = RV_FIELD(browser, MediaBrowser_albums, struct album *);
+ struct album *end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *);
+ if (first && begin != end)
+ return 0;
+ uint32_t album = RV_FIELD(record, MediaRecord_album, uint32_t);
+ if (!album)
+ return 1;
+ if (begin == end || end[-1].token != album) {
+ struct album row = {
+ album,
+ resolved_artist_token(record),
+ 0,
+ MediaBrowser_GetRecordArtworkId(MediaBrowser_GetOwner(browser), record),
+ 0,
+ ((RV_FIELD(record, MediaRecord_flags_15, uint8_t) &
+ MediaRecordFlags15_Compilation)
+ ? 1
+ : 0) |
+ ((RV_FIELD(record, MediaRecord_flags_8f, uint8_t) &
+ MediaRecordFlags8F_PlaceholderAlbum)
+ ? 2
+ : 0)};
+ AlbumGroupVector_Append((uint8_t *)browser + MediaBrowser_albums, &row);
+ end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *);
+ }
+ end[-1].tracks++;
+ return 1;
+}
+
+uint32_t album_subtitle(uint32_t model, uint32_t index, uint32_t out, const void *next)
+{
+ void *browser = browser_of(ptr(model));
+ if (!context_for(browser))
+ return api->hook_next(next, model, index, out, 0, 0, 0);
+ album_artist_subtitle(browser, (int)index, ptr(out));
+ return 0;
+}
+
+/* Artwork: the album source of an owned list reads through a borrowed
+ * model of its own, so Apple's artwork cache can outlive the screen. */
+
+static int release_artwork(void)
+{
+ if (custom_artwork_providers) {
+ void *session = ListArtworkSession_Get();
+ if (session) {
+ void *previous = artwork_model_reference;
+ artwork_model_reference = NULL;
+ ArtworkSession_Stop(session);
+ ListArtworkSession_SetSource(session, AlbumArtwork_Selector);
+ artwork_model_reference = previous;
+ }
+ }
+ return !custom_artwork_providers;
+}
+
+uint32_t select_artwork_source(uint32_t selection, uint32_t category, const void *next)
+{
+ void *reference = (uint8_t *)ptr(selection) + MediaListSelection_model;
+ void *model = LibraryModelRef_Get(reference);
+ int custom =
+ category == ArtworkCategory_Albums && model && context_for(browser_of(model));
+ /* The provider and cache are made again even when both screens are album
+ * categories. */
+ if (custom || custom_artwork_providers)
+ RV_FIELD(ptr(selection), MediaListSelection_artwork_category, uint8_t) = 0;
+ if (!custom)
+ release_artwork();
+ void *previous = artwork_model_reference;
+ artwork_model_reference = custom ? reference : NULL;
+ uint32_t result = api->hook_next(next, selection, category, 0, 0, 0, 0);
+ artwork_model_reference = previous;
+ return result;
+}
+
+/* ARM: Runtime_OperatorNew returns with mov pc, lr. */
+RV_ARM uint32_t create_artwork_provider(uint32_t kind, uint32_t selector,
+ const void *next)
+{
+ uint32_t provider = api->hook_next(next, kind, selector, 0, 0, 0, 0);
+ if (!provider || kind != ArtworkSource_SelectorKind ||
+ selector != AlbumArtwork_Selector || !artwork_model_reference)
+ return provider;
+ void *owner = LibraryModelRef_Get(artwork_model_reference);
+ struct artwork_model *model = Runtime_OperatorNew(sizeof *model);
+ if (!model)
+ return provider;
+ LibraryBrowser_InitBorrowed(model, 2, browser_of(owner));
+ model->owner_reference = NULL;
+ LibraryModelRef_Assign(&model->owner_reference, artwork_model_reference);
+ RV_FIELD(model, LibraryBrowser_ownership, uint8_t) = ARTWORK_MODEL_OWNERSHIP;
+ custom_artwork_providers++;
+ void *original = RV_FIELD(ptr(provider), AlbumArtworkProvider_model, void *);
+ RV_FIELD(ptr(provider), AlbumArtworkProvider_model, void *) = model;
+ typedef void (*destroy)(void *);
+ RV_METHOD(original, LibraryBrowser_delete_method, destroy)(original);
+ return provider;
+}
+
+/* LibraryBrowser_Destroy: the artwork model gives its reference back; an
+ * owned model's browser drops its rows and context. Apple's body follows. */
+uint32_t destroy_model(uint32_t model, const void *next)
+{
+ if (RV_FIELD(ptr(model), LibraryBrowser_ownership, uint8_t) ==
+ ARTWORK_MODEL_OWNERSHIP) {
+ if (custom_artwork_providers)
+ custom_artwork_providers--;
+ RV_FIELD(ptr(model), LibraryBrowser_ownership, uint8_t) =
+ LibraryBrowserOwnership_Borrowed;
+ LibraryModelRef_Release(&((struct artwork_model *)ptr(model))->owner_reference);
+ return api->hook_next(next, model, 0, 0, 0, 0, 0);
+ }
+ void *browser = browser_of(ptr(model));
+ struct context *context = context_for(browser);
+ if (context && RV_FIELD(ptr(model), LibraryBrowser_ownership, uint8_t) ==
+ LibraryBrowserOwnership_Child) {
+ if (context->track_data)
+ MediaBrowser_InvalidateEntryMatches(browser);
+ clear_groups(browser);
+ *context = (struct context){0};
+ }
+ return api->hook_next(next, model, 0, 0, 0, 0, 0);
+}
+
+/* Opening the list */
+
+static int owns_model(void *model)
+{
+ struct context *context = model ? context_for(browser_of(model)) : NULL;
+ return context && context->model_reference &&
+ LibraryModelRef_Get(&context->model_reference) == model;
+}
+
+/* The selection may still hold an owned model after its screens closed; when
+ * it is the sole owner, a stock model takes its place so the registry slot
+ * and the rows go. */
+static void release_cached_selection(void)
+{
+ void *selection = MediaListSelection_GetInstance();
+ void **reference = (void **)((uint8_t *)selection + MediaListSelection_model);
+ void *model = LibraryModelRef_Get(reference);
+ const uint32_t *block = *reference;
+ if (!owns_model(model) ||
+ RV_FIELD(model, LibraryBrowser_ownership, uint8_t) !=
+ LibraryBrowserOwnership_Child ||
+ !block || block[LibraryModelRefBlock_count / 4] != 1)
+ return;
+ void *stock = LibraryBrowser_Create(0);
+ if (!stock)
+ return;
+ void *replacement = NULL;
+ LibraryModelRef_Init(&replacement, stock, 0);
+ MediaListSelection_SetList(selection, &replacement, 1, 0, 0);
+ LibraryModelRef_Release(&replacement);
+}
+
+/* A model over a child browser of the shared music browser, in two free
+ * registry slots. */
+static void *create_model(void **reference)
+{
+ if (!release_artwork())
+ return NULL;
+ void **registry = (void **)BrowserRegistry;
+ unsigned available = 0;
+ for (unsigned i = 0; i < 4; i++)
+ available += registry[i] == NULL;
+ if (available < 2)
+ return NULL;
+ void *model = LibraryBrowser_Create(0);
+ if (!model)
+ return NULL;
+ void *browser = NULL;
+ typedef void (*destroy)(void *);
+ if (MediaBrowser_CreateChild(browser_of(model), &browser) || !browser) {
+ RV_METHOD(model, LibraryBrowser_delete_method, destroy)(model);
+ return NULL;
+ }
+ RV_FIELD(model, LibraryBrowser_browser, void *) = browser;
+ RV_FIELD(model, LibraryBrowser_ownership, uint8_t) = LibraryBrowserOwnership_Child;
+ LibraryModelRef_Init(reference, model, 0);
+ return model;
+}
+
+static void *acquire_model(void **reference)
+{
+ /* The selection or the artwork cache may keep the last model. */
+ for (unsigned i = 0; i < 4; i++)
+ if (contexts[i].model_reference) {
+ LibraryModelRef_Assign(reference, &contexts[i].model_reference);
+ return LibraryModelRef_Get(reference);
+ }
+ void *model = create_model(reference);
+ if (!model)
+ return NULL;
+ void *browser = browser_of(model);
+ unsigned slot = RV_FIELD(browser, MediaBrowser_registry_slot, uint8_t);
+ contexts[slot] = (struct context){browser, track_data_of(browser), *reference};
+ return model;
+}
+
+/* The model's query as the stock Artists list configures it: reset, artist
+ * sort, the kinds the Music menu includes (the kind masks take GameMediaKind
+ * bits). */
+static void prepare_artists(void *model)
+{
+ typedef void (*reset)(void *);
+ typedef void (*configure)(void *, uint32_t, uint32_t);
+ RV_METHOD(model, LibraryBrowser_reset_method, reset)(model);
+ RV_METHOD(model, LibraryBrowser_artist_sort_method, reset)(model);
+ RV_METHOD(model, LibraryBrowser_kind_masks_method,
+ configure)(model, GameMediaKind_Music | GameMediaKind_MusicVideo, 0);
+}
+
+void browser_open(const struct rv_context *ctx)
+{
+ void *reference = NULL;
+ /* The shared music browser's query, which a child browser starts from:
+ * music only, as the stock Artists row sets it. */
+ if (!MusicMenu_ConfigureLibraryBrowser(ctx->controller, MediaKind_Music, 0, 1,
+ LibraryGrouping_Artists, LibrarySort_Artist,
+ 0))
+ return;
+ void *model = acquire_model(&reference);
+ if (!model)
+ return;
+ if (!release_artwork())
+ goto done;
+ prepare_artists(model);
+ if (!build(browser_of(model)))
+ goto done;
+ /* The stock Artists screen titles itself from the selection. */
+ _Alignas(uint32_t) uint8_t storage[NativeString_bytes];
+ struct NativeString *title =
+ NativeString_InitUtf8((struct NativeString *)storage, "Album Artists");
+ MediaListSelection_SetTitle(MediaListSelection_GetInstance(), title);
+ NativeString_Destroy(title);
+ void *screen = UI_CreateScreenController(
+ UI_GetControllerRegistry(), RES_MediaLists_Artists_Screen,
+ RES_MediaLists_Artists_Screen_Default, Transition_ForegroundPush);
+ if (!screen)
+ goto done;
+ LibraryModelRef_Assign((uint8_t *)screen + MediaListController_model, &reference);
+ RV_FIELD(screen, MediaListController_created_model, uint8_t) = 0;
+ rv_controller_push(ctx->controller, screen);
+done:
+ LibraryModelRef_Release(&reference);
+}
+
+/* While the hooks are still bound: the artwork cache and the selection give
+ * back the models over owned browsers, so none outlives the module. */
+void browser_unload(void)
+{
+ release_artwork();
+ release_cached_selection();
+ for (unsigned i = 0; i < 4; i++) {
+ struct context *context = &contexts[i];
+ if (!context->browser)
+ continue;
+ if (context->track_data)
+ MediaBrowser_InvalidateEntryMatches(context->browser);
+ clear_groups(context->browser);
+ *context = (struct context){0};
+ }
+}
diff --git a/extensions/album-artists/browser.h b/extensions/album-artists/browser.h
new file mode 100644
index 0000000..c9471b3
--- /dev/null
+++ b/extensions/album-artists/browser.h
@@ -0,0 +1,44 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The Album Artists list: a browser of the extension's own on the stock
+ * Artists screen, grouped by the fields table's Album Artist with the Artist
+ * as the fallback. */
+
+#ifndef ALBUM_ARTISTS_BROWSER_H
+#define ALBUM_ARTISTS_BROWSER_H
+#include "rv_api.h"
+#include
+
+/* Opens the list above the menu of `ctx`. */
+void browser_open(const struct rv_context *ctx);
+
+/* The fields table of `track_data` is going: the owned browsers drop their rows. */
+void browser_invalidate(void *track_data);
+
+/* On unload: the owned browsers drop their rows and contexts. */
+void browser_unload(void);
+
+/* The handlers main.c binds: MediaBrowser_BuildArtists through the model's
+ * slot and its two call sites, Apple's clear of the rows, the row readers,
+ * the artist filter compare, the album accumulator BuildAlbums loads from
+ * its literal, the album subtitle, the artwork source and provider, and
+ * LibraryBrowser_Destroy. */
+uint32_t build_artists_slot(uint32_t model, const void *next);
+uint32_t build_artists(uint32_t browser, const void *next);
+uint32_t clear_artists(uint32_t browser, const void *next);
+uint32_t read_artist_name(uint32_t browser, uint32_t index, uint32_t out,
+ const void *next);
+uint32_t read_artist_jump_label(uint32_t browser, uint32_t index, uint32_t out,
+ const void *next);
+uint32_t artist_filter_compare(uint32_t browser, uint32_t left, uint32_t left_units,
+ uint32_t right, const void *next, uint32_t right_units,
+ uint32_t entry);
+struct MediaEntry;
+int album_group(void *browser, void *callback, uint32_t field_low, uint32_t field_high,
+ uint32_t index, struct MediaEntry *entry, void *record, int first);
+uint32_t album_subtitle(uint32_t model, uint32_t index, uint32_t out, const void *next);
+uint32_t select_artwork_source(uint32_t selection, uint32_t category, const void *next);
+uint32_t create_artwork_provider(uint32_t kind, uint32_t selector, const void *next);
+uint32_t destroy_model(uint32_t model, const void *next);
+
+#endif
diff --git a/extensions/album-artists/fields.c b/extensions/album-artists/fields.c
new file mode 100644
index 0000000..5170d81
--- /dev/null
+++ b/extensions/album-artists/fields.c
@@ -0,0 +1,290 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Apple's importer discards the Album Artist (mhod 22), Sort Artist (23) and
+ * Sort Album Artist (29) strings. These hooks intern them in the TrackData's
+ * artist cache instead and keep one 20-byte row per song that needs one: a
+ * song whose Album Artist is its Artist and that carries no Sort As stores
+ * nothing, because the browser resolves a missing Album Artist to the Artist.
+ * While the import runs the rows collect in fixed chunks; when it ends they
+ * move into one exact-size block, each chunk freed as it is copied, and the
+ * block is heapsorted by persistent id for binary search.
+ *
+ * The mhods of one mhit are parsed before the next mhit begins, so one
+ * pending record collects a song's values and is flushed when another record
+ * arrives and when the dataset parse returns; by then the record's own Artist
+ * token is final. No token is ever released: a string the cache already holds
+ * comes back as the same token without a further reference, so one release by
+ * anyone frees it for every record that names it. The strings live as long as
+ * the TrackData, whose destruction drops them all.
+ *
+ * Based on RepriseOS payload/album_artist.c (bfedd72) by lgreitis. */
+
+#include "fields.h"
+#include "browser.h"
+#include "shared.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include
+
+enum { TOKEN, SORT_ALBUM_ARTIST, SORT_ARTIST, TOKENS };
+
+#define CHUNK_ROWS 256
+
+struct row {
+ uint32_t id_low, id_high;
+ uint32_t tokens[TOKENS];
+};
+
+/* The rows of an import in progress, newest chunk first. */
+struct chunk {
+ struct chunk *next;
+ uint32_t count;
+ struct row rows[CHUNK_ROWS];
+};
+
+static struct {
+ void *owner; /* the TrackData of the import, NULL before the first */
+ void *cache; /* its artist string cache */
+ struct chunk *chunks;
+ struct row *rows; /* the sorted table once sealed */
+ uint32_t count;
+ uint8_t sealed; /* a later mhod only skips its bytes */
+
+ struct {
+ const void *record;
+ uint32_t tokens[TOKENS];
+ } pending;
+} table;
+
+static void drop_chunks(void)
+{
+ while (table.chunks) {
+ struct chunk *next = table.chunks->next;
+ api->free(self, table.chunks);
+ table.chunks = next;
+ }
+}
+
+static void clear(void)
+{
+ if (table.owner)
+ browser_invalidate(table.owner);
+ drop_chunks();
+ if (table.rows)
+ api->free(self, table.rows);
+ table.rows = NULL;
+ table.count = 0;
+ table.sealed = 0;
+ table.pending.record = NULL;
+ for (unsigned i = 0; i < TOKENS; i++)
+ table.pending.tokens[i] = 0;
+}
+
+static const uint32_t *persistent_id(const void *record)
+{
+ return &RV_FIELD(record, TrackData_dbid, const uint32_t);
+}
+
+static int before(const struct row *row, const uint32_t *id)
+{
+ return row->id_high < id[1] || (row->id_high == id[1] && row->id_low < id[0]);
+}
+
+static void append(const void *record, const uint32_t *tokens)
+{
+ struct chunk *chunk = table.chunks;
+ if (!chunk || chunk->count == CHUNK_ROWS) {
+ chunk = api->alloc(self, sizeof *chunk);
+ if (!chunk)
+ return;
+ chunk->next = table.chunks;
+ table.chunks = chunk;
+ }
+ struct row *row = &chunk->rows[chunk->count++];
+ table.count++;
+ const uint32_t *id = persistent_id(record);
+ row->id_low = id[0];
+ row->id_high = id[1];
+ for (unsigned i = 0; i < TOKENS; i++)
+ row->tokens[i] = tokens[i];
+}
+
+static void flush(void)
+{
+ const void *record = table.pending.record;
+ uint32_t *tokens = table.pending.tokens;
+ if (!record)
+ return;
+ table.pending.record = NULL;
+ /* Nothing to keep when the Album Artist is the Artist or empty and no
+ * Sort As came with it. */
+ uint32_t token = tokens[TOKEN];
+ int same = (!token || token == RV_FIELD(record, MediaRecord_artist, uint32_t)) &&
+ !tokens[SORT_ALBUM_ARTIST] && !tokens[SORT_ARTIST];
+ if (!same)
+ append(record, tokens);
+ for (unsigned i = 0; i < TOKENS; i++)
+ tokens[i] = 0;
+}
+
+static void sift(struct row *rows, uint32_t root, uint32_t count)
+{
+ while (root < count / 2) {
+ uint32_t child = root * 2 + 1;
+ if (child + 1 < count && before(&rows[child], &rows[child + 1].id_low))
+ child++;
+ if (!before(&rows[root], &rows[child].id_low))
+ break;
+ struct row swap = rows[root];
+ rows[root] = rows[child];
+ rows[child] = swap;
+ root = child;
+ }
+}
+
+/* The chunks into one exact-size block, heapsorted by persistent id in place.
+ * Without memory for the block the import's rows are dropped. */
+static void finish(void)
+{
+ uint32_t count = table.count;
+ struct row *rows = count ? api->alloc(self, count * sizeof *rows) : NULL;
+ uint32_t at = 0;
+ while (table.chunks) {
+ struct chunk *chunk = table.chunks;
+ if (rows)
+ for (uint32_t i = 0; i < chunk->count; i++)
+ rows[at++] = chunk->rows[i];
+ table.chunks = chunk->next;
+ api->free(self, chunk);
+ }
+ table.rows = rows;
+ table.count = rows ? count : 0;
+ table.sealed = 1;
+ if (!rows)
+ return;
+ for (uint32_t i = count / 2; i; i--)
+ sift(rows, i - 1, count);
+ for (uint32_t i = count; i > 1; i--) {
+ struct row swap = rows[0];
+ rows[0] = rows[i - 1];
+ rows[i - 1] = swap;
+ sift(rows, 0, i - 1);
+ }
+}
+
+void fields_import_begin(void *reader)
+{
+ clear();
+ table.owner = RV_FIELD(reader, ITunesReader_owner, void *);
+ table.cache = (uint8_t *)table.owner + TrackData_artist_cache;
+}
+
+void fields_import_end(int status)
+{
+ flush();
+ if (status)
+ clear();
+ else
+ finish();
+}
+
+int fields_import_mhod(void *reader, uint32_t body_bytes, void *record,
+ uint32_t mhod_type)
+{
+ /* Apple's skip treats a negative length as a seek back. */
+ if (body_bytes > INT32_MAX)
+ return -0xd0;
+ if (!table.owner || table.sealed || body_bytes < 16)
+ return ITunesDB_SkipImportBytes(reader, (int32_t)body_bytes);
+ void *file = RV_FIELD(reader, ITunesReader_file, void *);
+ uint64_t start, end;
+ if (BufferedFile_GetPosition(file, &start))
+ return ITunesDB_SkipImportBytes(reader, (int32_t)body_bytes);
+ /* Apple's own arguments for an artist string: UTF-16 in the file, the
+ * artist cache's glyph collection. */
+ uint32_t token = 0;
+ int status =
+ ITunesDB_ImportCachedString(reader, 1, mhod_type, table.cache, &token, 1, 1);
+ int cursor = BufferedFile_GetPosition(file, &end);
+ if (cursor || end < start || end - start > body_bytes)
+ return cursor ? cursor : -0xd0;
+ /* The padding the decode left, also after a failed optional field. */
+ int trailing = ITunesDB_SkipImportBytes(
+ reader, (int32_t)(body_bytes - (uint32_t)(end - start)));
+ if (trailing)
+ return trailing;
+ if (status)
+ token = 0;
+ if (table.pending.record != record)
+ flush();
+ table.pending.record = record;
+ unsigned which = mhod_type == MHOD_SORT_ALBUM_ARTIST ? SORT_ALBUM_ARTIST
+ : mhod_type == MHOD_SORT_ARTIST ? SORT_ARTIST
+ : TOKEN;
+ table.pending.tokens[which] = token;
+ return 0;
+}
+
+void fields_destroy(void *track_data)
+{
+ if (track_data == table.owner) {
+ clear();
+ table.owner = table.cache = NULL;
+ }
+}
+
+int fields_imported(void)
+{
+ return table.owner != NULL;
+}
+
+static const struct row *lookup(const void *record)
+{
+ if (!record || !table.sealed || !table.count ||
+ *(void *const *)record != table.owner)
+ return NULL;
+ const uint32_t *id = persistent_id(record);
+ uint32_t low = 0, high = table.count;
+ while (low < high) {
+ uint32_t middle = low + (high - low) / 2;
+ if (before(&table.rows[middle], id))
+ low = middle + 1;
+ else
+ high = middle;
+ }
+ const struct row *row = &table.rows[low];
+ return low < table.count && row->id_high == id[1] && row->id_low == id[0] ? row
+ : NULL;
+}
+
+uint32_t fields_token(const void *record)
+{
+ const struct row *row = lookup(record);
+ return row ? row->tokens[TOKEN] : 0;
+}
+
+uint32_t fields_sort_token(const void *record, int album_artist)
+{
+ const struct row *row = lookup(record);
+ return row ? row->tokens[album_artist ? SORT_ALBUM_ARTIST : SORT_ARTIST] : 0;
+}
+
+uint32_t fields_read(const void *record, uint16_t *text, uint32_t max_units)
+{
+ uint32_t token = fields_token(record);
+ if (!token || token == RV_FIELD(record, MediaRecord_artist, uint32_t) ||
+ !max_units || max_units > INT32_MAX / 2)
+ return 0;
+ uint32_t bytes = 0;
+ if (StringCache_ReadToken(table.cache, token, text, &bytes, max_units * 2))
+ return 0;
+ uint32_t units = bytes / 2;
+ if (units && text[units - 1] >= 0xd800 && text[units - 1] <= 0xdbff)
+ units--;
+ return units;
+}
+
+uint32_t fields_count(void)
+{
+ return table.count;
+}
diff --git a/extensions/album-artists/fields.h b/extensions/album-artists/fields.h
new file mode 100644
index 0000000..140031f
--- /dev/null
+++ b/extensions/album-artists/fields.h
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The Album Artist, Sort Artist and Sort Album Artist of each song, kept by
+ * persistent id through the iTunesDB import. Tokens name strings in the
+ * TrackData's artist cache; 0 means absent. */
+
+#ifndef ALBUM_ARTISTS_FIELDS_H
+#define ALBUM_ARTISTS_FIELDS_H
+#include
+
+/* The iTunesDB mhod types Apple discards. */
+enum { MHOD_ALBUM_ARTIST = 22, MHOD_SORT_ARTIST = 23, MHOD_SORT_ALBUM_ARTIST = 29 };
+
+/* The import hooks: the parse of a track dataset begins and ends, and one of
+ * the mhod types Apple discards is reached with the record being filled. The
+ * mhod call returns Apple's status for the import loop. */
+void fields_import_begin(void *reader);
+void fields_import_end(int status);
+int fields_import_mhod(void *reader, uint32_t body_bytes, void *record,
+ uint32_t mhod_type);
+
+/* Apple destroys a TrackData's storage: the table of that TrackData goes. */
+void fields_destroy(void *track_data);
+
+/* Whether an import has run on the current TrackData since the module loaded. */
+int fields_imported(void);
+
+uint32_t fields_token(const void *record);
+/* The Sort Album Artist when `album_artist` is set, else the Sort Artist. */
+uint32_t fields_sort_token(const void *record, int album_artist);
+uint32_t fields_read(const void *record, uint16_t *text, uint32_t max_units);
+
+/* For the host tests. */
+uint32_t fields_count(void);
+
+#endif
diff --git a/extensions/album-artists/listing.toml b/extensions/album-artists/listing.toml
new file mode 100644
index 0000000..4ab9b1e
--- /dev/null
+++ b/extensions/album-artists/listing.toml
@@ -0,0 +1,11 @@
+details = "Choose Album Artists in Music to browse the library by Album Artist, with the Artist as the fallback. Settings > Music Menu and Settings > Main Menu show or hide the row."
+
+icon = "assets/settings-album-artists.png"
+
+[[screenshots]]
+file = "screenshots/list.png"
+alt = "The Album Artists list: All Albums, then the album artists of the library."
+
+[[screenshots]]
+file = "screenshots/albums.png"
+alt = "An album artist's albums with their artwork and song counts."
diff --git a/extensions/album-artists/main.c b/extensions/album-artists/main.c
new file mode 100644
index 0000000..426f5ba
--- /dev/null
+++ b/extensions/album-artists/main.c
@@ -0,0 +1,132 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Album Artists: a row in Music and on the main menu that lists the library by
+ * Album Artist, falling back to Artist, on the stock Artists screen. The
+ * import hooks keep the Album Artist, Sort Artist and Sort Album Artist tags
+ * Apple discards (fields.c); the list is a browser of the extension's own
+ * (browser.c).
+ *
+ * Based on RepriseOS payload/album_artists.c (bfedd72) by lgreitis. */
+
+#include "browser.h"
+#include "fields.h"
+#include "service.h"
+#include "shared.h"
+#include "../shared/menu_visibility.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_menus.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+#include
+
+const struct rv_api *api;
+rv_extension_handle self;
+
+/* The reader of the dataset parse in progress, for the mhod hooks. */
+static void *importing;
+
+/* ITunesDB_ImportTrackDataset: the table of this TrackData is built here. */
+static uint32_t import_track_dataset(uint32_t reader, const void *next)
+{
+ fields_import_begin((void *)reader);
+ importing = (void *)reader;
+ uint32_t status = api->hook_next(next, reader, 0, 0, 0, 0, 0);
+ importing = NULL;
+ fields_import_end((int)status);
+ return status;
+}
+
+/* The two discard calls of the mhod switch: (file or reader, bytes), with the
+ * record and the mhod type copied from Apple's registers. */
+static uint32_t discard_mhod(uint32_t target, uint32_t bytes, uint32_t record,
+ uint32_t type, const void *next)
+{
+ if (importing && (type == MHOD_ALBUM_ARTIST || type == MHOD_SORT_ARTIST ||
+ type == MHOD_SORT_ALBUM_ARTIST))
+ return (uint32_t)fields_import_mhod(importing, bytes, (void *)record, type);
+ return api->hook_next(next, target, bytes, record, type, 0, 0);
+}
+
+static uint32_t destroy_storage(uint32_t track_data, const void *next)
+{
+ browser_invalidate((void *)track_data);
+ fields_destroy((void *)track_data);
+ return api->hook_next(next, track_data, 0, 0, 0, 0, 0);
+}
+
+static void unload(void)
+{
+ browser_unload();
+}
+
+static const struct rv_hook hooks[] = {
+ RV_HOOK_FILTER(RV_SITE_ITunesDB_ImportTrackDataset_call, import_track_dataset),
+ RV_HOOK_FILTER(RV_SITE_ITunesDB_DiscardMhod_call, discard_mhod),
+ RV_HOOK_FILTER(RV_SITE_ITunesDB_SkipMhod_call, discard_mhod),
+ RV_HOOK_FILTER(RV_SITE_TrackData_DestroyStorage_call, destroy_storage),
+ RV_HOOK_FILTER(RV_SITE_LibraryBrowser_BuildArtists_slot, build_artists_slot),
+ RV_HOOK_FILTER(RV_SITE_MediaBrowser_BuildArtists_RefreshCounts_call, build_artists),
+ RV_HOOK_FILTER(RV_SITE_MediaBrowser_BuildArtists_SecondaryInit_call, build_artists),
+ RV_HOOK_FILTER(RV_SITE_MediaBrowser_ClearArtists_entry, clear_artists),
+ RV_HOOK_FILTER(RV_SITE_MediaBrowser_ReadArtistName_entry, read_artist_name),
+ RV_HOOK_FILTER(RV_SITE_MediaBrowser_ReadArtistJumpLabel_entry,
+ read_artist_jump_label),
+ RV_HOOK_FILTER(RV_SITE_MediaBrowser_ArtistFilterCompare_call,
+ artist_filter_compare),
+ RV_HOOK_POINTER(RV_SITE_AlbumGroup_literal, album_group),
+ RV_HOOK_FILTER(RV_SITE_AlbumSubtitle_slot, album_subtitle),
+ RV_HOOK_FILTER(RV_SITE_MediaListSelection_SelectArtworkSource_call,
+ select_artwork_source),
+ RV_HOOK_FILTER(RV_SITE_AlbumArtworkProvider_Create_call, create_artwork_provider),
+ RV_HOOK_FILTER(RV_SITE_LibraryBrowser_Destroy_entry, destroy_model),
+};
+
+static const struct rv_menu_entry entries[] = {
+ RV_MENU_ENTRY(RV_MENU_MUSIC, RV_MUSIC_ARTISTS,
+ RV_ROW_ACTION("Album Artists", browser_open),
+ .shown_by = KEY_IN_MUSIC),
+ RV_MENU_ENTRY(RV_MENU_MAIN, RV_MAIN_ARTISTS,
+ RV_ROW_ACTION("Album Artists", browser_open), .shown_by = KEY_IN_MAIN,
+ .preview = RV_PREVIEW_MUSIC),
+};
+
+static const struct rv_setting settings[] = {
+ RV_SETTING_BOOL(KEY_IN_MUSIC, "Album Artists in Music", 1),
+ RV_SETTING_BOOL(KEY_IN_MAIN, "Album Artists in Main Menu", 0),
+};
+
+static const struct album_artists_service service = {fields_read};
+
+/* The old core's built-in Album Artists row in its menu visibility record. */
+#define OLD_MENU_KEY 0xdf951f53
+
+static int first_load = 1;
+
+static void changed(uint16_t key)
+{
+ if (key == RV_SETTING_KEY_ALL) {
+ int import = first_load;
+ first_load = 0;
+ migrate_menu_visibility(api, self, import, OLD_MENU_KEY, KEY_IN_MUSIC, 1,
+ KEY_IN_MAIN, 0);
+ }
+}
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+ .unload = unload,
+ RV_SETTINGS(settings),
+ .setting_changed = changed,
+ RV_ENTRIES(entries),
+ .service = &service,
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ api = core;
+ self = handle;
+ return &extension;
+}
diff --git a/extensions/album-artists/manifest.toml b/extensions/album-artists/manifest.toml
new file mode 100644
index 0000000..7979545
--- /dev/null
+++ b/extensions/album-artists/manifest.toml
@@ -0,0 +1,16 @@
+id = "album-artists"
+name = "Album Artists"
+description = "Browse the library by Album Artist, falling back to Artist, from Music or the Main Menu."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "media"
+
+[libraries]
+optional = ["reprise"]
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/album-artists/screenshots/albums.png b/extensions/album-artists/screenshots/albums.png
new file mode 100644
index 0000000..b340477
Binary files /dev/null and b/extensions/album-artists/screenshots/albums.png differ
diff --git a/extensions/album-artists/screenshots/list.png b/extensions/album-artists/screenshots/list.png
new file mode 100644
index 0000000..b74540a
Binary files /dev/null and b/extensions/album-artists/screenshots/list.png differ
diff --git a/extensions/album-artists/service.h b/extensions/album-artists/service.h
new file mode 100644
index 0000000..ab5286c
--- /dev/null
+++ b/extensions/album-artists/service.h
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* What Album Artists offers other extensions through api->extension_service. */
+
+#ifndef ALBUM_ARTISTS_SERVICE_H
+#define ALBUM_ARTISTS_SERVICE_H
+#include
+
+#define ALBUM_ARTISTS_ID "album-artists"
+
+struct album_artists_service {
+ /* UTF-16 units of the record's Album Artist into `text`, when it differs
+ * from the record's Artist; 0 otherwise, or while no library is imported. */
+ uint32_t (*read)(const void *record, uint16_t *text, uint32_t max_units);
+};
+
+#endif
diff --git a/extensions/album-artists/shared.h b/extensions/album-artists/shared.h
new file mode 100644
index 0000000..8ddf5ad
--- /dev/null
+++ b/extensions/album-artists/shared.h
@@ -0,0 +1,22 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The core table and handle every file of the module calls through. */
+
+#ifndef ALBUM_ARTISTS_SHARED_H
+#define ALBUM_ARTISTS_SHARED_H
+#include "rv_api.h"
+#include
+
+#define KEY_IN_MUSIC 1 /* Settings > Music Menu and Main Menu flip these two */
+#define KEY_IN_MAIN 2
+
+extern const struct rv_api *api;
+extern rv_extension_handle self;
+
+/* A hook argument as the pointer it carries. */
+static inline void *ptr(uint32_t word)
+{
+ return (void *)(uintptr_t)word;
+}
+
+#endif
diff --git a/extensions/album-artists/tests/browser_contracts.c b/extensions/album-artists/tests/browser_contracts.c
new file mode 100644
index 0000000..8c97cd4
--- /dev/null
+++ b/extensions/album-artists/tests/browser_contracts.c
@@ -0,0 +1,536 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include
+#include
+#include
+#include
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_media.h"
+
+/* Apple's row layouts hold pointers; the host's are wider, and the host
+ * compiler knows no ARM attribute. */
+#define _Static_assert(...)
+#undef RV_ARM
+#define RV_ARM
+#include "../fields.h"
+#include "../browser.c"
+
+/* The host doubles as the core: counted blocks from alloc and free. */
+static unsigned live_blocks;
+static int fail_alloc;
+
+static void *host_alloc(rv_extension_handle s, uint32_t bytes)
+{
+ (void)s;
+ if (fail_alloc && ++fail_alloc == 4)
+ return NULL;
+ void *block = calloc(1, bytes);
+ assert(block);
+ live_blocks++;
+ return block;
+}
+
+static void host_free(rv_extension_handle s, void *block)
+{
+ (void)s;
+ assert(live_blocks);
+ live_blocks--;
+ free(block);
+}
+static const struct rv_api host_api = {.alloc = host_alloc, .free = host_free};
+const struct rv_api *api = &host_api;
+rv_extension_handle self;
+
+/* One owned browser over a TrackData, a list of six entries and their records. */
+static _Alignas(16) uint8_t browser[MediaBrowser_track_data + 8];
+static _Alignas(16) uint8_t owner[MediaBrowser_track_data + 8];
+static _Alignas(16) uint8_t track_data[TrackData_artist_cache + 0x58];
+static _Alignas(16) uint8_t list[MediaList_jump_index + 0x40 * 8];
+static _Alignas(16) uint8_t root[MediaEntry_size];
+static uint8_t *native_order; /* a MediaOrder, or NULL */
+static uint32_t *native_jump;
+static unsigned pins;
+
+static _Alignas(16) uint8_t records[6][TrackData_dbid + 8];
+
+/* What the fields table and the filter answer for each record. */
+static struct tags {
+ uint32_t album_artist, sort_artist, sort_album_artist;
+ int accepted;
+} tags[6];
+
+static struct tags *tags_of(const void *record)
+{
+ return &tags[((const uint8_t *)record - records[0]) / sizeof records[0]];
+}
+
+static _Alignas(16) uint8_t entries[6][MediaEntry_size];
+static const uint16_t *strings[] = {
+ u"", u"The Clash", u"The Cure", u"Alpha", u"Guest", u"Clash",
+ u"Cure", u"Zulu", u"Aardvark", u"The Zebra", u"Theatre", u"An Artist",
+};
+
+/* The fields table, as the test sets it per record. */
+uint32_t fields_token(const void *r)
+{
+ return tags_of(r)->album_artist;
+}
+
+uint32_t fields_sort_token(const void *r, int album_artist)
+{
+ return album_artist ? tags_of(r)->sort_album_artist : tags_of(r)->sort_artist;
+}
+
+void *MediaBrowser_GetOwner(void *b)
+{
+ assert(b == browser);
+ return owner;
+}
+
+struct MediaList *MediaBrowser_GetCurrentList(void *b)
+{
+ assert(b == browser);
+ return (struct MediaList *)list;
+}
+
+int MediaBrowser_EvaluateEntryFilters(void *b, struct MediaEntry *entry,
+ struct MediaList *override)
+{
+ assert(b == browser && !override);
+ return tags_of(RV_FIELD(entry, MediaEntry_song_record, void *))->accepted;
+}
+
+uint32_t MediaBrowser_GetRecordArtworkId(void *o, void *record)
+{
+ assert(o == owner);
+ return RV_FIELD(record, MediaRecord_album, uint32_t) == 2 ? 0x200 : 0;
+}
+
+static unsigned clears;
+
+void MediaBrowser_ClearArtists(void *b)
+{
+ assert(b == browser && !RV_FIELD(b, MediaBrowser_artists, void *) &&
+ !RV_FIELD(b, MediaBrowser_artist_tokens, void *));
+ clears++;
+}
+
+void MediaBrowser_ClearAlbums(void *b)
+{
+ assert(b == browser);
+}
+
+void MediaBrowser_ClearSongs(void *b)
+{
+ assert(b == browser);
+}
+
+int MediaBrowser_InvalidateEntryMatches(void *b)
+{
+ assert(b == browser);
+ return 0;
+}
+
+void Heap_Free(void *block)
+{
+ assert(!block);
+}
+
+struct MediaEntry *MediaList_GetEntryByOrderIndex(struct MediaList *l, int mode,
+ uint32_t reverse, uint32_t index)
+{
+ assert((void *)l == list && mode == MediaOrderMode_Album && !reverse && index < 6);
+ return (struct MediaEntry *)entries[index];
+}
+
+int StringCache_GetTokenView(void *cache, uint32_t token, void **data, uint32_t *bytes)
+{
+ assert(cache == track_data + TrackData_artist_cache && pins);
+ assert(token < sizeof strings / sizeof *strings);
+ *data = (void *)strings[token];
+ *bytes = 0;
+ while (strings[token][*bytes / 2])
+ *bytes += 2;
+ return 0;
+}
+
+void TrackData_AcquireStringCaches(void *t)
+{
+ assert(t == track_data);
+ pins++;
+}
+
+void TrackData_ReleaseStringCaches(void *t)
+{
+ assert(t == track_data && pins);
+ pins--;
+}
+
+/* Apple's compare: case-insensitive after leading blanks, as far as the
+ * grouping needs. */
+int SongText_CompareUtf16(void *collation, const uint16_t *a, uint32_t na,
+ const uint16_t *b, uint32_t nb)
+{
+ assert(!collation);
+ while (na && *a <= ' ') {
+ a++;
+ na--;
+ }
+ while (nb && *b <= ' ') {
+ b++;
+ nb--;
+ }
+ for (uint32_t i = 0; i < na && i < nb; i++) {
+ uint16_t x = a[i] | 32, y = b[i] | 32;
+ if (x != y)
+ return x < y ? -1 : 1;
+ }
+ return (na > nb) - (na < nb);
+}
+
+static struct {
+ uint32_t units;
+ uint16_t text[64];
+} assigned;
+
+void NativeString_AssignUtf16(struct NativeString *s, const uint16_t *text,
+ int characters)
+{
+ (void)s;
+ assigned.units = (uint32_t)characters;
+ memcpy(assigned.text, text, (size_t)characters * 2);
+}
+
+static _Alignas(16) uint8_t album_storage[8 * AlbumGroup_bytes];
+
+void AlbumGroupVector_Append(void *vector, const void *row)
+{
+ assert(vector == browser + MediaBrowser_albums);
+ struct album *end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *);
+ if (!end) {
+ RV_FIELD(browser, MediaBrowser_albums, void *) = album_storage;
+ end = (struct album *)album_storage;
+ }
+ memcpy(end, row, sizeof *end);
+ RV_FIELD(browser, MediaBrowser_albums_end, struct album *) = end + 1;
+}
+
+int MediaBrowser_AccumulateAlbumGroup(void *b, void *c, uint32_t lo, uint32_t hi,
+ uint32_t i, struct MediaEntry *e, void *r,
+ int first)
+{
+ (void)b, (void)c, (void)lo, (void)hi, (void)i, (void)e, (void)r, (void)first;
+ abort();
+}
+
+/* Not reached by these tests: the open path and the artwork provider need the
+ * emulator. */
+void *LibraryBrowser_Create(uint32_t o)
+{
+ (void)o;
+ abort();
+}
+
+void *LibraryBrowser_InitBorrowed(void *m, uint8_t f, void *b)
+{
+ (void)m, (void)f, (void)b;
+ abort();
+}
+
+void *LibraryModelRef_Init(void *r, void *m, int s)
+{
+ (void)r, (void)m, (void)s;
+ abort();
+}
+
+void *LibraryModelRef_Assign(void *d, void *s)
+{
+ (void)d, (void)s;
+ abort();
+}
+
+void LibraryModelRef_Release(void *r)
+{
+ (void)r;
+ abort();
+}
+
+void *LibraryModelRef_Get(void *r)
+{
+ (void)r;
+ abort();
+}
+
+void *MediaListSelection_GetInstance(void)
+{
+ abort();
+}
+
+void *MediaListSelection_SetTitle(void *s, const struct NativeString *t)
+{
+ (void)s, (void)t;
+ abort();
+}
+
+struct NativeString *NativeString_InitUtf8(struct NativeString *s, const char *u)
+{
+ (void)s, (void)u;
+ abort();
+}
+
+struct NativeString *NativeString_Destroy(struct NativeString *s)
+{
+ (void)s;
+ abort();
+}
+
+void MediaListSelection_SetList(void *s, void *r, uint32_t c, uint32_t o, uint8_t e)
+{
+ (void)s, (void)r, (void)c, (void)o, (void)e;
+ abort();
+}
+
+void *ListArtworkSession_Get(void)
+{
+ abort();
+}
+
+void ArtworkSession_Stop(void *s)
+{
+ (void)s;
+ abort();
+}
+
+int ListArtworkSession_SetSource(void *s, unsigned sel)
+{
+ (void)s, (void)sel;
+ abort();
+}
+
+void *UI_GetControllerRegistry(void)
+{
+ abort();
+}
+
+void *UI_CreateScreenController(void *r, uint32_t s, uint32_t l, uint32_t t)
+{
+ (void)r, (void)s, (void)l, (void)t;
+ abort();
+}
+
+int MediaBrowser_CreateChild(void *o, void **out)
+{
+ (void)o, (void)out;
+ abort();
+}
+
+uint32_t MusicMenu_ConfigureLibraryBrowser(void *c, uint32_t i, uint32_t e, int r,
+ uint32_t g, uint32_t s, uint32_t o)
+{
+ (void)c, (void)i, (void)e, (void)r, (void)g, (void)s, (void)o;
+ abort();
+}
+
+void *Runtime_OperatorNew(uint32_t bytes)
+{
+ (void)bytes;
+ abort();
+}
+
+uint8_t BrowserRegistry[16];
+
+static void reset_groups(void)
+{
+ drop_rows(browser);
+ assert(!pins && !live_blocks);
+}
+
+static void expect_groups(const uint32_t *tokens, const char *letters, uint32_t count)
+{
+ assert(build(browser) == count);
+ assert(!pins && RV_FIELD(browser, MediaBrowser_artist_count, uint32_t) == count);
+ struct group *rows = groups_of(browser);
+ uint32_t *group_tokens = RV_FIELD(browser, MediaBrowser_artist_tokens, uint32_t *);
+ for (uint32_t i = 0; i < count; i++) {
+ assert(rows[i].token == tokens[i] && group_tokens[i] == tokens[i]);
+ uint16_t letter[2];
+ assert(!group_letter(browser, (int)i, letter));
+ assert(letter[0] == 1 && letter[1] == (uint16_t)letters[i]);
+ uint16_t name[256];
+ assert(!group_name(browser, (int)i, name));
+ assert(!memcmp(name + 1, strings[tokens[i]], name[0] * 2));
+ }
+ uint16_t none[2];
+ assert(group_name(browser, (int)count, none) == -50 &&
+ group_letter(browser, -1, none) == -50);
+ /* Built rows are kept. */
+ assert(build(browser) == count);
+ reset_groups();
+}
+
+static void check_album_runs(void)
+{
+ const struct source source = {(struct MediaList *)list, NULL};
+ struct track tracks[6];
+ const uint32_t albums[] = {1, 1, 2, 1, 3, 1};
+ for (unsigned i = 0; i < 6; i++)
+ RV_FIELD(records[i], MediaRecord_album, uint32_t) = albums[i];
+ tags[1].accepted = 0;
+ tags[2].accepted = 0;
+ pins++;
+ assert(collect_album_runs(browser, &source, 6, NULL, 0) == 3);
+ assert(collect_album_runs(browser, &source, 6, tracks, 3) == 3);
+ assert(tracks[0].order == 0 && tracks[1].order == 4 && tracks[2].order == 5);
+ tags[0].accepted = 0;
+ tags[1].accepted = 1;
+ assert(collect_album_runs(browser, &source, 6, tracks, 3) == 3);
+ assert(tracks[0].order == 1);
+ pins--;
+ assert(build(browser) == 1);
+ assert(groups_of(browser)->albums == 3);
+ reset_groups();
+ for (unsigned i = 0; i < 6; i++) {
+ RV_FIELD(records[i], MediaRecord_album, uint32_t) = i + 1;
+ tags[i].accepted = 1;
+ }
+}
+
+/* The selected group's filter and the album rows of a group. */
+static void check_group_albums(void)
+{
+ tags[0].album_artist = tags[4].album_artist = 1;
+ tags[1].album_artist = 2;
+ tags[2].album_artist = 3;
+ RV_FIELD(records[3], MediaRecord_artist, uint32_t) = 9;
+ tags[5].album_artist = 11;
+ RV_FIELD(records[0], MediaRecord_album, uint32_t) =
+ RV_FIELD(records[4], MediaRecord_album, uint32_t) = 5;
+ assert(build(browser) == 5);
+ pins++; /* Apple's filter evaluation and album build hold the caches */
+ RV_FIELD(browser, MediaBrowser_selected_artist, int) = -1;
+ assert(!outside_selected_group(browser, (struct MediaEntry *)entries[0]));
+ RV_FIELD(browser, MediaBrowser_selected_artist, int) =
+ 3; /* The Clash, after the Sort As groups */
+ assert(!outside_selected_group(browser, (struct MediaEntry *)entries[0]));
+ assert(!outside_selected_group(browser, (struct MediaEntry *)entries[4]));
+ assert(outside_selected_group(browser, (struct MediaEntry *)entries[1]));
+ RV_FIELD(browser, MediaBrowser_selected_artist, int) = 9;
+ assert(outside_selected_group(browser, (struct MediaEntry *)entries[0]));
+ /* Album rows: one per album token, counting tracks, the resolved artist
+ * as the subtitle, artwork from the first track. */
+ assert(album_group(browser, NULL, 0, 0, 0, (struct MediaEntry *)entries[0],
+ records[0], 1) == 1);
+ assert(album_group(browser, NULL, 0, 0, 1, (struct MediaEntry *)entries[4],
+ records[4], 0) == 1);
+ assert(album_group(browser, NULL, 0, 0, 2, (struct MediaEntry *)entries[2],
+ records[2], 0) == 1);
+ RV_FIELD(records[1], MediaRecord_album, uint32_t) = 0;
+ assert(album_group(browser, NULL, 0, 0, 3, (struct MediaEntry *)entries[1],
+ records[1], 0) == 1);
+ RV_FIELD(records[1], MediaRecord_album, uint32_t) = 2;
+ assert(album_group(browser, NULL, 0, 0, 0, (struct MediaEntry *)entries[0],
+ records[0], 1) == 0);
+ struct album *rows = RV_FIELD(browser, MediaBrowser_albums, struct album *);
+ assert(RV_FIELD(browser, MediaBrowser_albums_end, struct album *) - rows == 2);
+ assert(rows[0].token == 5 && rows[0].artist == 1 && rows[0].tracks == 2 &&
+ !rows[0].artwork);
+ assert(rows[1].token == 3 && rows[1].artist == 3 && rows[1].tracks == 1);
+ pins--;
+ album_artist_subtitle(browser, 0, NULL);
+ assert(assigned.units == 9 && !memcmp(assigned.text, u"The Clash", 18));
+ album_artist_subtitle(browser, 5, NULL);
+ assert(assigned.units == 9);
+ RV_FIELD(browser, MediaBrowser_albums, void *) = NULL;
+ RV_FIELD(browser, MediaBrowser_albums_end, void *) = NULL;
+ RV_FIELD(records[0], MediaRecord_album, uint32_t) = 1;
+ RV_FIELD(records[4], MediaRecord_album, uint32_t) = 5;
+ reset_groups();
+}
+
+int main(void)
+{
+ contexts[0].browser = browser;
+ RV_FIELD(owner, MediaBrowser_track_data, void *) = track_data;
+ RV_FIELD(list, MediaList_root, void *) = root;
+ RV_FIELD(root, MediaEntry_tracks, uint16_t) = 6;
+ for (unsigned i = 0; i < 6; i++) {
+ RV_FIELD(entries[i], MediaEntry_song_record, void *) = records[i];
+ RV_FIELD(records[i], 0, void *) = track_data;
+ tags[i].accepted = 1;
+ RV_FIELD(records[i], MediaRecord_artist, uint32_t) = 4;
+ RV_FIELD(records[i], MediaRecord_album, uint32_t) = i + 1;
+ }
+ check_album_runs();
+ tags[0].album_artist = tags[4].album_artist = 1;
+ tags[1].album_artist = 2;
+ tags[2].album_artist = 3;
+ RV_FIELD(records[3], MediaRecord_artist, uint32_t) = 9; /* the Artist fallback */
+ tags[5].album_artist = 11;
+ expect_groups((uint32_t[]){3, 11, 1, 2, 9}, "AATTT", 5);
+ strings[11] = u"An Aardvark";
+ expect_groups((uint32_t[]){3, 11, 1, 2, 9}, "AATTT", 5);
+ strings[11] = u"A Zebra";
+ expect_groups((uint32_t[]){11, 3, 1, 2, 9}, "AATTT", 5);
+ strings[11] = u"An Artist";
+
+ /* Sort As names come first, including a literal leading The. */
+ tags[0].sort_album_artist = tags[1].sort_album_artist = 7;
+ tags[4].sort_album_artist = 8;
+ tags[3].sort_artist = 8;
+ tags[2].sort_album_artist = 9;
+ expect_groups((uint32_t[]){9, 11, 3, 1, 2}, "AATZZ", 5);
+
+ /* Apple's own Album Artist order and jump table are consumed when complete. */
+ native_order = calloc(1, MediaOrder_entries + 6 * sizeof(void *));
+ RV_FIELD(native_order, MediaOrder_count, uint32_t) = 6;
+ RV_FIELD(native_order, MediaOrder_capacity, uint32_t) = 6;
+ const unsigned order[] = {3, 0, 2, 1, 4, 5};
+ for (unsigned i = 0; i < 6; i++)
+ ((void **)(native_order + MediaOrder_entries))[i] = entries[order[i]];
+ RV_FIELD(list, MediaList_order_index + AlbumArtist_order_mode * sizeof(void *),
+ void *) = native_order;
+ uint32_t jumps[] = {4, 0xbeef0000 | 'B', 0, 'C', 1, 'X', 2, 'Y', 3};
+ native_jump = jumps;
+ RV_FIELD(list, MediaList_jump_index + AlbumArtist_order_mode * sizeof(void *),
+ void *) = native_jump;
+ expect_groups((uint32_t[]){9, 1, 3, 2, 11}, "BCXYY", 5);
+ tags[0].accepted = 0;
+ expect_groups((uint32_t[]){9, 3, 2, 1, 11}, "BXYYY", 5);
+ tags[0].accepted = 1;
+ /* A bad or missing jump table falls back to the Sort As letters in the
+ * native order; an incomplete order falls back to the sort. */
+ jumps[2] = 1;
+ expect_groups((uint32_t[]){9, 1, 3, 2, 11}, "AZTZA", 5);
+ RV_FIELD(list, MediaList_jump_index + AlbumArtist_order_mode * sizeof(void *),
+ void *) = NULL;
+ expect_groups((uint32_t[]){9, 1, 3, 2, 11}, "AZTZA", 5);
+ RV_FIELD(native_order, MediaOrder_count, uint32_t) = 5;
+ expect_groups((uint32_t[]){9, 11, 3, 1, 2}, "AATZZ", 5);
+ RV_FIELD(list, MediaList_order_index + AlbumArtist_order_mode * sizeof(void *),
+ void *) = NULL;
+ free(native_order);
+
+ /* No eligible track, then an allocation failure, leave no rows. */
+ for (unsigned i = 0; i < 6; i++)
+ tags[i].accepted = 0;
+ expect_groups(NULL, "", 0);
+ for (unsigned i = 0; i < 6; i++)
+ tags[i].accepted = 1;
+ fail_alloc = 1;
+ assert(!build(browser) && !live_blocks && !pins);
+ fail_alloc = 0;
+ reset_groups();
+
+ check_group_albums();
+
+ /* Invalidation and the clear filter free the rows before Apple's clear. */
+ assert(build(browser) == 5 && live_blocks);
+ contexts[0].track_data = track_data;
+ browser_invalidate(track_data);
+ assert(!live_blocks && clears == 1 && !contexts[0].track_data);
+ assert(build(browser) == 5);
+ drop_rows(browser);
+ MediaBrowser_ClearArtists(browser);
+ assert(!live_blocks && clears == 2);
+ return 0;
+}
diff --git a/extensions/album-artists/tests/contracts.c b/extensions/album-artists/tests/contracts.c
new file mode 100644
index 0000000..36d801d
--- /dev/null
+++ b/extensions/album-artists/tests/contracts.c
@@ -0,0 +1,329 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include
+#include
+#include
+#include
+#include
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "../fields.c"
+
+/* The host doubles as the core: counted blocks from alloc and free. */
+static size_t live_blocks, live_bytes, peak_bytes;
+static int fail_alloc;
+
+union block {
+ max_align_t align;
+ size_t bytes;
+};
+
+static void *host_alloc(rv_extension_handle self, uint32_t bytes)
+{
+ (void)self;
+ if (fail_alloc)
+ return NULL;
+ union block *block = calloc(1, sizeof *block + bytes);
+ assert(block);
+ block->bytes = bytes;
+ live_blocks++;
+ live_bytes += bytes;
+ if (live_bytes > peak_bytes)
+ peak_bytes = live_bytes;
+ return block + 1;
+}
+
+static void host_free(rv_extension_handle self, void *memory)
+{
+ (void)self;
+ union block *block = (union block *)memory - 1;
+ assert(live_blocks);
+ live_blocks--;
+ live_bytes -= block->bytes;
+ free(block);
+}
+static const struct rv_api host_api = {.alloc = host_alloc, .free = host_free};
+const struct rv_api *api = &host_api;
+rv_extension_handle self;
+
+/* The artist cache: a string the cache holds comes back as its token with
+ * no further reference, so the table never releases one. */
+static struct {
+ const uint16_t *text;
+ uint32_t units;
+} tokens[512];
+
+static uint32_t token_count = 1;
+static uint8_t track_data[TrackData_artist_cache + 0x58];
+static void *cache = track_data + TrackData_artist_cache;
+
+int StringCache_ReadToken(void *c, uint32_t token, void *out, uint32_t *bytes,
+ uint32_t maximum)
+{
+ assert(c == cache && token && token < token_count);
+ *bytes = tokens[token].units * 2 < maximum ? tokens[token].units * 2 : maximum;
+ memcpy(out, tokens[token].text, *bytes);
+ return 0;
+}
+
+static uint32_t intern(const uint16_t *text, uint32_t units)
+{
+ for (uint32_t i = 1; i < token_count; i++)
+ if (tokens[i].units == units && !memcmp(tokens[i].text, text, units * 2))
+ return i;
+ assert(token_count < sizeof tokens / sizeof tokens[0]);
+ tokens[token_count].text = text;
+ tokens[token_count].units = units;
+ return token_count++;
+}
+
+/* The reader: a file cursor and the mhod body under it. */
+static struct {
+ uint64_t offset;
+ const uint16_t *text;
+ uint32_t units;
+ int decode_error, skip_error, position_error;
+} file;
+
+static _Alignas(16) uint8_t reader[ITunesReader_owner + 8];
+
+int ITunesDB_ImportCachedString(void *r, uint32_t encoding, uint32_t type, void *c,
+ uint32_t *token, uint32_t glyph_field, int collect)
+{
+ assert(r == reader && encoding == 1 && (type == 22 || type == 23 || type == 29) &&
+ c == cache && glyph_field == 1 && collect == 1);
+ if (file.decode_error) {
+ file.offset += 8;
+ return file.decode_error;
+ }
+ file.offset += 16 + file.units * 2;
+ *token = file.units ? intern(file.text, file.units) : 0;
+ return 0;
+}
+
+int ITunesDB_SkipImportBytes(void *r, int bytes)
+{
+ assert(r == reader);
+ if (file.skip_error)
+ return file.skip_error;
+ assert(bytes >= 0);
+ file.offset += (uint32_t)bytes;
+ return 0;
+}
+
+int BufferedFile_GetPosition(void *f, uint64_t *position)
+{
+ assert(f == RV_FIELD(reader, ITunesReader_file, void *));
+ if (file.position_error)
+ return file.position_error;
+ *position = file.offset;
+ return 0;
+}
+
+static int invalidated;
+
+void browser_invalidate(void *owner)
+{
+ assert(owner == track_data);
+ invalidated++;
+}
+
+/* Records: the owner word, the Artist token and the persistent id. */
+static uint8_t records[64][TrackData_dbid + 8];
+
+static void *record(unsigned i, uint32_t artist, uint32_t id_low, uint32_t id_high)
+{
+ uint8_t *r = records[i];
+ memset(r, 0, sizeof records[i]);
+ RV_FIELD(r, 0, void *) = track_data;
+ RV_FIELD(r, MediaRecord_artist, uint32_t) = artist;
+ RV_FIELD(r, TrackData_dbid, uint32_t) = id_low;
+ RV_FIELD(r, TrackData_dbid + 4, uint32_t) = id_high;
+ return r;
+}
+
+#define U(...) ((const uint16_t[]){__VA_ARGS__})
+static const uint16_t artist_a[] = {'A', 'r', 't', 'i', 's', 't', ' ', 'A'};
+static const uint16_t various[] = {'V', 'a', 'r', 'i', 'o', 'u', 's'};
+static const uint16_t sort_x[] = {'X'};
+
+/* One mhod of `type` with `text` for `record`, through the discard hook. */
+static int mhod(void *r, uint32_t type, const uint16_t *text, uint32_t units)
+{
+ file.text = text;
+ file.units = units;
+ uint64_t before = file.offset;
+ uint32_t body = 16 + units * 2 + 4; /* with retained padding */
+ int status = fields_import_mhod(reader, body, r, type);
+ if (!status)
+ assert(file.offset == before + body);
+ return status;
+}
+
+static void begin(void)
+{
+ RV_FIELD(reader, ITunesReader_file, void *) = &file;
+ RV_FIELD(reader, ITunesReader_owner, void *) = track_data;
+ memset(&file, 0, sizeof file);
+ fields_import_begin(reader);
+}
+
+static void expect_text(const void *r, const uint16_t *text, uint32_t units)
+{
+ uint16_t out[64];
+ uint32_t got = fields_read(r, out, 64);
+ assert(got == units && !memcmp(out, text, units * 2));
+}
+
+static void test_flush_rules(void)
+{
+ begin();
+ uint32_t a = intern(artist_a, 8); /* the record's own Artist token */
+ void *same = record(0, a, 1, 0);
+ void *differs = record(1, a, 2, 0);
+ void *sort_only = record(2, a, 3, 0);
+ void *same_sorted = record(3, a, 4, 0);
+ void *untagged = record(4, a, 5, 0);
+ void *no_artist = record(5, 0, 6, 0);
+ void *empty = record(6, a, 7, 0);
+ assert(!mhod(same, 22, artist_a, 8));
+ assert(!mhod(empty, 22, various, 0)); /* an empty tag */
+ assert(!mhod(differs, 22, various, 7));
+ assert(!mhod(sort_only, 23, sort_x, 1));
+ assert(!mhod(same_sorted, 22, artist_a, 8));
+ assert(!mhod(same_sorted, 29, sort_x, 1));
+ assert(!mhod(no_artist, 22, various, 7));
+ /* The pending record flushes when another arrives, and once at the end. */
+ assert(fields_count() == 3);
+ fields_import_end(0);
+ assert(fields_count() == 4 && fields_imported());
+ /* Same-as-Artist stores nothing. */
+ assert(!fields_token(same) && !fields_sort_token(same, 1) &&
+ !fields_sort_token(same, 0));
+ assert(fields_read(same, NULL, 0) == 0);
+ assert(fields_token(differs) && fields_token(differs) != a);
+ expect_text(differs, various, 7);
+ assert(!fields_token(sort_only) && fields_sort_token(sort_only, 0) &&
+ !fields_sort_token(sort_only, 1));
+ assert(fields_token(same_sorted) == a && fields_sort_token(same_sorted, 1));
+ uint16_t text[8];
+ assert(fields_read(same_sorted, text, 8) == 0);
+ assert(!fields_token(untagged) && !fields_token(empty));
+ assert(fields_token(no_artist) == fields_token(differs));
+ /* A record of another TrackData, or a stale one, answers nothing. */
+ uint8_t other[TrackData_dbid + 8];
+ memcpy(other, differs, sizeof other);
+ RV_FIELD(other, 0, void *) = other;
+ assert(!fields_token(other) && !fields_token(NULL));
+ /* After the import a late mhod only skips. */
+ uint32_t count = token_count;
+ assert(!mhod(untagged, 22, various, 7) && token_count == count &&
+ !fields_token(untagged));
+ /* The table is exact: 4 rows of 20 bytes, the import chunk gone. */
+ assert(live_blocks == 1 && live_bytes == 4 * 20);
+ fields_destroy(track_data);
+ assert(!live_blocks && invalidated == 1 && !fields_imported());
+ /* Destroying another TrackData's storage does nothing to the next table. */
+ begin();
+ fields_destroy(reader);
+ assert(fields_imported());
+ fields_import_end(0);
+ assert(!live_blocks);
+ fields_destroy(track_data);
+}
+
+static void test_sort_and_lookup(void)
+{
+ begin();
+ /* Ids in both halves, out of order; more than one chunk's worth comes
+ * from the repeats below. */
+ static const uint32_t ids[][2] = {
+ {5, 1}, {1, 0}, {0xffffffff, 0}, {2, 1}, {9, 9}, {4, 0},
+ {3, 0}, {7, 2}, {8, 2}, {6, 2}, {1, 1}, {0, 1},
+ {0xfffffffe, 0}, {11, 0}, {10, 0}, {12, 0}, {13, 0}, {14, 0},
+ };
+
+ enum { N = sizeof ids / sizeof ids[0] };
+
+ for (unsigned i = 0; i < N; i++)
+ assert(!mhod(record(i, 0, ids[i][0], ids[i][1]), 22, various, 7));
+ /* Chunk growth: 300 more ids fill a second chunk; the peak is the chunks
+ * plus the exact block while it is filled. */
+ for (unsigned i = 0; i < 300; i++)
+ assert(!mhod(record(40 + i % 20, 0, 100 + i, 3), 22, various, 7));
+ uint32_t total = N + 300;
+ fields_import_end(0);
+ assert(fields_count() == total && live_bytes == total * 20 && live_blocks == 1);
+ assert(peak_bytes <= total * 20 + 2 * (8 + 256 * 20) + 16);
+ uint32_t token = fields_token(records[0]);
+ for (unsigned i = 0; i < N; i++)
+ assert(fields_token(records[i]) == token);
+ assert(fields_token(record(59, 0, 399, 3)) == token &&
+ !fields_token(record(59, 0, 400, 3)));
+ assert(!fields_token(record(60, 0, 5, 0)) && !fields_token(record(61, 0, 15, 0)) &&
+ !fields_token(record(62, 0, 0, 0)));
+ fields_destroy(track_data);
+ assert(!live_blocks);
+}
+
+static void test_failures(void)
+{
+ /* A failed import drops the table. */
+ begin();
+ assert(!mhod(record(0, 0, 1, 0), 22, various, 7));
+ assert(!mhod(record(1, 0, 2, 0), 22, various, 7));
+ fields_import_end(-1);
+ assert(!live_blocks && !fields_count());
+ /* A body over INT32_MAX is refused; a short body, a cursor error, a decode
+ * past the body and a skip error all store nothing. */
+ begin();
+ void *r = record(0, 0, 1, 0);
+ assert(fields_import_mhod(reader, 0x80000000u, r, 22) == -0xd0);
+ assert(!fields_import_mhod(reader, 8, r, 22));
+ file.position_error = -3;
+ assert(!mhod(r, 22, various, 7));
+ file.position_error = 0;
+ file.text = various;
+ file.units = 7;
+ assert(fields_import_mhod(reader, 16, r, 22) == -0xd0);
+ file.skip_error = -4;
+ assert(fields_import_mhod(reader, 16 + 14 + 2, r, 22) == -4);
+ file.skip_error = 0;
+ /* A decode error keeps the row's slot empty but consumes the body. */
+ file.decode_error = -5;
+ assert(!mhod(r, 22, various, 7));
+ file.decode_error = 0;
+ fields_import_end(0);
+ assert(!fields_count() && !live_blocks);
+ fields_destroy(track_data);
+ /* Allocation failure drops the row; the table stays usable. Without
+ * memory for the final block the import's rows go. */
+ begin();
+ fail_alloc = 1;
+ assert(!mhod(record(0, 0, 1, 0), 22, various, 7));
+ assert(!mhod(record(1, 0, 2, 0), 22, various, 7)); /* flushes record 0 */
+ fail_alloc = 0;
+ assert(!mhod(record(2, 0, 3, 0), 22, various, 7));
+ fields_import_end(0);
+ assert(fields_count() == 2 && fields_token(records[1]) &&
+ fields_token(records[2]) && !fields_token(records[0]));
+ fields_destroy(track_data);
+ assert(!live_blocks);
+ begin();
+ assert(!mhod(record(0, 0, 1, 0), 22, various, 7));
+ assert(!mhod(record(1, 0, 2, 0), 22, various, 7));
+ assert(!mhod(record(2, 0, 3, 0), 22, various, 7));
+ fail_alloc = 1;
+ fields_import_end(0);
+ fail_alloc = 0;
+ assert(!fields_count() && !live_blocks && fields_imported());
+ fields_destroy(track_data);
+}
+
+int main(void)
+{
+ test_flush_rules();
+ test_sort_and_lookup();
+ test_failures();
+ assert(!live_blocks);
+ return 0;
+}
diff --git a/extensions/album-artists/tests/run.py b/extensions/album-artists/tests/run.py
new file mode 100644
index 0000000..1d85789
--- /dev/null
+++ b/extensions/album-artists/tests/run.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
+"""Run the table and browser tests with a staged SDK: python3 tests/run.py SDK."""
+
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+root = Path(__file__).resolve().parent
+sdk = Path(sys.argv[1]).resolve()
+with tempfile.TemporaryDirectory(prefix="album-artists-tests-") as name:
+ work = Path(name)
+ # Widen the pointer-bearing native layouts for the host; record offsets stay.
+ header = (sdk / "osos-2.0.5.h").read_text()
+
+ def widen(match):
+ key, value = match.groups()
+ if key.startswith(("ITunesReader_", "MediaBrowser_", "MediaList_", "MediaEntry_",
+ "MediaOrder_", "TrackData_", "LibraryBrowser_",
+ "MediaListSelection_")):
+ return f"#define {key} {int(value, 16) * 2:#x}"
+ return match[0]
+
+ (work / "osos-2.0.5.h").write_text(
+ re.sub(r"#define (\w+) (0x[0-9a-f]+)", widen, header)
+ )
+ for header in ("rv_api.h", "rv_libc.h", "rv_media.h"):
+ (work / header).write_text((sdk / header).read_text())
+ for source in ("contracts.c", "browser_contracts.c"):
+ executable = work / source[:-2]
+ subprocess.run(
+ [
+ "cc",
+ "-std=c11",
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-g",
+ "-fsanitize=address,undefined",
+ "-I",
+ str(work),
+ str(root / source),
+ "-o",
+ str(executable),
+ ],
+ check=True,
+ )
+ subprocess.run([str(executable)], check=True)
+print("Album Artists contracts passed")
diff --git a/extensions/balance/manifest.toml b/extensions/balance/manifest.toml
index 2e4aa37..635b3c2 100644
--- a/extensions/balance/manifest.toml
+++ b/extensions/balance/manifest.toml
@@ -1,10 +1,10 @@
id = "balance"
name = "Balance"
description = "Shift the sound towards the left or right ear in decibel steps, or play one ear only."
-version = "0.1.0"
+version = "0.1.1"
author = "RevolaOS"
license = "GPL-3.0-only"
-api = "1.78"
+api = "1.89"
stability = "beta"
category = "effects"
diff --git a/extensions/clicker-modes/Makefile b/extensions/clicker-modes/Makefile
new file mode 100644
index 0000000..cb973a7
--- /dev/null
+++ b/extensions/clicker-modes/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c
+include $(SDK)/rv.mk
diff --git a/extensions/clicker-modes/README.md b/extensions/clicker-modes/README.md
new file mode 100644
index 0000000..4938c9d
--- /dev/null
+++ b/extensions/clicker-modes/README.md
@@ -0,0 +1,13 @@
+# Clicker Modes
+
+Based on the RepriseOS core's [clicker modes](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/clicker.c), by Alex Ball and lgreitis.
+
+Settings > Clicker cycles Off, Speaker, Headphones and Both instead of Off and On. Apple's click engine already handles all four values; the extension adds the missing two to the row and labels them correctly. Every mode except Off shows Apple's On picture.
+
+Without the extension, a saved Speaker or Headphones still routes the click, but the stock row swaps their labels ("Speaker" for Headphones), picks the picture by the speaker alone, and Select goes to Both.
+
+| | |
+|---|---|
+| Default | on |
+| Memory | image only |
+| Settings | none; the mode is Apple's preference |
diff --git a/extensions/clicker-modes/assets/LICENSE.cupertino-icons b/extensions/clicker-modes/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/clicker-modes/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/clicker-modes/assets/settings-clicker-modes.png b/extensions/clicker-modes/assets/settings-clicker-modes.png
new file mode 100644
index 0000000..5a650aa
Binary files /dev/null and b/extensions/clicker-modes/assets/settings-clicker-modes.png differ
diff --git a/extensions/clicker-modes/assets/settings-clicker-modes.svg b/extensions/clicker-modes/assets/settings-clicker-modes.svg
new file mode 100644
index 0000000..d15817c
--- /dev/null
+++ b/extensions/clicker-modes/assets/settings-clicker-modes.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/clicker-modes/listing.toml b/extensions/clicker-modes/listing.toml
new file mode 100644
index 0000000..4b745f3
--- /dev/null
+++ b/extensions/clicker-modes/listing.toml
@@ -0,0 +1,7 @@
+details = "Open Settings > Clicker and press Select to cycle Off, Speaker, Headphones and Both."
+
+icon = "assets/settings-clicker-modes.png"
+
+[[screenshots]]
+file = "screenshots/settings.png"
+alt = "Settings > Clicker set to Headphones, with the Headphones description in the preview pane."
diff --git a/extensions/clicker-modes/main.c b/extensions/clicker-modes/main.c
new file mode 100644
index 0000000..4c67e89
--- /dev/null
+++ b/extensions/clicker-modes/main.c
@@ -0,0 +1,126 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Clicker Modes. Settings > Clicker cycles Off, Speaker, Headphones and Both
+ * instead of Off and On. Apple's click engine already routes all four values
+ * of its Clicker preference; only the Settings row offers two of them, and its
+ * labels for Speaker and Headphones are swapped.
+ *
+ * Adapted from RepriseOS payload/clicker.c (565dfe0, d48e7c4, c997a51) by
+ * Alex Ball (alexballvideos-netizen) and lgreitis. */
+
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_libc.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+
+static const struct rv_api *api;
+
+static uint32_t clicker_get(void *preferences)
+{
+ typedef uint32_t (*get_fn)(void *, uint32_t, uint32_t);
+ return RV_METHOD(preferences, Preferences_get_method,
+ get_fn)(preferences, Preference_Clicker, Service_Preferences);
+}
+
+static void clicker_set(void *preferences, uint32_t value)
+{
+ typedef void (*set_fn)(void *, uint32_t, uint32_t, uint32_t);
+ RV_METHOD(preferences, Preferences_set_method,
+ set_fn)(preferences, Preference_Clicker, Service_Preferences, value);
+}
+
+static void notify(void *model, uint32_t property)
+{
+ typedef void (*notify_fn)(void *, uint32_t, uint32_t);
+ RV_METHOD(model, Model_notify_method, notify_fn)(model, Notify_All, property);
+}
+
+static uint32_t on_action(uint32_t controller, uint32_t name, uint32_t argument,
+ const void *next)
+{
+ void *preferences = PreferencesService_Get();
+ if (!preferences || !name || strcmp((const char *)name, "ToggleSetting_Clicker"))
+ return api->hook_next(next, controller, name, argument, 0, 0, 0);
+ if (argument == ActionSupportQuery)
+ return 1;
+ uint32_t value;
+ switch (clicker_get(preferences)) {
+ case Clicker_Off:
+ value = Clicker_Speaker;
+ break;
+ case Clicker_Speaker:
+ value = Clicker_Headphones;
+ break;
+ case Clicker_Headphones:
+ value = Clicker_Both;
+ break;
+ default:
+ value = Clicker_Off;
+ break;
+ }
+ clicker_set(preferences, value);
+ void *model = *(void **)(controller + ScreenController_settings_model);
+ notify(model, SettingsProperty_ClickerValue);
+ notify(model, SettingsProperty_ClickerDescription);
+ notify(model, SettingsProperty_ClickerImage);
+ return 1;
+}
+
+static uint32_t on_property(uint32_t model, uint32_t type, uint32_t property,
+ uint32_t out, const void *next)
+{
+ int image = property == SettingsProperty_ClickerImage && type == Resource_BMap;
+ int row = property == SettingsProperty_ClickerValue;
+ void *preferences = PreferencesService_Get();
+ if (!preferences ||
+ (!image && !((row || property == SettingsProperty_ClickerDescription) &&
+ type == Property_String)))
+ return api->hook_next(next, model, type, property, out, 0, 0);
+ uint32_t value = clicker_get(preferences);
+ void *service = UI_GetResourceService();
+ if (image) {
+ /* Apple's picks the picture by the speaker bit alone. */
+ *(uintptr_t *)out = (uintptr_t)ResourceService_GetBitmap(
+ service, value == Clicker_Off ? RES_Settings_ClickerOff_Image
+ : RES_Settings_ClickerOn_Image);
+ return 1;
+ }
+ uint32_t id;
+ switch (value) {
+ case Clicker_Off:
+ id = row ? RES_Settings_Off_String : RES_Settings_ClickerOff_Description;
+ break;
+ case Clicker_Speaker:
+ id =
+ row ? RES_Settings_Speaker_String : RES_Settings_ClickerSpeaker_Description;
+ break;
+ case Clicker_Headphones:
+ id = row ? RES_Settings_Headphones_String
+ : RES_Settings_ClickerHeadphones_Description;
+ break;
+ default:
+ id = row ? RES_Settings_Both_String : RES_Settings_ClickerBoth_Description;
+ break;
+ }
+ *(uintptr_t *)out = (uintptr_t)ResourceService_GetString(service, id);
+ return 1;
+}
+
+static const struct rv_hook hooks[] = {
+ RV_HOOK_FILTER(RV_SITE_Settings_Action_slot, on_action),
+ RV_HOOK_FILTER(RV_SITE_Settings_Property_slot, on_property),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ (void)handle;
+ api = core;
+ return &extension;
+}
diff --git a/extensions/clicker-modes/manifest.toml b/extensions/clicker-modes/manifest.toml
new file mode 100644
index 0000000..42eac75
--- /dev/null
+++ b/extensions/clicker-modes/manifest.toml
@@ -0,0 +1,13 @@
+id = "clicker-modes"
+name = "Clicker Modes"
+description = "Choose where the click wheel sound plays: the iPod's speaker, headphones, both or off."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "system"
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/clicker-modes/screenshots/settings.png b/extensions/clicker-modes/screenshots/settings.png
new file mode 100644
index 0000000..069c011
Binary files /dev/null and b/extensions/clicker-modes/screenshots/settings.png differ
diff --git a/extensions/crossfeed/manifest.toml b/extensions/crossfeed/manifest.toml
index 1109dc6..1449cb3 100644
--- a/extensions/crossfeed/manifest.toml
+++ b/extensions/crossfeed/manifest.toml
@@ -1,14 +1,17 @@
id = "crossfeed"
name = "Crossfeed"
description = "Blends a little of each channel into the other so hard-panned stereo is easier on headphones. A simple mode or a custom filter."
-version = "0.1.0"
+version = "0.1.1"
author = "RevolaOS"
note = "Ported from Rockbox"
license = "GPL-3.0-only"
-api = "1.78"
+api = "1.89"
stability = "beta"
category = "effects"
-requires = ["dsp"]
+
+[libraries]
+required = ["dsp"]
+optional = ["reprise"]
[[module]]
name = "main"
diff --git a/extensions/dsp/manifest.toml b/extensions/dsp/manifest.toml
index c1657c3..14b074b 100644
--- a/extensions/dsp/manifest.toml
+++ b/extensions/dsp/manifest.toml
@@ -1,11 +1,11 @@
id = "dsp"
name = "DSP"
description = "Signal processing the audio effects share: the look-ahead limiter, filter designs, the biquad cascade and the maths behind them."
-version = "0.1.0"
+version = "0.1.1"
author = "RevolaOS"
note = "Partly adapted from RepriseOS"
license = "GPL-3.0-only"
-api = "1.74"
+api = "1.89"
stability = "beta"
category = "library"
exports = [
diff --git a/extensions/dsp/rv_dsp.h b/extensions/dsp/rv_dsp.h
index 5ae8a22..d63b241 100644
--- a/extensions/dsp/rv_dsp.h
+++ b/extensions/dsp/rv_dsp.h
@@ -1,7 +1,7 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* What the dsp library exports, and the state its limiter and fade run on.
- * An effect lists `requires = ["dsp"]` in its manifest; rv.mk finds the
+ * An effect lists dsp under `[libraries] required`; rv.mk finds the
* library and the core fills in the addresses when it loads. No
* RV_MODULE_CALL here: a call into a library is a long call. */
diff --git a/extensions/equalizer/Makefile b/extensions/equalizer/Makefile
new file mode 100644
index 0000000..5370c73
--- /dev/null
+++ b/extensions/equalizer/Makefile
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c engine.c presets.c
+editor_SOURCES := editor.c
+include $(SDK)/rv.mk
diff --git a/extensions/equalizer/README.md b/extensions/equalizer/README.md
new file mode 100644
index 0000000..0ce7f30
--- /dev/null
+++ b/extensions/equalizer/README.md
@@ -0,0 +1,25 @@
+# Equalizer
+
+Partly adapted from the RepriseOS core's [Custom EQ](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/custom_eq.c), [EQ audio path](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/eq_audio.c), [EQ canvas](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/eq_canvas.c) and [filter design](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/eq_coefficients.c), by lgreitis and paviro.
+
+Apple's EQ rounds each of its three filter stages to 16 bits, so boosting presets distort loud passages. Equalizer runs the same presets through its own filter chain with 42 dB of headroom between stages, and lowers each preset by its peak gain. A look-ahead limiter at the end catches the peaks the precut misses and delays the output by about 0.7 ms. Off and Flat pass audio through untouched.
+
+The EQ list gains a Custom preset after Apple's. While Custom is selected, Settings shows an Edit EQ row to shape it. The wheel picks a band, Select steps into its parameters and then edits one, Menu goes back. Holding Select resets the highlighted band or parameter. Changes apply immediately. Moving the Hold switch shows the response curve, precut included. Like Flat, Custom is not replaced by a track's own EQ setting. Each of the five bands has:
+
+| Parameter | Range | Default |
+|---|---|---|
+| Type | off, peaking, low shelf, high shelf | low shelf, peaking, high shelf, off, off |
+| Frequency | 20 Hz to 20 kHz | 60 Hz, 1 kHz, 8 kHz, 250 Hz, 4 kHz |
+| Q | 0.3 to 4.0 | 0.7 |
+| Gain | -12 to +12 dB | 0 dB |
+| Precut, for the whole preset | automatic (the chain's peak gain) or fixed down to -10 dB | automatic |
+
+Enabled during playback, it takes over at the next track or preset change. Disabling it with Custom selected sets the EQ to Off.
+
+On first start the extension imports the Custom EQ values the earlier core kept in its settings store (the CEQ record) and shows the Edit EQ row when Custom was the selected preset. Custom EQ values that exist only in the pre-store CFWEQ file start from the defaults.
+
+| | |
+|---|---|
+| Default | on |
+| Memory | image only |
+| Settings | the Custom preset and whether the Edit EQ row shows |
diff --git a/extensions/equalizer/assets/settings-eq.png b/extensions/equalizer/assets/settings-eq.png
new file mode 100644
index 0000000..20644d3
Binary files /dev/null and b/extensions/equalizer/assets/settings-eq.png differ
diff --git a/extensions/equalizer/assets/settings-eq.svg b/extensions/equalizer/assets/settings-eq.svg
new file mode 100644
index 0000000..3508b93
--- /dev/null
+++ b/extensions/equalizer/assets/settings-eq.svg
@@ -0,0 +1,11 @@
+
diff --git a/extensions/equalizer/editor.c b/extensions/equalizer/editor.c
new file mode 100644
index 0000000..3af747f
--- /dev/null
+++ b/extensions/equalizer/editor.c
@@ -0,0 +1,322 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The Custom EQ editor: five gain bars over a row of the selected band's
+ * parameters. The wheel picks a band; Select moves into the parameters and
+ * then into editing one, holding Select puts what is highlighted back to its
+ * default, Menu steps back out. Every change plays at once through the link
+ * main passed as the screen's argument. The hold switch shows the response
+ * curve of what plays.
+ *
+ * Adapted from RepriseOS payload/eq_canvas.c (d640115, 93f6a45) by lgreitis. */
+
+#include "rv_canvas.h"
+#include "rv_libc.h"
+#include "rv_ui.h"
+#include "shared.h"
+
+static const struct rv_api *api;
+static rv_extension_handle self;
+
+enum { DEPTH_BAND, DEPTH_PARAMETER, DEPTH_EDIT, DEPTHS };
+
+/* Wheel order follows reading order: Type | Precut, then Gain | Frequency | Q. */
+enum { PARAM_TYPE, PARAM_PRECUT, PARAM_GAIN, PARAM_FREQUENCY, PARAM_Q, PARAM_COUNT };
+
+static const uint8_t parameters[PARAM_COUNT] = {EQ_TYPE, EQ_PRECUT, EQ_GAIN,
+ EQ_FREQUENCY, EQ_Q};
+static const char *const titles[PARAM_COUNT] = {"Type", "Precut", "Gain", "Frequency",
+ "Q"};
+static const char *const types[] = {"Off", "Peaking", "Low shelf", "High shelf"};
+
+enum {
+ BAND_LEFT = 42,
+ BAND_WIDTH = 54,
+ BAND_TOP = 18,
+ BAND_BOTTOM = 108,
+ BAND_ZERO = (BAND_TOP + BAND_BOTTOM) / 2,
+ INLINE_TOP = 141, /* Type | Precut, title left and value right */
+ INLINE_HEIGHT = 27,
+ INLINE_COUNT = PARAM_GAIN,
+ CELL_TOP = INLINE_TOP + INLINE_HEIGHT +
+ 1, /* the cells run to the bottom of the canvas */
+ RESPONSE_POINTS = 261,
+ RESPONSE_TOP = 36,
+ RESPONSE_BOTTOM = 180,
+ RESPONSE_ZERO = (RESPONSE_TOP + RESPONSE_BOTTOM) / 2,
+ TICK_TOP = 192,
+ TICK_HEIGHT = 22,
+};
+
+static struct {
+ struct rv_editor input;
+ int band, parameter, response, dirty;
+ int16_t curve[RESPONSE_POINTS];
+ /* The response from +extent at the top to -extent at the bottom, tenths
+ * of a decibel, doubled until the curve fits. */
+ struct rv_plot plot;
+ unsigned int precut;
+} editor;
+
+static const struct eq_link *link(const struct rv_context *ctx)
+{
+ return ctx->arg;
+}
+
+static unsigned int slot(int band, int parameter)
+{
+ return eq_slot((unsigned int)band, parameters[parameter]);
+}
+
+static unsigned int choice(const struct rv_context *ctx, int band, int parameter)
+{
+ return link(ctx)->values[slot(band, parameter)];
+}
+
+static void save(const struct rv_context *ctx)
+{
+ if (editor.dirty)
+ link(ctx)->save();
+ editor.dirty = 0;
+}
+
+enum { LABEL_BYTES = 12 };
+
+static const char *label(int parameter, unsigned int choice, char out[LABEL_BYTES])
+{
+ switch (parameter) {
+ case PARAM_TYPE:
+ return types[choice];
+ case PARAM_PRECUT:
+ if (choice == EQ_PRECUT_AUTO)
+ return "Auto";
+ rv_format_tenths(out, LABEL_BYTES, eq_precut_tenths(choice), 0, " dB");
+ return out;
+ case PARAM_GAIN:
+ rv_format_tenths(out, LABEL_BYTES, eq_gain_tenths(choice), 1, " dB");
+ return out;
+ case PARAM_FREQUENCY:
+ rv_format_hz(out, LABEL_BYTES, eq_frequencies[choice]);
+ return out;
+ default:
+ rv_format_tenths(out, LABEL_BYTES, eq_q_tenths(choice), 0, "");
+ return out;
+ }
+}
+
+static void compute_response(const struct rv_context *ctx)
+{
+ int extent = 60;
+ editor.precut = link(ctx)->response(editor.curve, RESPONSE_POINTS);
+ for (unsigned int i = 0; i < RESPONSE_POINTS; i++)
+ while (editor.curve[i] < -extent || editor.curve[i] > extent)
+ extent *= 2;
+ editor.plot = (struct rv_plot){.left = 44,
+ .top = RESPONSE_TOP,
+ .bottom = RESPONSE_BOTTOM,
+ .points = RESPONSE_POINTS,
+ .top_value = (int16_t)extent,
+ .bottom_value = (int16_t)-extent};
+}
+
+static void draw_response(const struct rv_context *ctx, const struct rv_canvas *c)
+{
+ static const char *const tick_labels[] = {"20", "200", "2k", "20k Hz"};
+ char value[LABEL_BYTES], high[8], low[8];
+ const char *scale[] = {high, "0", low};
+ unsigned int precut = choice(ctx, 0, PARAM_PRECUT);
+ const char *title = "Precut";
+ rv_canvas_header(c, "EQ response", NULL, 0);
+ /* With Auto, the attenuation the engine found. */
+ if (precut == EQ_PRECUT_AUTO) {
+ title = "Auto precut";
+ precut = editor.precut + 1;
+ }
+ label(PARAM_PRECUT, precut, value);
+ int right = c->width - 8;
+ int value_width = c->gfx->measure(RV_FONT_TEXT, value);
+ int title_width = c->gfx->measure(RV_FONT_TEXT, title);
+ rv_canvas_text(c, right - value_width - 6 - title_width, 3, title_width, 24, title,
+ 0, RV_ALIGN_LEFT, RV_CANVAS_MUTED);
+ rv_canvas_text(c, right - value_width, 3, value_width, 24, value, 0, RV_ALIGN_RIGHT,
+ RV_CANVAS_TEXT);
+ rv_format(high, sizeof high, "+%u", (unsigned int)editor.plot.top_value / 10);
+ rv_format(low, sizeof low, "-%u", (unsigned int)editor.plot.top_value / 10);
+ rv_plot_ticks(c, &editor.plot, tick_labels, 4, TICK_TOP, TICK_HEIGHT);
+ rv_plot_grid(c, &editor.plot, scale, 3);
+ rv_canvas_rect(c, editor.plot.left, RESPONSE_ZERO, RESPONSE_POINTS, 1,
+ RV_CANVAS_ZERO);
+ rv_plot_curve(c, &editor.plot, editor.curve, 1, RV_CANVAS_ACCENT);
+}
+
+static void draw_bands(const struct rv_context *ctx, const struct rv_canvas *c)
+{
+ rv_canvas_rect(c, BAND_LEFT, BAND_TOP, BAND_WIDTH * EQ_BANDS, 1, RV_CANVAS_GRID);
+ rv_canvas_rect(c, BAND_LEFT, BAND_BOTTOM, BAND_WIDTH * EQ_BANDS, 1, RV_CANVAS_GRID);
+ rv_canvas_rect(c, BAND_LEFT + 2 + editor.band * BAND_WIDTH, 4, BAND_WIDTH - 4,
+ INLINE_TOP - 7, RV_CANVAS_SELECTION);
+ rv_canvas_rect(c, BAND_LEFT, BAND_ZERO, BAND_WIDTH * EQ_BANDS, 1, RV_CANVAS_ZERO);
+ rv_canvas_text(c, 2, BAND_TOP - 9, 34, 18, "+12", 0, RV_ALIGN_CENTER,
+ RV_CANVAS_MUTED);
+ rv_canvas_text(c, 2, BAND_ZERO - 9, 34, 18, "0", 0, RV_ALIGN_CENTER,
+ RV_CANVAS_MUTED);
+ rv_canvas_text(c, 2, BAND_BOTTOM - 9, 34, 18, "-12", 0, RV_ALIGN_CENTER,
+ RV_CANVAS_MUTED);
+ for (int band = 0; band < EQ_BANDS; band++) {
+ char frequency[LABEL_BYTES];
+ int x = BAND_LEFT + BAND_WIDTH / 2 + band * BAND_WIDTH;
+ int y = BAND_ZERO - eq_gain_tenths(choice(ctx, band, PARAM_GAIN)) *
+ (BAND_BOTTOM - BAND_ZERO) / 120;
+ int selected = band == editor.band;
+ int off = choice(ctx, band, PARAM_TYPE) == EQ_OFF;
+ uint8_t color = off ? RV_CANVAS_BORDER
+ : selected ? RV_CANVAS_ACCENT
+ : RV_CANVAS_INACTIVE;
+ rv_canvas_rect(c, x - 8, BAND_TOP, 16, BAND_BOTTOM - BAND_TOP, RV_CANVAS_TRACK);
+ rv_canvas_rect(c, x - 16, BAND_ZERO, 32, 1, RV_CANVAS_ZERO);
+ int top = y < BAND_ZERO ? y : BAND_ZERO;
+ int height = y < BAND_ZERO ? BAND_ZERO - y : y - BAND_ZERO;
+ if (height)
+ rv_canvas_rect(c, x - 8, top, 16, height, color);
+ rv_canvas_rect(c, x - 12, y - 3, 24, 6, color);
+ rv_canvas_text(
+ c, x - 25, INLINE_TOP - 25, 50, 22,
+ off ? "Off"
+ : label(PARAM_FREQUENCY, choice(ctx, band, PARAM_FREQUENCY), frequency),
+ 0, RV_ALIGN_CENTER, selected ? RV_CANVAS_ACCENT : RV_CANVAS_MUTED);
+ }
+}
+
+static void draw_parameters(const struct rv_context *ctx, const struct rv_canvas *c)
+{
+ char text[PARAM_COUNT][LABEL_BYTES];
+ const char *values[PARAM_COUNT];
+ uint8_t states[PARAM_COUNT];
+ for (int parameter = 0; parameter < PARAM_COUNT; parameter++) {
+ int active = editor.input.depth != DEPTH_BAND && parameter == editor.parameter;
+ values[parameter] =
+ label(parameter, choice(ctx, editor.band, parameter), text[parameter]);
+ states[parameter] = !active ? RV_CELL_IDLE
+ : editor.input.depth == DEPTH_EDIT ? RV_CELL_EDITING
+ : RV_CELL_SELECTED;
+ }
+ rv_canvas_fields(c, INLINE_TOP, INLINE_HEIGHT, titles, values, states,
+ INLINE_COUNT);
+ rv_canvas_cells(c, CELL_TOP, c->height - CELL_TOP, titles + INLINE_COUNT,
+ values + INLINE_COUNT, states + INLINE_COUNT,
+ PARAM_COUNT - INLINE_COUNT);
+}
+
+static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width,
+ int height)
+{
+ struct rv_canvas c;
+ rv_canvas_begin(&c, g, width, height);
+ if (editor.response) {
+ draw_response(ctx, &c);
+ return;
+ }
+ draw_bands(ctx, &c);
+ draw_parameters(ctx, &c);
+}
+
+static void wheel(const struct rv_context *ctx, int delta)
+{
+ if (editor.input.depth == DEPTH_BAND) {
+ editor.band = rv_clamp(editor.band + delta, 0, EQ_BANDS - 1);
+ } else if (editor.input.depth == DEPTH_PARAMETER) {
+ editor.parameter = rv_clamp(editor.parameter + delta, 0, PARAM_COUNT - 1);
+ } else {
+ unsigned int at = slot(editor.band, editor.parameter);
+ int previous = link(ctx)->values[at];
+ int value =
+ rv_clamp(previous + delta, 0, eq_choices[parameters[editor.parameter]] - 1);
+ if (value != previous) {
+ link(ctx)->change(at, (unsigned int)value);
+ editor.dirty = 1;
+ }
+ }
+}
+
+/* A held Select puts what is highlighted back to its default: a band with its
+ * four parameters, or at the parameter levels the one parameter, Precut
+ * included. One publish. */
+static void reset(const struct rv_context *ctx)
+{
+ uint8_t trial[EQ_VALUES];
+ unsigned int first, count;
+ if (editor.input.depth == DEPTH_BAND) {
+ first = eq_slot((unsigned int)editor.band, EQ_TYPE);
+ count = EQ_PARAMETERS - 1;
+ } else {
+ first = slot(editor.band, editor.parameter);
+ count = 1;
+ }
+ if (!memcmp(link(ctx)->values + first, link(ctx)->defaults + first, count))
+ return;
+ memcpy(trial, link(ctx)->values, EQ_VALUES);
+ memcpy(trial + first, link(ctx)->defaults + first, count);
+ link(ctx)->set(trial);
+ editor.dirty = 1;
+}
+
+static int input(const struct rv_context *ctx, const struct rv_input *input)
+{
+ if (input->kind == RV_INPUT_HOLD) {
+ editor.response = input->delta;
+ if (editor.response) {
+ save(ctx);
+ compute_response(ctx);
+ }
+ } else if (editor.response) {
+ return 1;
+ } else {
+ switch (rv_editor_input(&editor.input, input)) {
+ case RV_EDITOR_IGNORED:
+ return 0;
+ case RV_EDITOR_CONSUMED:
+ return 1;
+ case RV_EDITOR_WHEEL:
+ wheel(ctx, input->delta);
+ break;
+ case RV_EDITOR_RESET:
+ reset(ctx);
+ break;
+ default:
+ save(ctx);
+ break;
+ }
+ }
+ api->ui_invalidate(self);
+ return 1;
+}
+
+static void opened(const struct rv_context *ctx)
+{
+ (void)ctx;
+ memset(&editor, 0, sizeof editor);
+ editor.input.depths = DEPTHS;
+}
+
+static void closed(const struct rv_context *ctx)
+{
+ save(ctx);
+}
+
+static const struct rv_screen screens[] = {
+ RV_SCREEN_CANVAS("editor", "Custom EQ", draw, input,
+ .transition = RV_TRANSITION_FROM_PANE, .opened = opened,
+ .closed = closed),
+};
+
+static const struct rv_descriptor module = {
+ .size = sizeof module,
+ RV_SCREENS(screens),
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ api = core;
+ self = handle;
+ return &module;
+}
diff --git a/extensions/equalizer/engine.c b/extensions/equalizer/engine.c
new file mode 100644
index 0000000..839f961
--- /dev/null
+++ b/extensions/equalizer/engine.c
@@ -0,0 +1,269 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* What the EQ plays. Apple's loader still fills its three stages for its own
+ * presets; the engine copies them, cuts the first by the cascade's peak so a
+ * boost has room, and runs them through the dsp library's cascade. The Custom
+ * preset is five stages Apple's loader never sees. Apple's records keep what
+ * Apple wrote.
+ *
+ * Load and reset arrive on the task that changed the setting or prepared a
+ * track, process on the PCM output pump task. Only the pump task touches the
+ * stages that play. The others leave it a set of coefficients with interrupts
+ * masked, and it takes the set over once it sees the generation move.
+ *
+ * Adapted from RepriseOS payload/eq_audio.c (93f6a45) by lgreitis. */
+
+#include "engine.h"
+#include "osos-2.0.5.h"
+#include "rv_dsp.h"
+#include "rv_libc.h"
+
+/* The saved band types are the library's filter types. */
+_Static_assert((int)EQ_OFF == RV_DSP_FLAT && (int)EQ_PEAKING == RV_DSP_PEAKING &&
+ (int)EQ_LOW_SHELF == RV_DSP_LOW_SHELF &&
+ (int)EQ_HIGH_SHELF == RV_DSP_HIGH_SHELF,
+ "band types");
+
+enum {
+ NATIVE_STAGES = 3,
+ PRECUT_LIMIT = 100,
+ UNITY = 1 << 24,
+};
+
+static const struct rv_api *api;
+
+/* The Custom preset at 44.1 and 48 kHz, each stage b0, b1, b2, a1, a2, and the
+ * precut inside its first stage. */
+static int32_t custom[2][EQ_BANDS][5];
+static uint8_t custom_precut[2];
+
+/* The set left for the pump task, and what the last load found. */
+struct eq_set {
+ int32_t coefficients[EQ_BANDS][5];
+ uint8_t count;
+ uint8_t fade; /* blend from what plays instead of switching */
+ uint8_t dry; /* the pump task may not have run since the last set: start from dry */
+};
+static struct eq_set next;
+static struct rv_handoff handoff;
+static struct ThreeBandEQ *volatile owner; /* NULL until the first load */
+static uint8_t plays_custom, custom_bank;
+static volatile uint8_t rest_pending;
+/* Apple runs the EQ only while its record is enabled; until the next set that
+ * plays, what the pump task holds is stale. 1 before the first load. */
+static uint8_t stopped = 1;
+
+/* The precut of the last Apple preset loaded: tenths of a decibel, the preset
+ * from bit 8 and the rate's bank in bit 16. Preset 0 has no stages, so 0 is
+ * no entry. */
+static uint32_t native_precut;
+
+/* Pump task only. The limiter runs while a stage does; a flat set passes the
+ * audio through, and a change between the two fades its delay in or out. */
+static struct rv_dsp_stage playing[EQ_BANDS], fading[EQ_BANDS];
+static struct rv_fade fade;
+static struct rv_limiter limiter;
+
+void eq_engine_start(const struct rv_api *core)
+{
+ api = core;
+}
+
+static int supported(unsigned int rate)
+{
+ return rate == 44100 || rate == 48000;
+}
+
+static unsigned int precut_for(const int32_t (*set)[5], unsigned int count,
+ unsigned int rate)
+{
+ int peak = rv_dsp_peak(set, count, rate);
+ return peak <= 0 ? 0 : peak > PRECUT_LIMIT ? PRECUT_LIMIT : (unsigned int)peak;
+}
+
+/* Interrupts masked. */
+static void leave(const int32_t (*set)[5], unsigned int count, unsigned int blend)
+{
+ for (unsigned int i = 0; i < count; i++)
+ for (unsigned int c = 0; c < 5; c++)
+ next.coefficients[i][c] = set[i][c];
+ next.count = (uint8_t)count;
+ next.fade = (uint8_t)blend;
+ next.dry = stopped;
+ handoff.generation++;
+}
+
+int eq_publish(const uint8_t values[EQ_VALUES])
+{
+ int32_t banks[2][EQ_BANDS][5];
+ unsigned int precut[2];
+ for (unsigned int bank = 0; bank < 2; bank++) {
+ unsigned int rate = bank ? 48000 : 44100;
+ int automatic = values[EQ_PRECUT] == EQ_PRECUT_AUTO;
+ precut[bank] =
+ automatic ? 0 : (unsigned int)-eq_precut_tenths(values[EQ_PRECUT]);
+ for (unsigned int band = 0; band < EQ_BANDS; band++) {
+ const uint8_t *v = values + band * (EQ_PARAMETERS - 1);
+ if (!rv_dsp_biquad(
+ banks[bank][band], v[EQ_TYPE], eq_frequencies[v[EQ_FREQUENCY]],
+ (unsigned int)eq_q_tenths(v[EQ_Q]), eq_gain_tenths(v[EQ_GAIN]),
+ band ? 0 : precut[bank], rate))
+ return 0;
+ }
+ if (automatic) {
+ precut[bank] = precut_for(banks[bank], EQ_BANDS, rate);
+ rv_dsp_attenuate(banks[bank][0], precut[bank]);
+ }
+ }
+ uint32_t state = api->irq_save();
+ memcpy(custom, banks, sizeof custom);
+ custom_precut[0] = (uint8_t)precut[0];
+ custom_precut[1] = (uint8_t)precut[1];
+ if (plays_custom)
+ leave(custom[custom_bank], EQ_BANDS, 1);
+ api->irq_restore(state);
+ return 1;
+}
+
+unsigned int eq_custom_response(int16_t *tenths, unsigned int points)
+{
+ unsigned int bank = custom_bank;
+ rv_dsp_response(custom[bank], EQ_BANDS, bank ? 48000 : 44100, tenths, points);
+ return custom_precut[bank];
+}
+
+/* Works out what `eq` plays after a load and leaves it for the pump task. */
+static void prepare(struct ThreeBandEQ *eq)
+{
+ int32_t set[NATIVE_STAGES][5];
+ unsigned int count = 0, rate = RV_FIELD(eq, ThreeBandEQ_sample_rate, uint32_t);
+ unsigned int preset = RV_FIELD(eq, ThreeBandEQ_preset, uint32_t),
+ bank = rate == 48000;
+ if (preset == EQ_CUSTOM_PRESET) {
+ RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t) = (uint8_t)supported(rate);
+ count = supported(rate) ? EQ_BANDS : 0;
+ } else if (RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t)) {
+ for (unsigned int i = 0; i < NATIVE_STAGES; i++) {
+ uint8_t *stage =
+ &RV_FIELD(eq, ThreeBandEQ_stages + i * EQStage_bytes, uint8_t);
+ if (RV_FIELD(stage, EQStage_bypass, uint8_t))
+ continue;
+ set[count][0] = RV_FIELD(stage, EQStage_b0, int32_t);
+ set[count][1] = RV_FIELD(stage, EQStage_b1, int32_t);
+ set[count][2] = RV_FIELD(stage, EQStage_b2, int32_t);
+ set[count][3] = RV_FIELD(stage, EQStage_a1, int32_t);
+ set[count][4] = RV_FIELD(stage, EQStage_a2, int32_t);
+ count++;
+ }
+ uint32_t key = preset << 8 | bank << 16, cached = native_precut;
+ if (count && (cached & ~0xffu) != key) {
+ cached = key | precut_for(set, count, rate);
+ native_precut = cached;
+ }
+ if (count)
+ rv_dsp_attenuate(set[0], cached & 0xff);
+ }
+ uint32_t state = api->irq_save();
+ owner = eq;
+ plays_custom = preset == EQ_CUSTOM_PRESET && count;
+ custom_bank = (uint8_t)bank;
+ leave(plays_custom ? custom[bank] : set, count, 0);
+ stopped = !RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t);
+ api->irq_restore(state);
+}
+
+void eq_load(struct ThreeBandEQ *eq, const void *next_hook)
+{
+ (void)next_hook;
+ /* Apple's loader has no row for the Custom preset. */
+ if (RV_FIELD(eq, ThreeBandEQ_preset, uint32_t) != EQ_CUSTOM_PRESET)
+ EQ_LoadPresetCoefficients(eq);
+ prepare(eq);
+}
+
+void eq_reset(struct ThreeBandEQ *eq, const void *next_hook)
+{
+ (void)next_hook;
+ EQ_ResetAllBiquadStates(eq);
+ rest_pending = 1;
+}
+
+static int running(const struct rv_dsp_stage *stages)
+{
+ for (unsigned int i = 0; i < EQ_BANDS; i++)
+ if (!stages[i].bypass)
+ return 1;
+ return 0;
+}
+
+/* Takes over the set a load or publish left. A set left meanwhile moves the
+ * generation again, and the next call takes that one. Between a flat set and
+ * one that runs the limiter's delay fades in or out, whether the set asks for
+ * a fade or not; after the EQ was off the old state is treated as flat. */
+static void take(void)
+{
+ struct eq_set set;
+ memcpy(fading, playing, sizeof fading);
+ rv_handoff_take(&handoff, &set, &next, sizeof set);
+ if (set.dry)
+ for (unsigned int i = 0; i < EQ_BANDS; i++)
+ fading[i].bypass = 1;
+ for (unsigned int i = 0; i < EQ_BANDS; i++) {
+ const int32_t *c = set.coefficients[i];
+ rv_dsp_stage_set(&playing[i], c);
+ playing[i].bypass =
+ i >= set.count || (c[0] == UNITY && !(c[1] | c[2] | c[3] | c[4]));
+ }
+ rv_dsp_cascade_rest(playing, EQ_BANDS);
+ int was = running(fading), now = running(playing);
+ if (now && !was)
+ rv_limiter_rest(&limiter);
+ if (was != now)
+ rv_fade_start(&fade, now ? RV_LIMITER_FRAMES : 0);
+ else if (set.fade)
+ rv_fade_start(&fade, 0);
+ else
+ fade.remaining = 0;
+}
+
+static int cascade(void *stages, const int16_t *in, int32_t *out, uint32_t frames)
+{
+ if (!running(stages))
+ return 0;
+ rv_dsp_cascade_run(stages, EQ_BANDS, in, out, frames);
+ return 1;
+}
+
+void eq_process(struct ThreeBandEQ *eq, int16_t *samples, uint32_t frames,
+ int16_t **output, const void *next_hook, uint32_t *output_frames)
+{
+ (void)next_hook;
+ /* Bound while a preset plays: Apple's stages as they are until the next load. */
+ if (owner != eq) {
+ EQ_ProcessThreeBiquadsInPlace(eq, samples, frames, output, output_frames);
+ return;
+ }
+ *output = samples;
+ *output_frames = frames;
+ if (rv_handoff_pending(&handoff) && !rv_fade_switching(&fade))
+ take();
+ if (rest_pending) {
+ rest_pending = 0;
+ rv_dsp_cascade_rest(playing, EQ_BANDS);
+ /* A load resets right after it, so a fade of the delay stays. */
+ if (running(playing) == running(fading))
+ fade.remaining = 0;
+ }
+ rv_fade_run_limited(&fade, &limiter, cascade, playing, fading, samples, frames);
+}
+
+void eq_engine_stop(void)
+{
+ struct ThreeBandEQ *eq = owner;
+ uint32_t state = api->irq_save();
+ if (eq && RV_FIELD(eq, ThreeBandEQ_preset, uint32_t) == EQ_CUSTOM_PRESET) {
+ RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t) = 0;
+ RV_FIELD(eq, ThreeBandEQ_preset, uint32_t) = 0;
+ }
+ api->irq_restore(state);
+}
diff --git a/extensions/equalizer/engine.h b/extensions/equalizer/engine.h
new file mode 100644
index 0000000..bfd2144
--- /dev/null
+++ b/extensions/equalizer/engine.h
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The audio path of the main module. */
+
+#ifndef EQUALIZER_ENGINE_H
+#define EQUALIZER_ENGINE_H
+#include "shared.h"
+
+struct rv_api;
+struct ThreeBandEQ;
+
+/* The Custom preset is the DSP preset and the EQ menu row after Apple's last. */
+#define EQ_CUSTOM_PRESET EQ_PresetCount
+
+void eq_engine_start(const struct rv_api *core);
+/* Before the hooks are unbound: turns the EQ off if it plays the Custom preset,
+ * which Apple's own code cannot. */
+void eq_engine_stop(void);
+
+/* Makes `values` the Custom preset, crossfading when it plays. 0, and nothing
+ * changes, when a band has no stable filter. UI task. */
+int eq_publish(const uint8_t values[EQ_VALUES]);
+/* struct eq_link's response, of the Custom preset. UI task. */
+unsigned int eq_custom_response(int16_t *tenths, unsigned int points);
+
+/* Hook handlers: load and reset on the task that changed the setting or
+ * prepared a track, process on the PCM output pump task. */
+void eq_load(struct ThreeBandEQ *eq, const void *next_hook);
+void eq_reset(struct ThreeBandEQ *eq, const void *next_hook);
+void eq_process(struct ThreeBandEQ *eq, int16_t *samples, uint32_t frames,
+ int16_t **output, const void *next_hook, uint32_t *output_frames);
+
+#endif
diff --git a/extensions/equalizer/listing.toml b/extensions/equalizer/listing.toml
new file mode 100644
index 0000000..c94fc75
--- /dev/null
+++ b/extensions/equalizer/listing.toml
@@ -0,0 +1,5 @@
+details = "Choose Custom at the end of Settings > EQ, then open Settings > Edit EQ to shape its five bands. Every preset runs through the extension's own filter chain, which keeps loud passages from distorting."
+
+[[screenshots]]
+file = "screenshots/editor.png"
+alt = "The Custom EQ editor, opened from Settings > Edit EQ: the response curve above the five bands and their parameters."
diff --git a/extensions/equalizer/main.c b/extensions/equalizer/main.c
new file mode 100644
index 0000000..c99fb92
--- /dev/null
+++ b/extensions/equalizer/main.c
@@ -0,0 +1,229 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Equalizer: Apple's EQ presets through a cascade with headroom, and a Custom
+ * preset of five bands shaped in the editor screen.
+ *
+ * The count patches and the band defaults are adapted from RepriseOS
+ * payload/patches/patches.c and payload/custom_eq.ui (8fc840d) by lgreitis. */
+
+#include "engine.h"
+#include "presets.h"
+#include "../reprise/reprise.h"
+#include "osos-2.0.5.h"
+#include "rv_libc.h"
+#include "rv_menus.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+
+static const struct rv_api *api;
+static rv_extension_handle self;
+
+/* The Custom preset that plays. */
+static uint8_t values[EQ_VALUES];
+
+/* A low shelf at 60 Hz, a peak at 1 kHz and a high shelf at 8 kHz, all flat;
+ * two bands off at 250 Hz and 4 kHz. */
+static const uint8_t defaults[EQ_VALUES] = {
+ EQ_PRECUT_AUTO,
+ EQ_LOW_SHELF,
+ 5,
+ 4,
+ 24,
+ EQ_PEAKING,
+ 18,
+ 4,
+ 24,
+ EQ_HIGH_SHELF,
+ 27,
+ 4,
+ 24,
+ EQ_OFF,
+ 12,
+ 4,
+ 24,
+ EQ_OFF,
+ 24,
+ 4,
+ 24,
+};
+
+static int valid(const uint8_t *v)
+{
+ if (v[EQ_PRECUT] >= eq_choices[EQ_PRECUT])
+ return 0;
+ for (unsigned int band = 0; band < EQ_BANDS; band++)
+ for (unsigned int parameter = EQ_TYPE; parameter < EQ_PARAMETERS; parameter++)
+ if (v[eq_slot(band, parameter)] >= eq_choices[parameter])
+ return 0;
+ return 1;
+}
+
+/* Plays what the store holds, the defaults when it holds nothing usable. */
+static void load(void)
+{
+ uint8_t stored[EQ_VALUES];
+ const uint8_t *wanted = defaults;
+ if (api->setting_read(self, KEY_VALUES, stored, sizeof stored) == sizeof stored &&
+ valid(stored))
+ wanted = stored;
+ if (!memcmp(values, wanted, EQ_VALUES))
+ return;
+ memcpy(values, wanted, EQ_VALUES);
+ if (!eq_publish(values)) {
+ memcpy(values, defaults, EQ_VALUES);
+ eq_publish(values);
+ }
+}
+
+static void set(const uint8_t *choices)
+{
+ if (eq_publish(choices))
+ memcpy(values, choices, EQ_VALUES);
+}
+
+static void change(unsigned int slot, unsigned int choice)
+{
+ uint8_t trial[EQ_VALUES];
+ memcpy(trial, values, EQ_VALUES);
+ trial[slot] = (uint8_t)choice;
+ set(trial);
+}
+
+static void save(void)
+{
+ api->setting_write(self, KEY_VALUES, RV_SETTING_TYPE_BLOB, values, EQ_VALUES);
+}
+
+static const struct eq_link link = {values, defaults, change,
+ set, save, eq_custom_response};
+
+/* The Custom EQ record of the earlier core: the EQ_VALUES choices as words in
+ * the slot order of shared.h, then a layout word from the Auto precut on. */
+enum { LEGACY_KEY = 0x20514543 /* "CEQ " */, LEGACY_LAYOUT_AUTO_PRECUT = 1 };
+
+/* Only the first start imports the old core's Custom EQ record. Whatever it
+ * holds, KEY_VALUES is written, so a later boot cannot import it; on a core
+ * without the reprise library nothing is imported. The row flag takes its
+ * first value from Apple's EQ preference: Custom was the preset selected
+ * when that is the row after Apple's last. */
+static void import_legacy(void)
+{
+ uint8_t stored[EQ_VALUES];
+ if (reprise_legacy_preference &&
+ api->setting_read(self, KEY_VALUES, stored, sizeof stored) != sizeof stored) {
+ uint32_t record[EQ_VALUES + 1];
+ uint32_t bytes = (reprise_legacy_preference)(LEGACY_KEY, record, sizeof record);
+ int usable = bytes == sizeof record || bytes == sizeof record - 4;
+ /* Auto took precut choice 0; earlier layouts start at 0 dB. */
+ if (usable &&
+ (bytes < sizeof record || record[EQ_VALUES] < LEGACY_LAYOUT_AUTO_PRECUT)) {
+ usable = record[EQ_PRECUT] < eq_choices[EQ_PRECUT] - 1u;
+ record[EQ_PRECUT]++;
+ }
+ for (unsigned int i = 0; usable && i < EQ_VALUES; i++) {
+ usable = record[i] <= 0xff;
+ stored[i] = (uint8_t)record[i];
+ }
+ api->setting_write(self, KEY_VALUES, RV_SETTING_TYPE_BLOB,
+ usable && valid(stored) ? stored : defaults, EQ_VALUES);
+ }
+ int32_t shown;
+ void *preferences = PreferencesService_Get();
+ if (preferences && api->setting_read(self, KEY_CUSTOM_SHOWN, &shown,
+ sizeof shown) != sizeof shown) {
+ typedef uint32_t (*get_fn)(void *, uint32_t, uint32_t);
+ shown = RV_METHOD(preferences, Preferences_get_method,
+ get_fn)(preferences, Preference_EQMenuIndex,
+ Service_Preferences) == EQ_PresetCount;
+ api->setting_write(self, KEY_CUSTOM_SHOWN, RV_SETTING_TYPE_BOOL, &shown,
+ sizeof shown);
+ }
+}
+
+static void open_editor(const struct rv_context *ctx)
+{
+ (void)ctx;
+ api->ui_push(self, "editor", (void *)&link);
+}
+
+/* The Settings row shows while Custom plays. The stored flag carries over a
+ * boot: MediaPlayer_GetInstance builds the player on first use, too early while
+ * extensions load, and the preset it then takes is the one stored anyway. */
+static uint32_t eq_apply(uintptr_t player, uint32_t settings_id, const void *next)
+{
+ uint32_t result = api->hook_next(next, player, settings_id, 0, 0, 0, 0);
+ int custom = MediaPlayer_GetEQSettingsId((void *)player) == EQ_CUSTOM_SETTINGS_ID;
+ if (api->setting_get_int(self, KEY_CUSTOM_SHOWN) != custom)
+ api->setting_set_int(self, KEY_CUSTOM_SHOWN, custom);
+ return result;
+}
+
+static void setting_changed(uint16_t key)
+{
+ if (key == KEY_VALUES || key == RV_SETTING_KEY_ALL)
+ load();
+}
+
+static void unload(void)
+{
+ /* Apple's code has no row for Custom once the tables are its own again. */
+ if (MediaPlayer_GetEQSettingsId(MediaPlayer_GetInstance()) == EQ_CUSTOM_SETTINGS_ID)
+ SettingsModel_SelectEQMenuIndex(SettingsModel_GetInstance(), 0);
+ eq_engine_stop();
+}
+
+/* Bound in this order: the engine before anything can ask for the Custom
+ * preset, the tables before the counts that reach into them, the id map last. */
+static const struct rv_hook hooks[] = {
+ RV_HOOK_REPLACE(RV_SITE_EQ_Process_slot, eq_process),
+ RV_HOOK_REPLACE(RV_SITE_EQ_Reset_slot, eq_reset),
+ RV_HOOK_REPLACE(RV_SITE_EQ_SetPreset_Load_call, eq_load),
+ RV_HOOK_REPLACE(RV_SITE_EQ_SetRate_Load_call, eq_load),
+ RV_HOOK_WORD(RV_SITE_EQ_DspCount_word, 0xe3510018), /* cmp r1, #EQ_ROWS */
+ RV_HOOK_POINTER(RV_SITE_EQ_MenuIds_literal, eq_preset_ids),
+ RV_HOOK_POINTER(RV_SITE_EQ_SettingsIds_literal, eq_preset_ids),
+ RV_HOOK_POINTER(RV_SITE_EQ_PreviewTable_literal, eq_preset_rows),
+ RV_HOOK_POINTER(RV_SITE_EQ_NameTable_literal, eq_preset_rows),
+ RV_HOOK_POINTER(RV_SITE_EQ_ResourceTable_literal, eq_preset_rows),
+ RV_HOOK_WORD(RV_SITE_EQ_PreviewCount_word, 0xe3510018), /* cmp r1, #EQ_ROWS */
+ RV_HOOK_WORD(RV_SITE_EQ_NameCount_word, 0xe3510018), /* cmp r1, #EQ_ROWS */
+ RV_HOOK_WORD(RV_SITE_EQ_SettingsCount_word, 0xe3520018), /* cmp r2, #EQ_ROWS */
+ RV_HOOK_WORD(RV_SITE_EQ_ProviderCount_word, 0xe3a00018), /* mov r0, #EQ_ROWS */
+ RV_HOOK_WORD(RV_SITE_EQ_ResourceCount_word, 0xe3550018), /* cmp r5, #EQ_ROWS */
+ RV_HOOK_REPLACE(RV_SITE_EQ_TrackPreset_call, eq_track_preset),
+ RV_HOOK_REPLACE(RV_SITE_EQ_SettingsIdToDspPreset_entry, eq_map_preset),
+ RV_HOOK_FILTER(RV_SITE_EQ_ApplySettingsId_slot, eq_apply),
+};
+
+static const struct rv_setting settings[] = {
+ RV_SETTING_BOOL(KEY_CUSTOM_SHOWN, NULL, 0),
+};
+
+static const struct rv_menu_entry entries[] = {
+ RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_EQ,
+ RV_ROW_ACTION("Edit EQ", open_editor),
+ .pane = RV_PANE(.caption = "Adjust Your Sound",
+ .bitmap = RV_BITMAP("settings-eq")),
+ .shown_by = KEY_CUSTOM_SHOWN),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+ RV_SETTINGS(settings),
+ .unload = unload,
+ .setting_changed = setting_changed,
+ RV_ENTRIES(entries),
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ api = core;
+ self = handle;
+ eq_engine_start(core);
+ eq_presets_start(api->string_resource(self, "Custom"));
+ import_legacy();
+ load();
+ return &extension;
+}
diff --git a/extensions/equalizer/manifest.toml b/extensions/equalizer/manifest.toml
new file mode 100644
index 0000000..a797dfc
--- /dev/null
+++ b/extensions/equalizer/manifest.toml
@@ -0,0 +1,27 @@
+id = "equalizer"
+name = "Equalizer"
+description = "Stop the EQ presets from distorting, and add a Custom preset with five bands you shape yourself."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "effects"
+
+[libraries]
+required = ["dsp"]
+optional = ["reprise"]
+
+[[module]]
+name = "main"
+trigger = "always"
+
+[[module]]
+name = "editor"
+trigger = "screen"
+screens = ["editor"]
+
+[[asset]]
+name = "settings-eq"
+file = "assets/settings-eq.png"
+pane = "icon"
diff --git a/extensions/equalizer/presets.c b/extensions/equalizer/presets.c
new file mode 100644
index 0000000..9df6f6e
--- /dev/null
+++ b/extensions/equalizer/presets.c
@@ -0,0 +1,50 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Apple keeps the EQ presets in two tables of EQ_PresetCount rows: the settings
+ * ids and the name and preview resource ids. Six count words and five literals
+ * in the image give their length and address; the extension points them at
+ * copies one row longer, and maps the Custom settings id to the DSP preset
+ * after Apple's last, which the engine plays.
+ *
+ * Adapted from RepriseOS payload/custom_eq.c and payload/custom_eq.S (8fc840d) by
+ * lgreitis. */
+
+#include "presets.h"
+#include "engine.h"
+#include "rv_api.h"
+#include "rv_libc.h"
+
+uint32_t eq_preset_ids[EQ_ROWS];
+uint32_t eq_preset_rows[EQ_ROWS * EQPreset_bytes / sizeof(uint32_t)];
+
+void eq_presets_start(uint32_t name)
+{
+ uint8_t *custom = (uint8_t *)eq_preset_rows + EQ_PresetCount * EQPreset_bytes;
+ memcpy(eq_preset_ids, EQ_PresetIds, EQ_PresetCount * sizeof(uint32_t));
+ memcpy(eq_preset_rows, EQ_Presets, EQ_PresetCount * EQPreset_bytes);
+ eq_preset_ids[EQ_PresetCount] = EQ_CUSTOM_SETTINGS_ID;
+ /* Off and Flat share a preview: the flat line. */
+ RV_FIELD(custom, EQPreset_preview, uint32_t) =
+ RV_FIELD(EQ_Presets, EQPreset_preview, uint32_t);
+ RV_FIELD(custom, EQPreset_name, uint32_t) = name;
+}
+
+uint32_t eq_map_preset(uint32_t settings_id, const void *next)
+{
+ (void)next;
+ /* Apple's ids and Custom's are consecutive, as the presets they map to. */
+ uint32_t n = settings_id - EQ_SettingsId_First;
+ return n < EQ_PresetCount ? n + 1 : 0;
+}
+
+uint32_t eq_track_preset(struct MediaItem *item, struct MediaTrack *track,
+ const void *next)
+{
+ (void)track;
+ (void)next;
+ /* A track's own preset replaces the player's unless that is Flat; Custom
+ * holds as well. */
+ if (MediaPlayer_GetEQSettingsId(MediaPlayer_GetInstance()) == EQ_CUSTOM_SETTINGS_ID)
+ return 0;
+ return MediaItem_GetEQSettingsId(item);
+}
diff --git a/extensions/equalizer/presets.h b/extensions/equalizer/presets.h
new file mode 100644
index 0000000..74042ce
--- /dev/null
+++ b/extensions/equalizer/presets.h
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The Custom preset's row in Apple's EQ tables. */
+
+#ifndef EQUALIZER_PRESETS_H
+#define EQUALIZER_PRESETS_H
+#include "osos-2.0.5.h"
+
+/* The settings id of the Custom preset, after Apple's last. */
+#define EQ_CUSTOM_SETTINGS_ID (EQ_SettingsId_Last + 1)
+/* The rows of the EQ list with Custom. */
+#define EQ_ROWS (EQ_PresetCount + 1)
+
+/* Copies of Apple's two tables with the Custom row appended, for the literal
+ * sites. eq_presets_start fills them, naming the row by the string resource
+ * `name`; before that they are zero. */
+extern uint32_t eq_preset_ids[EQ_ROWS];
+extern uint32_t eq_preset_rows[EQ_ROWS * EQPreset_bytes / sizeof(uint32_t)];
+void eq_presets_start(uint32_t name);
+
+/* Hook handlers. */
+uint32_t eq_map_preset(uint32_t settings_id, const void *next);
+uint32_t eq_track_preset(struct MediaItem *item, struct MediaTrack *track,
+ const void *next);
+
+#endif
diff --git a/extensions/equalizer/screenshots/editor.png b/extensions/equalizer/screenshots/editor.png
new file mode 100644
index 0000000..89be125
Binary files /dev/null and b/extensions/equalizer/screenshots/editor.png differ
diff --git a/extensions/equalizer/shared.h b/extensions/equalizer/shared.h
new file mode 100644
index 0000000..588639f
--- /dev/null
+++ b/extensions/equalizer/shared.h
@@ -0,0 +1,82 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* What the two modules of Equalizer agree on.
+ *
+ * The parameter choices and the band type enum are adapted from RepriseOS
+ * payload/custom_eq.ui and payload/eq_coefficients.h (8fc840d) by lgreitis. */
+
+#ifndef EQUALIZER_SHARED_H
+#define EQUALIZER_SHARED_H
+#include
+
+enum { EQ_BANDS = 5 };
+
+enum eq_type { EQ_OFF, EQ_PEAKING, EQ_LOW_SHELF, EQ_HIGH_SHELF };
+
+/* The Custom preset is EQ_VALUES choices, one byte each: the precut, then each
+ * band's type, frequency, Q and gain. The order and the choices are the saved
+ * format. */
+enum {
+ EQ_PRECUT, /* 0 is Auto, then 0.0 to -10.0 dB in tenths */
+ EQ_TYPE, /* enum eq_type */
+ EQ_FREQUENCY, /* an index into eq_frequencies */
+ EQ_Q, /* 0.3 to 4.0 in tenths */
+ EQ_GAIN, /* -12.0 to +12.0 dB in halves */
+ EQ_PARAMETERS,
+ EQ_VALUES = 1 + EQ_BANDS * (EQ_PARAMETERS - 1),
+};
+
+#define KEY_VALUES 1 /* blob: the EQ_VALUES choices */
+#define KEY_CUSTOM_SHOWN \
+ 2 /* bool: Custom is the preset that plays; shows the Settings row */
+
+enum { EQ_PRECUT_AUTO = 0 };
+
+static const uint8_t eq_choices[EQ_PARAMETERS] = {102, 4, 32, 38, 49};
+
+static const uint16_t eq_frequencies[] = {
+ 20, 25, 31, 40, 50, 60, 70, 80, 100, 125, 160,
+ 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000,
+ 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000, 20000,
+};
+
+/* Where a band's parameter is among the choices; the precut has no band. */
+static inline unsigned int eq_slot(unsigned int band, unsigned int parameter)
+{
+ return parameter == EQ_PRECUT ? 0 : parameter + band * (EQ_PARAMETERS - 1);
+}
+
+/* Choices as tenths: of a decibel for precut (below zero) and gain, of one for Q. */
+static inline int eq_precut_tenths(unsigned int choice)
+{
+ return 1 - (int)choice;
+}
+
+static inline int eq_q_tenths(unsigned int choice)
+{
+ return 3 + (int)choice;
+}
+
+static inline int eq_gain_tenths(unsigned int choice)
+{
+ return (int)choice * 5 - 120;
+}
+
+/* What main passes the editor screen as its argument. The editor module links
+ * none of the filter code; it calls main's. */
+struct eq_link {
+ const uint8_t *values; /* the EQ_VALUES choices that play */
+ const uint8_t *defaults; /* the choices a reset returns to */
+ /* Plays one choice changed. Nothing changes when a band then has no stable
+ * filter. */
+ void (*change)(unsigned int slot, unsigned int choice);
+ /* Plays a whole set of choices, under the same rule. */
+ void (*set)(const uint8_t *choices);
+ void (*save)(void); /* stores the choices */
+ /* What plays, at `points` frequencies from 20 Hz to 20 kHz evenly spaced in
+ * octaves, in tenths of a decibel. Returns the precut applied, in tenths
+ * of a decibel. */
+ unsigned int (*response)(int16_t *tenths, unsigned int points);
+};
+
+#endif
diff --git a/extensions/equalizer/tests/engine_test.c b/extensions/equalizer/tests/engine_test.c
new file mode 100644
index 0000000..208c6d5
--- /dev/null
+++ b/extensions/equalizer/tests/engine_test.c
@@ -0,0 +1,487 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The engine on the host, against a double-precision cascade: Apple's loader,
+ * reset and process are stubs, and the ThreeBandEQ is a byte array. Includes
+ * engine.c for its state. */
+
+#include
+#include
+#include
+#include
+
+#include "../engine.c"
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+enum { BASS_PRESET = 8, FRAMES = 2048, D = RV_LIMITER_FRAMES };
+
+static uint8_t record[ThreeBandEQ_bytes + 16]; /* the last 16 bytes a guard */
+static unsigned int loads, resets, passes, irq_depth;
+
+static uint32_t irq_save(void)
+{
+ assert(!irq_depth++);
+ return 0x13;
+}
+
+static void irq_restore(uint32_t state)
+{
+ assert(state == 0x13 && irq_depth-- == 1);
+}
+
+static const struct rv_api fake_api = {.irq_save = irq_save,
+ .irq_restore = irq_restore};
+
+static uint8_t *stage(void *eq, unsigned int i)
+{
+ return (uint8_t *)eq + ThreeBandEQ_stages + i * EQStage_bytes;
+}
+
+/* Apple's loader: three identity stages, bypassed but for the Bass preset's
+ * second, a +6 dB low shelf at 1 kHz; enabled for a preset at 44.1 or 48 kHz. */
+void EQ_LoadPresetCoefficients(struct ThreeBandEQ *eq)
+{
+ uint32_t preset = RV_FIELD(eq, ThreeBandEQ_preset, uint32_t);
+ uint32_t rate = RV_FIELD(eq, ThreeBandEQ_sample_rate, uint32_t);
+ assert(preset != EQ_CUSTOM_PRESET);
+ loads++;
+ for (unsigned int i = 0; i < NATIVE_STAGES; i++) {
+ int32_t shelf[5] = {UNITY, 0, 0, 0, 0};
+ int bass = i == 1 && preset == BASS_PRESET && supported(rate);
+ if (bass)
+ assert(rv_dsp_biquad(shelf, EQ_LOW_SHELF, 1000, 7, 60, 0, rate));
+ RV_FIELD(stage(eq, i), EQStage_b0, int32_t) = shelf[0];
+ RV_FIELD(stage(eq, i), EQStage_b1, int32_t) = shelf[1];
+ RV_FIELD(stage(eq, i), EQStage_b2, int32_t) = shelf[2];
+ RV_FIELD(stage(eq, i), EQStage_a1, int32_t) = shelf[3];
+ RV_FIELD(stage(eq, i), EQStage_a2, int32_t) = shelf[4];
+ RV_FIELD(stage(eq, i), EQStage_bypass, uint8_t) = !bass;
+ }
+ RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t) = preset && supported(rate);
+}
+
+void EQ_ResetAllBiquadStates(struct ThreeBandEQ *eq)
+{
+ (void)eq;
+ resets++;
+}
+
+void EQ_ProcessThreeBiquadsInPlace(struct ThreeBandEQ *eq, int16_t *input,
+ uint32_t frames, int16_t **output,
+ uint32_t *output_frames)
+{
+ (void)eq;
+ passes++;
+ *output = input;
+ *output_frames = frames;
+}
+
+static void process(int16_t *samples, unsigned int frames)
+{
+ int16_t *output = NULL;
+ uint32_t count = 0;
+ eq_process((struct ThreeBandEQ *)record, samples, frames, &output, NULL, &count);
+ assert(output == samples && count == frames);
+}
+
+static void load(uint32_t preset, uint32_t rate)
+{
+ RV_FIELD(record, ThreeBandEQ_preset, uint32_t) = preset;
+ RV_FIELD(record, ThreeBandEQ_sample_rate, uint32_t) = rate;
+ eq_load((struct ThreeBandEQ *)record, NULL);
+}
+
+static void noise(int16_t *samples, unsigned int frames)
+{
+ for (unsigned int i = 0; i < frames; i++) {
+ samples[i * 2] = (int16_t)((int)(i * 71 % 2000) - 1000);
+ samples[i * 2 + 1] = (int16_t)((int)(i * 173 % 4000) - 2000);
+ }
+}
+
+static void sine(int16_t *samples, unsigned int frames, double hz, double amplitude)
+{
+ for (unsigned int i = 0; i < frames; i++)
+ samples[i * 2] = samples[i * 2 + 1] =
+ (int16_t)lrint(amplitude * sin(2 * M_PI * hz * i / 44100));
+}
+
+/* A double-precision cascade from rest; returns the largest magnitude before
+ * saturation. */
+static double reference(const int32_t (*k)[5], unsigned int stages, const int16_t *in,
+ int16_t *out, unsigned int frames)
+{
+ double peak = 0;
+ for (unsigned int c = 0; c < 2; c++) {
+ double h[EQ_BANDS][4] = {{0}};
+ for (unsigned int i = 0; i < frames; i++) {
+ double x = in[i * 2 + c];
+ for (unsigned int s = 0; s < stages; s++) {
+ double y = (k[s][0] * x + k[s][1] * h[s][0] + k[s][2] * h[s][1] -
+ k[s][3] * h[s][2] - k[s][4] * h[s][3]) /
+ 16777216.0;
+ h[s][1] = h[s][0];
+ h[s][0] = x;
+ h[s][3] = h[s][2];
+ h[s][2] = y;
+ x = y;
+ }
+ peak = fmax(peak, fabs(x));
+ long rounded = lrint(x);
+ out[i * 2 + c] = (int16_t)(rounded > 32767 ? 32767
+ : rounded < -32768 ? -32768
+ : rounded);
+ }
+ }
+ return peak;
+}
+
+/* The double cascade from rest on the left channel, unsaturated into both;
+ * returns the largest magnitude. */
+static double reference_wide(const int32_t (*k)[5], const int16_t *in, double *out,
+ unsigned int frames)
+{
+ double peak = 0, h[EQ_BANDS][4] = {{0}};
+ for (unsigned int i = 0; i < frames; i++) {
+ double x = in[i * 2];
+ for (unsigned int s = 0; s < EQ_BANDS; s++) {
+ double y = (k[s][0] * x + k[s][1] * h[s][0] + k[s][2] * h[s][1] -
+ k[s][3] * h[s][2] - k[s][4] * h[s][3]) /
+ 16777216.0;
+ h[s][1] = h[s][0];
+ h[s][0] = x;
+ h[s][3] = h[s][2];
+ h[s][2] = y;
+ x = y;
+ }
+ out[i * 2] = out[i * 2 + 1] = x;
+ peak = fmax(peak, fabs(x));
+ }
+ return peak;
+}
+
+/* The output plays D frames late: frame i of `a` against frame i - D of `b`. */
+static int max_difference(const int16_t *a, const int16_t *b, unsigned int frames)
+{
+ a += D * 2;
+ frames -= D;
+ int worst = 0;
+ for (unsigned int i = 0; i < frames * 2; i++) {
+ int d = a[i] > b[i] ? a[i] - b[i] : b[i] - a[i];
+ worst = d > worst ? d : worst;
+ }
+ return worst;
+}
+
+/* The cascade alone, in place, saturated. */
+static void cascade_in_place(struct rv_dsp_stage *stages, int16_t *samples,
+ unsigned int frames)
+{
+ int32_t wide[RV_LIMITER_CHUNK_FRAMES * 2];
+ for (unsigned int done = 0; done < frames; done += RV_LIMITER_CHUNK_FRAMES) {
+ rv_dsp_cascade_run(stages, EQ_BANDS, samples + done * 2, wide,
+ RV_LIMITER_CHUNK_FRAMES);
+ for (unsigned int i = 0; i < RV_LIMITER_CHUNK_FRAMES * 2; i++)
+ samples[done * 2 + i] = rv_saturate16(wide[i]);
+ }
+}
+
+/* Choices: Auto or a precut in tenths below zero; the frequency as an index. */
+static unsigned int precut_choice(int tenths)
+{
+ return (unsigned int)(1 - tenths);
+}
+
+static unsigned int frequency_choice(unsigned int hz)
+{
+ for (unsigned int i = 0;; i++)
+ if (eq_frequencies[i] == hz)
+ return i;
+}
+
+static unsigned int gain_choice(int tenths)
+{
+ return (unsigned int)(tenths + 120) / 5;
+}
+
+static unsigned int q_choice(int tenths)
+{
+ return (unsigned int)(tenths - 3);
+}
+
+static void band(uint8_t *values, unsigned int i, unsigned int type, unsigned int hz,
+ int q_tenths, int gain_tenths)
+{
+ values[eq_slot(i, EQ_TYPE)] = (uint8_t)type;
+ values[eq_slot(i, EQ_FREQUENCY)] = (uint8_t)frequency_choice(hz);
+ values[eq_slot(i, EQ_Q)] = (uint8_t)q_choice(q_tenths);
+ values[eq_slot(i, EQ_GAIN)] = (uint8_t)gain_choice(gain_tenths);
+}
+
+static void flat(uint8_t *values, unsigned int precut)
+{
+ memset(values, 0, EQ_VALUES);
+ values[EQ_PRECUT] = (uint8_t)precut;
+ for (unsigned int i = 0; i < EQ_BANDS; i++)
+ band(values, i, EQ_OFF, 1000, 7, 0);
+}
+
+static void histories_at_rest(void)
+{
+ struct rv_dsp_stage rest;
+ rv_dsp_cascade_rest(&rest, 1);
+ for (unsigned int i = 0; i < EQ_BANDS; i++)
+ for (unsigned int c = 0; c < 2; c++) {
+ for (unsigned int n = 0; n < 4; n++)
+ assert(!playing[i].history[c][n]);
+ assert(playing[i].error[c] == rest.error[0]);
+ }
+}
+
+int main(void)
+{
+ static int16_t samples[FRAMES * 2], expected[FRAMES * 2], previous[FRAMES * 2];
+ static struct rv_dsp_stage old_stages[EQ_BANDS], new_stages[EQ_BANDS];
+ uint8_t values[EQ_VALUES], untouched[sizeof record];
+ eq_engine_start(&fake_api);
+ memset(record + ThreeBandEQ_bytes, 0xdb, 16);
+
+ /* Before the first load, Apple's process runs. */
+ noise(samples, 64);
+ process(samples, 64);
+ assert(passes == 1 && !owner);
+
+ for (unsigned int rate = 44100; rate <= 48000; rate += 3900) {
+ unsigned int bank = rate == 48000;
+ /* A manual 6.5 dB precut and three bells match the double cascade. */
+ flat(values, precut_choice(-65));
+ band(values, 0, EQ_PEAKING, 60, 7, 50);
+ band(values, 1, EQ_PEAKING, 160, 7, 50);
+ band(values, 2, EQ_PEAKING, 1000, 7, 50);
+ assert(eq_publish(values) && custom_precut[bank] == 65);
+ load(EQ_CUSTOM_PRESET, rate);
+ assert(RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) &&
+ owner == (void *)record);
+ memcpy(untouched, record, sizeof record);
+ if (rate == 44100) {
+ /* The first set fades in from dry: the input plays alone while
+ * the limiter fills, then blends into the EQ. */
+ noise(samples, 256);
+ memcpy(previous, samples, 512 * sizeof *samples);
+ process(samples, 256);
+ assert(!memcmp(samples, previous, D * 2 * sizeof *samples));
+ assert(memcmp(samples, previous, 256 * 2 * sizeof *samples));
+ eq_reset((struct ThreeBandEQ *)record, NULL);
+ }
+ noise(samples, 256);
+ reference(custom[bank], EQ_BANDS, samples, expected, 256);
+ process(samples, 256);
+ assert(max_difference(samples, expected, 256) <= 1);
+ assert(!memcmp(record, untouched, sizeof record) && passes == 1);
+ assert(playing[3].bypass && playing[4].bypass);
+
+ /* A live edit fades from the old five stages to the new over 128 frames. */
+ memcpy(old_stages, playing, sizeof old_stages);
+ band(values, 3, EQ_PEAKING, 4000, 7, 50);
+ band(values, 4, EQ_PEAKING, 8000, 7, 50);
+ assert(eq_publish(values) && next.fade);
+ for (unsigned int i = 0; i < EQ_BANDS; i++) {
+ new_stages[i].b0 = custom[bank][i][0];
+ new_stages[i].b1 = custom[bank][i][1];
+ new_stages[i].b2 = custom[bank][i][2];
+ new_stages[i].a1 = -custom[bank][i][3];
+ new_stages[i].a2 = -custom[bank][i][4];
+ new_stages[i].bypass = 0;
+ }
+ rv_dsp_cascade_rest(new_stages, EQ_BANDS);
+ noise(samples, 256);
+ memcpy(expected, samples, 512 * sizeof *samples);
+ memcpy(previous, samples, 512 * sizeof *samples);
+ cascade_in_place(old_stages, previous, 128);
+ cascade_in_place(new_stages, expected, 256);
+ for (unsigned int i = 0; i < 128; i++)
+ for (unsigned int c = 0; c < 2; c++) {
+ unsigned int n = i * 2 + c;
+ expected[n] = (int16_t)(((int32_t)previous[n] * (127 - (int)i) +
+ (int32_t)expected[n] * ((int)i + 1)) >>
+ 7);
+ }
+ process(samples, 17);
+ assert(fade.remaining == 111);
+ process(samples + 34, 239);
+ assert(!fade.remaining &&
+ !memcmp(samples + D * 2, expected, (256 - D) * 2 * sizeof *samples));
+ assert(!memcmp(record, untouched, sizeof record));
+
+ /* A reset puts the histories at rest and ends a fade. */
+ values[eq_slot(4, EQ_GAIN)] = (uint8_t)gain_choice(-50);
+ assert(eq_publish(values));
+ process(samples, 1);
+ assert(fade.remaining == 127);
+ eq_reset((struct ThreeBandEQ *)record, NULL);
+ assert(rest_pending);
+ process(samples, 1);
+ assert(!fade.remaining);
+ eq_reset((struct ThreeBandEQ *)record, NULL);
+ process(samples, 0);
+ histories_at_rest();
+ }
+
+ /* A +12 dB bell and its inverse are transparent at a 30000 peak; between
+ * them the signal passes 60000, which a 16-bit stage would saturate. */
+ flat(values, precut_choice(0));
+ band(values, 0, EQ_PEAKING, 1000, 7, 120);
+ band(values, 1, EQ_PEAKING, 1000, 7, -120);
+ assert(eq_publish(values) && custom_precut[0] == 0);
+ load(EQ_CUSTOM_PRESET, 44100);
+ sine(samples, FRAMES, 1000, 30000);
+ assert(reference(custom[0], 1, samples, expected, FRAMES) > 60000);
+ memcpy(previous, samples, sizeof samples);
+ process(samples, FRAMES);
+ assert(max_difference(samples, previous, FRAMES) <= 2);
+
+ /* Auto precut takes a +6 dB low shelf's boost back out; 0 dB would clip. */
+ flat(values, precut_choice(0));
+ band(values, 0, EQ_LOW_SHELF, 1000, 7, 60);
+ assert(eq_publish(values));
+ sine(samples, FRAMES, 100, 32767);
+ assert(reference(custom[0], EQ_BANDS, samples, expected, FRAMES) > 60000);
+ values[EQ_PRECUT] = EQ_PRECUT_AUTO;
+ assert(eq_publish(values));
+ assert(custom_precut[0] >= 60 && custom_precut[0] <= 61 &&
+ rv_dsp_peak(custom[0], 5, 44100) <= 0);
+ load(EQ_CUSTOM_PRESET, 44100);
+ assert(reference(custom[0], EQ_BANDS, samples, expected, FRAMES) <= 32767.5);
+ process(samples, FRAMES);
+ assert(max_difference(samples, expected, FRAMES) <= 1);
+
+ /* Error feedback keeps low poles from amplifying the rounding: a 20 Hz bell
+ * and a 60 Hz shelf, both +12 dB, track the double cascade. */
+ flat(values, precut_choice(0));
+ band(values, 0, EQ_PEAKING, 20, 19, 120);
+ band(values, 1, EQ_LOW_SHELF, 60, 7, 120);
+ assert(eq_publish(values));
+ load(EQ_CUSTOM_PRESET, 44100);
+ sine(samples, FRAMES, 1000, 1000);
+ reference(custom[0], EQ_BANDS, samples, expected, FRAMES);
+ process(samples, FRAMES);
+ double error = 0;
+ for (unsigned int i = D * 2; i < FRAMES * 2; i++)
+ error += (double)(samples[i] - expected[i - D * 2]) *
+ (samples[i] - expected[i - D * 2]);
+ assert(sqrt(error / ((FRAMES - D) * 2)) < 0.2);
+
+ /* Auto precut bounds the response, not the samples: full-scale input with
+ * the signs of the time-reversed impulse response lines every tap's
+ * phase up and goes over. The limiter brings the peak to full scale and
+ * scales its neighbours alike instead of clipping. */
+ flat(values, EQ_PRECUT_AUTO);
+ band(values, 0, EQ_LOW_SHELF, 60, 7, 60);
+ band(values, 1, EQ_HIGH_SHELF, 8000, 7, 60);
+ assert(eq_publish(values));
+ load(EQ_CUSTOM_PRESET, 44100);
+
+ enum { TAPS = 512 };
+
+ static int16_t impulse[TAPS * 2], response[TAPS * 2];
+ static double wide_reference[FRAMES * 2];
+ impulse[0] = impulse[1] = 32767;
+ reference(custom[0], EQ_BANDS, impulse, response, TAPS);
+ for (unsigned int i = 0; i < FRAMES; i++) {
+ int16_t tap = response[(TAPS - 1 - i % TAPS) * 2];
+ samples[i * 2] = samples[i * 2 + 1] = (int16_t)(tap < 0 ? -32767 : 32767);
+ }
+ double over = reference_wide(custom[0], samples, wide_reference, FRAMES);
+ assert(over > 32767 * 1.2);
+ unsigned int at = 0;
+ for (unsigned int i = TAPS; i < FRAMES - D; i++)
+ if (fabs(wide_reference[i * 2]) > fabs(wide_reference[at * 2]))
+ at = i;
+ memcpy(previous, samples, sizeof samples);
+ process(samples, FRAMES);
+ for (unsigned int i = 0; i < FRAMES - D; i++)
+ assert(fabs((double)samples[(i + D) * 2]) <= fabs(wide_reference[i * 2]) + 1);
+ assert(fabs((double)samples[(at + D) * 2]) >= 32760);
+ double ratio = wide_reference[(at - 1) * 2] / wide_reference[at * 2];
+ assert(fabs((double)samples[(at - 1 + D) * 2] / samples[(at + D) * 2] - ratio) <
+ 0.02);
+ rv_limiter_rest(&limiter); /* rather than wait out the release */
+
+ /* An Apple preset: its stages are copied, the first cut by the peak, and
+ * its record is left as Apple's loader wrote it. */
+ unsigned int before = loads;
+ load(BASS_PRESET, 44100);
+ assert(loads == before + 1 && RV_FIELD(record, ThreeBandEQ_enabled, uint8_t));
+ assert(!plays_custom && next.count == 1);
+ int32_t shelf[5], attenuated[5];
+ assert(rv_dsp_biquad(shelf, EQ_LOW_SHELF, 1000, 7, 60, 0, 44100));
+ assert(RV_FIELD(stage(record, 1), EQStage_b0, int32_t) == shelf[0]);
+ int peak = rv_dsp_peak((const int32_t (*)[5])shelf, 1, 44100);
+ assert(peak >= 60 && peak <= 61 && (native_precut & 0xff) == (uint32_t)peak);
+ memcpy(attenuated, shelf, sizeof shelf);
+ rv_dsp_attenuate(attenuated, (unsigned int)peak);
+ assert(!memcmp(next.coefficients[0], attenuated, sizeof attenuated));
+ uint32_t cached = native_precut;
+ load(BASS_PRESET, 44100);
+ assert(loads == before + 2 && native_precut == cached);
+ eq_reset((struct ThreeBandEQ *)record, NULL);
+ sine(samples, FRAMES, 100, 32767);
+ assert(reference((const int32_t (*)[5])attenuated, 1, samples, expected, FRAMES) <=
+ 32767.5);
+ process(samples, FRAMES);
+ assert(max_difference(samples, expected, FRAMES) <= 1);
+
+ /* An unsupported rate: nothing plays, for Apple's presets or Custom. */
+ load(BASS_PRESET, 32000);
+ assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && !next.count);
+ load(EQ_CUSTOM_PRESET, 32000);
+ assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && !next.count &&
+ !plays_custom);
+ noise(samples, 256);
+ memcpy(expected, samples, 512 * sizeof *samples);
+ process(samples, 256);
+ assert(!memcmp(samples, expected, 512 * sizeof *samples)); /* no delay either */
+
+ /* Off: Apple's loader disables the EQ; the engine has nothing to play. */
+ load(0, 44100);
+ assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && !next.count);
+
+ /* A preset after Off fades in from dry: Apple ran nothing meanwhile, so
+ * neither the old stages nor what the limiter held play. */
+ load(BASS_PRESET, 44100);
+ eq_reset((struct ThreeBandEQ *)record, NULL);
+ noise(samples, 512);
+ memcpy(previous, samples, 1024 * sizeof *samples);
+ process(samples, 512);
+ assert(!memcmp(samples, previous, D * 2 * sizeof *samples));
+ assert(!fade.remaining && running(playing));
+
+ /* A flat set passes the audio through undelayed, and nothing runs per
+ * sample; the reset after its load keeps the fade from the delayed
+ * output, which ends exactly on the input. */
+ flat(values, precut_choice(0));
+ assert(eq_publish(values));
+ load(EQ_CUSTOM_PRESET, 44100);
+ eq_reset((struct ThreeBandEQ *)record, NULL);
+ noise(samples, 512);
+ memcpy(previous, samples, 1024 * sizeof *samples);
+ process(samples, 512);
+ assert(!running(playing) && !fade.remaining);
+ assert(memcmp(samples, previous, RV_FADE_FRAMES * 2 * sizeof *samples));
+ assert(!memcmp(samples + RV_FADE_FRAMES * 2, previous + RV_FADE_FRAMES * 2,
+ (512 - RV_FADE_FRAMES) * 2 * sizeof *samples));
+
+ /* Stopping while Custom plays turns the EQ off in Apple's record. */
+ load(EQ_CUSTOM_PRESET, 44100);
+ assert(RV_FIELD(record, ThreeBandEQ_enabled, uint8_t));
+ eq_engine_stop();
+ assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) &&
+ !RV_FIELD(record, ThreeBandEQ_preset, uint32_t));
+ for (unsigned int i = 0; i < 16; i++)
+ assert(record[ThreeBandEQ_bytes + i] == 0xdb);
+ assert(passes == 1 && resets == 8);
+ puts("engine: cascade headroom, precut, crossfade, reset and stop passed");
+ return 0;
+}
diff --git a/extensions/equalizer/tests/run.py b/extensions/equalizer/tests/run.py
new file mode 100755
index 0000000..cbfecf7
--- /dev/null
+++ b/extensions/equalizer/tests/run.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
+"""Run the host tests with a staged SDK: python3 tests/run.py SDK."""
+
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+root = Path(__file__).resolve().parent
+dsp = root.parents[1] / "dsp"
+
+
+def run_engine_test(work):
+ """The engine against a double-precision cascade, in tests/engine_test.c."""
+ program = work / "engine_test"
+ subprocess.run(
+ ["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", "-g"]
+ + [
+ "-fsanitize=undefined",
+ "-fno-sanitize-recover=undefined",
+ f"-I{sdk}",
+ f"-I{dsp}",
+ ]
+ + ["-D_FORTIFY_SOURCE=0"] # macOS string.h would wrap what rv_libc.h declares
+ + [str(root / "engine_test.c"), str(dsp / "cascade.c")]
+ + [
+ str(dsp / "filter.c"),
+ str(dsp / "math.c"),
+ str(dsp / "limiter.c"),
+ "-lm",
+ "-o",
+ str(program),
+ ],
+ check=True,
+ )
+ subprocess.run([str(program)], check=True)
+
+
+sdk = Path(sys.argv[1]).resolve()
+with tempfile.TemporaryDirectory(prefix="equalizer-tests-") as name:
+ run_engine_test(Path(name))
+print("Equalizer tests passed")
diff --git a/extensions/eu-volume-limit/Makefile b/extensions/eu-volume-limit/Makefile
new file mode 100644
index 0000000..cb973a7
--- /dev/null
+++ b/extensions/eu-volume-limit/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c
+include $(SDK)/rv.mk
diff --git a/extensions/eu-volume-limit/README.md b/extensions/eu-volume-limit/README.md
new file mode 100644
index 0000000..d100b39
--- /dev/null
+++ b/extensions/eu-volume-limit/README.md
@@ -0,0 +1,24 @@
+# EU Volume Limit
+
+By paviro.
+
+Gives an EU iPod the volume behaviour of a non-EU one. With the EU Volume Limit switch in Settings > Volume Limit off, the volume goes 15% higher; with it on, the EU cap stays. Other iPods are unchanged.
+
+| | Stock EU iPod | With the extension |
+|---|---|---|
+| Ceiling with the switch off | 222 | 256 on Apple's scale, 15% higher |
+| Ceiling with the switch on | 168 | 168 |
+| Default volume limit | 222 | 256; a saved limit is kept |
+| High-volume warning | yes | never |
+| Saved volume lowered at startup | yes | never |
+| Volume lowered after 20 hours of listening | yes | never |
+
+Apple checks two region flags, bit 0 and bit 7, and accepts a stored override where it checks bit 7. Stock shows the switch only for bit 7 and holds a bit-0 iPod at 222 without one; the extension shows it for either. It patches seven constants in 2.0.5.
+
+Turned off, Apple's behaviour returns at once, except the startup clamp, which returns at the next boot. The current volume and saved limit are kept.
+
+| | |
+|---|---|
+| Default | off |
+| Memory | image only |
+| Settings | none; Apple stores the switch |
diff --git a/extensions/eu-volume-limit/assets/LICENSE.cupertino-icons b/extensions/eu-volume-limit/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/eu-volume-limit/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/eu-volume-limit/assets/settings-eu-volume-limit.png b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.png
new file mode 100644
index 0000000..058fcd1
Binary files /dev/null and b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.png differ
diff --git a/extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg
new file mode 100644
index 0000000..767f15f
--- /dev/null
+++ b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/eu-volume-limit/listing.toml b/extensions/eu-volume-limit/listing.toml
new file mode 100644
index 0000000..bdbf2e8
--- /dev/null
+++ b/extensions/eu-volume-limit/listing.toml
@@ -0,0 +1,3 @@
+details = "On an EU iPod, turn the EU Volume Limit switch in Settings > Volume Limit off for the full volume range, no high-volume warning and no automatic lowering. Other iPods are unchanged."
+
+icon = "assets/settings-eu-volume-limit.png"
diff --git a/extensions/eu-volume-limit/main.c b/extensions/eu-volume-limit/main.c
new file mode 100644
index 0000000..0d3cd75
--- /dev/null
+++ b/extensions/eu-volume-limit/main.c
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+#include "rv_api.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+
+static const struct rv_hook hooks[] = {
+ /* Test SysInfo bits 0 and 7 instead of bit 7 alone. */
+ RV_HOOK_WORD(RV_SITE_VolumePolicy_RegionTest_word, 0xe3100081),
+ /* EU Volume Limit off: ceiling 256 instead of 222. */
+ RV_HOOK_WORD(RV_SITE_Volume_EUOffCeiling_word, 0x03a00c01),
+ /* Default user limit and volume: 256 instead of 222. */
+ RV_HOOK_WORD(RV_SITE_Volume_EUDefaultLimit_word, 0xe3a00c01),
+ /* The warning always reads as acknowledged. */
+ RV_HOOK_WORD(RV_SITE_VolumePolicy_WarningPolicyTest_word, 0xe3a00000),
+ /* No startup volume clamp. */
+ RV_HOOK_WORD(RV_SITE_Volume_StartupClampTest_word, 0xe3a00000),
+ /* No 18-hour exposure check on track change and stop. */
+ RV_HOOK_WORD(RV_SITE_VolumeExposure_TrackFinishTest_word, 0xea00000f),
+ /* bx lr: the 20-hour exposure event never lowers the volume. */
+ RV_HOOK_WORD(RV_SITE_MediaPlayer_PostVolumeExposureLimitEvent_word, 0xe12fff1e),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ (void)core;
+ (void)handle;
+ return &extension;
+}
diff --git a/extensions/eu-volume-limit/manifest.toml b/extensions/eu-volume-limit/manifest.toml
new file mode 100644
index 0000000..6bd47ab
--- /dev/null
+++ b/extensions/eu-volume-limit/manifest.toml
@@ -0,0 +1,13 @@
+id = "eu-volume-limit"
+name = "EU Volume Limit"
+description = "Turns off the EU volume cap: 15% more volume with the limit switch off, no high-volume warning and no automatic lowering of the volume."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "media"
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/file-info/Makefile b/extensions/file-info/Makefile
new file mode 100644
index 0000000..71e4704
--- /dev/null
+++ b/extensions/file-info/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c info.c
+include $(SDK)/rv.mk
diff --git a/extensions/file-info/README.md b/extensions/file-info/README.md
new file mode 100644
index 0000000..c4cb315
--- /dev/null
+++ b/extensions/file-info/README.md
@@ -0,0 +1,33 @@
+# File Info
+
+Based on the RepriseOS core's [File Info](https://github.com/RepriseOS/repriseos/blob/acbb928/payload/file_info.c), by lgreitis and paviro.
+
+Adds File Info to the context menu (hold Select) of a song, podcast episode, iTunes U episode, audiobook, movie, TV episode or video playlist entry, and to the Now Playing context menu. Other extensions can open it for a record through its service. The screen lists the item's tags and file properties.
+
+| Media kind | Rows |
+|---|---|
+| Song | Title, Artist, Album Artist, Album, Year, Genre, Composer, Grouping, Comment, Duration, Track, Disc, Kind, Sample Rate, Bitrate, File Size, Volume Adjustment, Rating, Play Count, Last Played, Skip Count, Last Skipped, Date Added, Date Modified |
+| Podcast episode | Title, Podcast, Artist, Category, Genre, Description, Release Date, Duration, Chapters, Kind, Sample Rate, Bitrate, File Size, Volume Adjustment, Play Count, Last Played, Date Added |
+| iTunes U episode | as a podcast episode, with Album in place of Podcast |
+| Audiobook | Title, Author, Book, Genre, Description, Duration, Chapters, Kind, Sample Rate, Bitrate, File Size, Volume Adjustment, Play Count, Last Played, Date Added |
+| Music video | Title, Artist, Album Artist, Album, Year, Genre, Comment, Duration, Kind, Bitrate, File Size, Volume Adjustment, Rating, Play Count, Last Played, Date Added |
+| Movie, TV episode, rental | Title, Show, Year, Genre, Description, Release Date, Duration, Kind, Bitrate, File Size, Volume Adjustment, Rating, Play Count, Last Played, Date Added |
+
+Rows without a value are left out. Album Artist comes from the Album Artists extension while it runs, and only when it differs from the Artist.
+
+| Row | Format |
+|---|---|
+| Kind | iTunes's file kind, such as "AAC audio file" |
+| Track, Disc | "3 of 12" when the total is known |
+| dates | local time, "2024-03-05 14:07" |
+| Volume Adjustment | the Sound Check offset as a percentage |
+| Rating | stars out of five, or Unrated |
+| File Size | MiB with one decimal |
+
+Values are read from Apple's library when the screen opens, and go blank if the library reloads.
+
+| | |
+|---|---|
+| Default | on |
+| Memory | image only, plus about 130 bytes for the row table and the item it shows |
+| Settings | none |
diff --git a/extensions/file-info/assets/LICENSE.cupertino-icons b/extensions/file-info/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/file-info/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/file-info/assets/settings-file-info.png b/extensions/file-info/assets/settings-file-info.png
new file mode 100644
index 0000000..eef5690
Binary files /dev/null and b/extensions/file-info/assets/settings-file-info.png differ
diff --git a/extensions/file-info/assets/settings-file-info.svg b/extensions/file-info/assets/settings-file-info.svg
new file mode 100644
index 0000000..afa249f
--- /dev/null
+++ b/extensions/file-info/assets/settings-file-info.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/file-info/info.c b/extensions/file-info/info.c
new file mode 100644
index 0000000..8cd39fe
--- /dev/null
+++ b/extensions/file-info/info.c
@@ -0,0 +1,390 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The rows of File Info: which fields a media kind shows, in which order, and
+ * each value formatted from the MediaItem's getters and its iTunesDB record.
+ *
+ * Based on RepriseOS payload/file_info.c (acbb928) by lgreitis and paviro. */
+
+#include "info.h"
+#include "../album-artists/service.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_libc.h"
+#include "rv_media.h"
+
+enum field {
+ TITLE,
+ ARTIST,
+ AUTHOR,
+ ALBUM,
+ PODCAST,
+ BOOK,
+ SHOW,
+ YEAR,
+ GENRE,
+ CATEGORY,
+ COMPOSER,
+ GROUPING,
+ COMMENT,
+ DESCRIPTION,
+ RELEASE_DATE,
+ DURATION,
+ CHAPTERS,
+ TRACK,
+ DISC,
+ KIND,
+ SAMPLE_RATE,
+ BITRATE,
+ FILE_SIZE,
+ VOLUME,
+ RATING,
+ PLAY_COUNT,
+ LAST_PLAYED,
+ SKIP_COUNT,
+ LAST_SKIPPED,
+ DATE_ADDED,
+ DATE_MODIFIED,
+ ALBUM_ARTIST, /* from the Album Artists extension while it runs */
+ FIELDS
+};
+
+/* Labels in field order, each found by its offset into one string. */
+static const char labels[] =
+ "Title\0Artist\0Author\0Album\0Podcast\0Book\0Show\0Year\0Genre\0Category\0"
+ "Composer\0Grouping\0Comment\0Description\0Release Date\0Duration\0Chapters\0"
+ "Track\0Disc\0Kind\0Sample Rate\0Bitrate\0File Size\0Volume Adjustment\0"
+ "Rating\0Play Count\0Last Played\0Skip Count\0Last Skipped\0Date Added\0"
+ "Date Modified\0Album Artist";
+static const uint16_t label_offsets[FIELDS] = {
+ 0, 6, 13, 20, 26, 34, 39, 44, 49, 55, 64, 73, 82, 90, 102, 115,
+ 124, 133, 139, 144, 149, 161, 169, 179, 197, 204, 215, 227, 238, 251, 262, 276,
+};
+_Static_assert(sizeof labels == 276 + sizeof "Album Artist", "label offsets drifted");
+
+/* Rows per media kind, in display order. Fields without a value are left out. */
+static const uint8_t song_rows[] = {
+ TITLE, ARTIST, ALBUM_ARTIST, ALBUM, YEAR,
+ GENRE, COMPOSER, GROUPING, COMMENT, DURATION,
+ TRACK, DISC, KIND, SAMPLE_RATE, BITRATE,
+ FILE_SIZE, VOLUME, RATING, PLAY_COUNT, LAST_PLAYED,
+ SKIP_COUNT, LAST_SKIPPED, DATE_ADDED, DATE_MODIFIED, FIELDS,
+};
+static const uint8_t podcast_rows[] = {
+ TITLE, PODCAST, ARTIST, CATEGORY, GENRE, DESCRIPTION,
+ RELEASE_DATE, DURATION, CHAPTERS, KIND, SAMPLE_RATE, BITRATE,
+ FILE_SIZE, VOLUME, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS,
+};
+static const uint8_t lecture_rows[] = {
+ TITLE, ALBUM, ARTIST, CATEGORY, GENRE, DESCRIPTION,
+ RELEASE_DATE, DURATION, CHAPTERS, KIND, SAMPLE_RATE, BITRATE,
+ FILE_SIZE, VOLUME, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS,
+};
+static const uint8_t audiobook_rows[] = {
+ TITLE, AUTHOR, BOOK, GENRE, DESCRIPTION, DURATION,
+ CHAPTERS, KIND, SAMPLE_RATE, BITRATE, FILE_SIZE, VOLUME,
+ PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS,
+};
+static const uint8_t music_video_rows[] = {
+ TITLE, ARTIST, ALBUM_ARTIST, ALBUM, YEAR, GENRE,
+ COMMENT, DURATION, KIND, BITRATE, FILE_SIZE, VOLUME,
+ RATING, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS,
+};
+static const uint8_t video_rows[] = {
+ TITLE, SHOW, YEAR, GENRE, DESCRIPTION, RELEASE_DATE, DURATION, KIND,
+ BITRATE, FILE_SIZE, VOLUME, RATING, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS,
+};
+
+/* The item the rows were worked out for, the native string the last text
+ * value lives in, and the formatted number of the last other value. */
+static struct {
+ uint32_t item[MediaItem_bytes / 4];
+ uint32_t text[NativeString_bytes / 4];
+ uint8_t text_live;
+ uint8_t unknown; /* the requested field has no value */
+ uint8_t rows[FIELDS];
+ uint8_t count;
+ char value[24]; /* the longest is "4294967295 kbps" */
+} info;
+
+static const struct rv_api *api;
+
+static const uint8_t *record(const void *item)
+{
+ return RV_FIELD(item, MediaItem_record, const uint8_t *);
+}
+
+static void release_text(void)
+{
+ if (info.text_live)
+ NativeString_Destroy((struct NativeString *)info.text);
+ info.text_live = 0;
+}
+
+static void number(uint32_t value, const char *unit)
+{
+ if (!value) {
+ info.unknown = 1;
+ return;
+ }
+ rv_format(info.value, sizeof info.value, "%lu%s", (unsigned long)value, unit);
+}
+
+static const char *text(const void *item, enum field field)
+{
+ static const uint16_t slots[FIELDS] = {
+ [TITLE] = MediaItem_title_method,
+ [ARTIST] = MediaItem_artist_method,
+ [AUTHOR] = MediaItem_artist_method,
+ [ALBUM] = MediaItem_album_method,
+ [PODCAST] = MediaItem_album_method,
+ [BOOK] = MediaItem_album_method,
+ [SHOW] = MediaItem_show_name_method,
+ [GENRE] = MediaItem_genre_method,
+ [CATEGORY] = MediaItem_category_method,
+ [COMPOSER] = MediaItem_composer_method,
+ [GROUPING] = MediaItem_grouping_method,
+ [COMMENT] = MediaItem_comment_method,
+ [DESCRIPTION] = MediaItem_description_method,
+ [KIND] = MediaItem_file_type_method,
+ };
+ release_text();
+ const char *data =
+ rv_item_text(item, slots[field], (struct NativeString *)info.text);
+ info.text_live = 1;
+ if (data)
+ return data;
+ info.unknown = 1;
+ return "";
+}
+
+/* The Album Artist from the Album Artists extension, which has one only when
+ * it differs from the Artist. */
+static const char *album_artist(const void *item)
+{
+ const struct album_artists_service *albums =
+ api->extension_service(ALBUM_ARTISTS_ID);
+ uint16_t units[256];
+ uint32_t count = albums ? albums->read(record(item), units, 255) : 0;
+ release_text();
+ if (!count) {
+ info.unknown = 1;
+ return "";
+ }
+ struct NativeString *string = (struct NativeString *)info.text;
+ NativeString_InitEmpty(string);
+ NativeString_AssignUtf16(string, units, (int)count);
+ info.text_live = 1;
+ const char *data = NativeString_GetUtf8(string);
+ return data ? data : "";
+}
+
+static void ordinal(uint32_t value, uint32_t total)
+{
+ number(value, "");
+ if (value && total >= value)
+ rv_format(info.value, sizeof info.value, "%lu of %lu", (unsigned long)value,
+ (unsigned long)total);
+}
+
+/* A local date and time from one of the DateTime getters: "2024-03-05 14:07".
+ * The record's own word is checked first, since a getter turns an unset
+ * date into 1904. Release dates have no word; their getter says whether
+ * the record has one. */
+static void date(const void *item, uint32_t slot, int present)
+{
+ typedef int (*getter)(void *, const void *);
+ typedef int (*release_getter)(const void *, void *);
+ uint16_t when[DateTime_bytes / 2];
+ const uint8_t *w = (const uint8_t *)when;
+ if (present && slot == MediaItem_release_date_method)
+ present = RV_FIELD(RV_FIELD(item, 0, void *), slot, release_getter)(item, when);
+ else if (present)
+ RV_FIELD(RV_FIELD(item, 0, void *), slot, getter)(when, item);
+ if (!present) {
+ info.unknown = 1;
+ return;
+ }
+ rv_format(info.value, sizeof info.value, "%u-%02u-%02u %02u:%02u",
+ RV_FIELD(w, DateTime_year, uint16_t), w[DateTime_month], w[DateTime_day],
+ w[DateTime_hour], w[DateTime_minute]);
+}
+
+/* Sound Check's per-track adjustment, -255..255 for -100%..+100%. */
+static void volume(int32_t adjustment)
+{
+ if (!adjustment) {
+ info.unknown = 1;
+ return;
+ }
+ rv_format(info.value, sizeof info.value, "%s%d%%", adjustment > 0 ? "+" : "",
+ (int)(adjustment * 100 / 255));
+}
+
+/* The record keeps the sample rate as an IEEE single. */
+static void sample_rate(uint32_t bits)
+{
+ uint32_t exponent = bits >> 23 & 0xff, hertz = 0;
+ if (!(bits >> 31) && exponent >= 127 && exponent < 150)
+ hertz = ((bits & 0x7fffff) | 0x800000) >> (150 - exponent);
+ if (!hertz) {
+ info.unknown = 1;
+ return;
+ }
+ if (hertz % 1000 >= 100)
+ rv_format(info.value, sizeof info.value, "%lu.%lu kHz",
+ (unsigned long)(hertz / 1000), (unsigned long)(hertz % 1000 / 100));
+ else
+ rv_format(info.value, sizeof info.value, "%lu kHz",
+ (unsigned long)(hertz / 1000));
+}
+
+static const char *value(const void *item, enum field field)
+{
+ const uint8_t *r = record(item);
+ switch (field) {
+ case YEAR:
+ number(rv_item_value(item, MediaItem_year_method) & 0xffff, "");
+ break;
+ case DURATION: {
+ uint32_t ms = rv_item_value(item, MediaItem_duration_method);
+ if (ms)
+ rv_format_duration(info.value, sizeof info.value, ms / 1000);
+ else
+ info.unknown = 1;
+ break;
+ }
+ case CHAPTERS:
+ number(rv_item_value(item, MediaItem_chapter_count_method), "");
+ break;
+ /* The record keeps the track and disc totals beside the ordinals. */
+ case TRACK:
+ ordinal(rv_item_value(item, MediaItem_track_number_method) & 0xffff,
+ RV_FIELD(r, MediaRecord_track_total, uint16_t));
+ break;
+ case DISC:
+ ordinal(rv_item_value(item, MediaItem_disc_number_method) & 0xffff,
+ RV_FIELD(r, MediaRecord_disc_total, uint16_t));
+ break;
+ case SAMPLE_RATE:
+ sample_rate(RV_FIELD(r, MediaRecord_sample_rate, uint32_t));
+ break;
+ case BITRATE:
+ number(rv_item_value(item, MediaItem_bitrate_method) & 0xffff, " kbps");
+ break;
+ case FILE_SIZE: {
+ uint32_t bytes = rv_item_value(item, MediaItem_file_size_method);
+ if (bytes)
+ rv_format(info.value, sizeof info.value, "%lu.%lu MiB",
+ (unsigned long)(bytes >> 20),
+ (unsigned long)((bytes & 0xfffff) * 10 >> 20));
+ else
+ info.unknown = 1;
+ break;
+ }
+ case RATING: {
+ int32_t rating = (int32_t)rv_item_value(item, MediaItem_rating_method);
+ if (rating > 0 && rating <= 100)
+ rv_format(info.value, sizeof info.value, "%d/5", (int)(rating / 20));
+ else
+ rv_format(info.value, sizeof info.value, "Unrated");
+ break;
+ }
+ case VOLUME:
+ volume(RV_FIELD(r, MediaRecord_volume, int16_t));
+ break;
+ case RELEASE_DATE:
+ date(item, MediaItem_release_date_method, 1);
+ break;
+ case LAST_PLAYED:
+ date(item, MediaItem_last_played_method,
+ RV_FIELD(r, MediaRecord_last_played, uint32_t) != 0);
+ break;
+ case LAST_SKIPPED:
+ date(item, MediaItem_last_skipped_method,
+ RV_FIELD(r, MediaRecord_last_skipped, uint32_t) != 0);
+ break;
+ case DATE_ADDED:
+ date(item, MediaItem_date_added_method,
+ RV_FIELD(r, MediaRecord_date_added, uint32_t) != 0);
+ break;
+ case DATE_MODIFIED:
+ date(item, MediaItem_date_modified_method,
+ RV_FIELD(r, MediaRecord_date_modified, uint32_t) != 0);
+ break;
+ case PLAY_COUNT:
+ rv_format(info.value, sizeof info.value, "%lu",
+ (unsigned long)rv_item_value(item, MediaItem_play_count_method));
+ break;
+ case SKIP_COUNT:
+ rv_format(info.value, sizeof info.value, "%lu",
+ (unsigned long)rv_item_value(item, MediaItem_skip_count_method));
+ break;
+ case ALBUM_ARTIST:
+ return album_artist(item);
+ default:
+ return text(item, field);
+ }
+ return info.value;
+}
+
+static const uint8_t *rows_for(uint32_t kind)
+{
+ if (kind & MediaKind_Audiobook)
+ return audiobook_rows;
+ if (kind & MediaKind_Podcast)
+ return podcast_rows;
+ if (kind & MediaKind_ITunesU)
+ return lecture_rows;
+ if (kind & MediaKind_MusicVideo)
+ return music_video_rows;
+ if (kind & (MediaKind_Movie | MediaKind_TVShow | MediaKind_Rental))
+ return video_rows;
+ return song_rows;
+}
+
+uint32_t info_rows(const void *item)
+{
+ if (!item)
+ return 0;
+ if (!memcmp(item, info.item, MediaItem_bytes))
+ return info.count;
+ memcpy(info.item, item, MediaItem_bytes);
+ info.count = 0;
+ if (!rv_item_valid(item))
+ return 0;
+ uint32_t kind = RV_FIELD(record(item), MediaRecord_media_kind, uint32_t);
+ for (const uint8_t *row = rows_for(kind); *row != FIELDS; row++) {
+ info.unknown = 0;
+ value(item, (enum field) * row);
+ if (!info.unknown)
+ info.rows[info.count++] = *row;
+ }
+ release_text();
+ return info.count;
+}
+
+const char *info_row(const void *item, uint32_t index, const char **out)
+{
+ if (info_rows(item) <= index) {
+ *out = NULL;
+ return "";
+ }
+ enum field field = (enum field)info.rows[index];
+ info.unknown = 0;
+ info.value[0] = 0;
+ /* The list can outlive the item when the library reloads. */
+ *out = rv_item_valid(item) ? value(item, field) : info.value;
+ return labels + label_offsets[field];
+}
+
+void info_init(const struct rv_api *core)
+{
+ api = core;
+}
+
+void info_release(void)
+{
+ release_text();
+ memset(info.item, 0, sizeof info.item);
+ info.count = 0;
+}
diff --git a/extensions/file-info/info.h b/extensions/file-info/info.h
new file mode 100644
index 0000000..3aa080f
--- /dev/null
+++ b/extensions/file-info/info.h
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+#ifndef INFO_H
+#define INFO_H
+#include
+
+/* The rows of File Info for `item` (a MediaItem of the symbols header): how
+ * many have a value, and the label and value of row `index`. The rows are
+ * worked out when `item` changes and kept until info_release. */
+uint32_t info_rows(const void *item);
+const char *info_row(const void *item, uint32_t index, const char **value);
+void info_release(void);
+/* The core table, for the Album Artists service. */
+struct rv_api;
+void info_init(const struct rv_api *api);
+
+#endif
diff --git a/extensions/file-info/listing.toml b/extensions/file-info/listing.toml
new file mode 100644
index 0000000..4802c53
--- /dev/null
+++ b/extensions/file-info/listing.toml
@@ -0,0 +1,11 @@
+details = "Hold Select on a song, podcast or iTunes U episode, audiobook, movie, TV episode or video playlist entry, or in Now Playing, then choose File Info to see its tags and file properties."
+
+icon = "assets/settings-file-info.png"
+
+[[screenshots]]
+file = "screenshots/context-menu.png"
+alt = "A song's context menu with File Info above Play Next and Play Last."
+
+[[screenshots]]
+file = "screenshots/song.png"
+alt = "File Info for a compilation track: Title, Artist, Album Artist, Album and Year."
diff --git a/extensions/file-info/main.c b/extensions/file-info/main.c
new file mode 100644
index 0000000..6e7ae94
--- /dev/null
+++ b/extensions/file-info/main.c
@@ -0,0 +1,122 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* File Info in the context menus of songs, podcast and iTunes U episodes,
+ * audiobooks, movies, TV episodes, video playlists and Now Playing: the item's
+ * tags and file properties as a list of label and value rows.
+ *
+ * Based on RepriseOS payload/file_info.c (acbb928) by lgreitis and paviro. */
+
+#include "info.h"
+#include "service.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_ui.h"
+#include
+
+static const struct rv_api *api;
+static rv_extension_handle self;
+
+/* The item File Info shows when another extension opened it, held until the
+ * screen closes. */
+static uint32_t opened[MediaItem_bytes / 4];
+static int holding;
+
+/* The menu's item, or the one the service opened. */
+static const void *item_of(const struct rv_context *ctx)
+{
+ return ctx->arg ? ctx->arg : ctx->item;
+}
+
+static int has_item(const struct rv_context *ctx)
+{
+ return ctx->item != NULL;
+}
+
+static uint32_t count(const struct rv_context *ctx)
+{
+ return info_rows(item_of(ctx));
+}
+
+static const char *row(const struct rv_context *ctx, uint32_t index,
+ const char **detail)
+{
+ return info_row(item_of(ctx), index, detail);
+}
+
+static uint32_t first(const struct rv_context *ctx)
+{
+ (void)ctx;
+ return 0;
+}
+
+static void release(void)
+{
+ if (holding)
+ MediaItem_Destroy((struct MediaItem *)opened);
+ holding = 0;
+}
+
+static void closed(const struct rv_context *ctx)
+{
+ (void)ctx;
+ info_release();
+ release();
+}
+
+/* closed is not called when the extension unloads under the screen. */
+static void unload(void)
+{
+ info_release();
+ release();
+}
+
+static int open(void *record)
+{
+ release();
+ info_release();
+ MediaItem_InitFromRecord((struct MediaItem *)opened, record, 0);
+ holding = 1;
+ int status = api->ui_push(self, "info", opened);
+ if (status != RV_OK)
+ release();
+ return status;
+}
+
+static const struct file_info_service service = {open};
+
+static const struct rv_screen screens[] = {
+ RV_SCREEN_DYNAMIC_LIST("info", "File Info", count, row, .layout = RV_LAYOUT_FULL,
+ .dynamic.detail = RV_DETAIL_BELOW, .dynamic.initial = first,
+ .closed = closed),
+};
+
+/* Every context menu that hands over an item. */
+#define ITEM_MENUS \
+ (RV_MENU_BIT(RV_MENU_SONG_CONTEXT) | RV_MENU_BIT(RV_MENU_NOW_PLAYING_CONTEXT) | \
+ RV_MENU_BIT(RV_MENU_PODCAST_EPISODE_CONTEXT) | \
+ RV_MENU_BIT(RV_MENU_ITUNES_U_EPISODE_CONTEXT) | \
+ RV_MENU_BIT(RV_MENU_AUDIOBOOK_CONTEXT) | RV_MENU_BIT(RV_MENU_MOVIE_CONTEXT) | \
+ RV_MENU_BIT(RV_MENU_TV_EPISODE_CONTEXT) | \
+ RV_MENU_BIT(RV_MENU_VIDEO_PLAYLIST_CONTEXT))
+
+static const struct rv_menu_entry entries[] = {
+ RV_MENUS_ENTRY(ITEM_MENUS, 0, RV_ROW_PUSH("File Info", "info"),
+ .available = has_item),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_SCREENS(screens),
+ RV_ENTRIES(entries),
+ .unload = unload,
+ .service = &service,
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *table,
+ rv_extension_handle handle)
+{
+ api = table;
+ self = handle;
+ info_init(api);
+ return &extension;
+}
diff --git a/extensions/file-info/manifest.toml b/extensions/file-info/manifest.toml
new file mode 100644
index 0000000..b4adea0
--- /dev/null
+++ b/extensions/file-info/manifest.toml
@@ -0,0 +1,13 @@
+id = "file-info"
+name = "File Info"
+description = "Show a song, episode, audiobook or video's tags and file properties from its context menu."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "media"
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/file-info/screenshots/context-menu.png b/extensions/file-info/screenshots/context-menu.png
new file mode 100644
index 0000000..006318c
Binary files /dev/null and b/extensions/file-info/screenshots/context-menu.png differ
diff --git a/extensions/file-info/screenshots/song.png b/extensions/file-info/screenshots/song.png
new file mode 100644
index 0000000..75ddfac
Binary files /dev/null and b/extensions/file-info/screenshots/song.png differ
diff --git a/extensions/file-info/service.h b/extensions/file-info/service.h
new file mode 100644
index 0000000..e5e2872
--- /dev/null
+++ b/extensions/file-info/service.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* What File Info offers other extensions through api->extension_service. */
+
+#ifndef FILE_INFO_SERVICE_H
+#define FILE_INFO_SERVICE_H
+
+#define FILE_INFO_ID "file-info"
+
+struct file_info_service {
+ /* Opens File Info above the top screen for `record` (a media record of
+ * the symbols header); RV_OK or the ui_push error. UI task. */
+ int (*open)(void *record);
+};
+
+#endif
diff --git a/extensions/file-info/tests/contracts.c b/extensions/file-info/tests/contracts.c
new file mode 100644
index 0000000..f0bea5d
--- /dev/null
+++ b/extensions/file-info/tests/contracts.c
@@ -0,0 +1,489 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include
+#include
+#include
+#include
+#include "../info.c"
+
+/* The host formats; the device's rv_libc does the same for these conversions. */
+uint32_t rv_format(char *out, uint32_t capacity, const char *format, ...)
+{
+ va_list args;
+ va_start(args, format);
+ int n = vsnprintf(out, capacity, format, args);
+ va_end(args);
+ return (uint32_t)n;
+}
+
+uint32_t rv_format_duration(char *out, uint32_t capacity, uint32_t seconds)
+{
+ uint32_t minutes = seconds / 60;
+ if (minutes < 60)
+ return rv_format(out, capacity, "%u:%02u", minutes, seconds % 60);
+ return rv_format(out, capacity, "%u:%02u:%02u", minutes / 60, minutes % 60,
+ seconds % 60);
+}
+
+/* A native string holds one pointer; init, destroy and read are counted. */
+static int strings_live;
+
+struct NativeString *NativeString_InitEmpty(struct NativeString *s)
+{
+ RV_FIELD(s, 0, const char *) = "";
+ strings_live++;
+ return s;
+}
+
+struct NativeString *NativeString_Destroy(struct NativeString *s)
+{
+ assert(strings_live > 0);
+ strings_live--;
+ RV_FIELD(s, 0, const char *) = NULL;
+ return s;
+}
+
+char *NativeString_GetUtf8(struct NativeString *s)
+{
+ return (char *)RV_FIELD(s, 0, const char *);
+}
+
+/* The native string takes UTF-16 as the Album Artists service hands it over. */
+static char assigned[256];
+
+void NativeString_AssignUtf16(struct NativeString *s, const uint16_t *text,
+ int characters)
+{
+ for (int i = 0; i < characters; i++)
+ assigned[i] = (char)text[i];
+ assigned[characters] = 0;
+ RV_FIELD(s, 0, const char *) = assigned;
+}
+
+/* The Album Artists service: present with a text, present without one, or absent. */
+static const char *album_artist_text;
+static int album_artists_present;
+
+static uint32_t read_album_artist(const void *record, uint16_t *text,
+ uint32_t max_units)
+{
+ (void)record;
+ if (!album_artist_text)
+ return 0;
+ uint32_t n = 0;
+ for (; album_artist_text[n] && n < max_units; n++)
+ text[n] = (uint16_t)album_artist_text[n];
+ return n;
+}
+static const struct album_artists_service album_artists = {read_album_artist};
+
+static const void *extension_service(const char *id)
+{
+ assert(!strcmp(id, ALBUM_ARTISTS_ID));
+ return album_artists_present ? &album_artists : NULL;
+}
+static const struct rv_api fake_api = {.extension_service = extension_service};
+
+static int item_valid = 1;
+
+int MediaItem_IsValid(struct MediaItem *i)
+{
+ (void)i;
+ return item_valid;
+}
+
+/* The item under test: a vtable of getters over these values and a record. */
+static struct {
+ const char *title, *artist, *album, *genre, *composer, *grouping, *kind, *comment,
+ *category, *description, *show;
+ uint32_t year, duration, chapters, track, disc, bitrate, file_size, play_count,
+ skip_count;
+ int32_t rating, release;
+} fake;
+
+static uint8_t track_record[0x100];
+static uintptr_t methods[0x140 / 4];
+static uint8_t item[MediaItem_bytes];
+
+#define TEXT_GETTER(name, field) \
+ static void name(const void *i, void *s) \
+ { \
+ assert(i == item); \
+ RV_FIELD(s, 0, const char *) = fake.field; \
+ }
+TEXT_GETTER(get_title, title)
+TEXT_GETTER(get_artist, artist)
+TEXT_GETTER(get_album, album)
+TEXT_GETTER(get_genre, genre)
+TEXT_GETTER(get_composer, composer)
+TEXT_GETTER(get_grouping, grouping)
+TEXT_GETTER(get_kind, kind)
+TEXT_GETTER(get_comment, comment)
+TEXT_GETTER(get_category, category)
+TEXT_GETTER(get_description, description)
+TEXT_GETTER(get_show, show)
+#define VALUE_GETTER(name, field) \
+ static uint32_t name(const void *i) \
+ { \
+ assert(i == item); \
+ return (uint32_t)fake.field; \
+ }
+VALUE_GETTER(get_year, year)
+VALUE_GETTER(get_duration, duration)
+VALUE_GETTER(get_chapters, chapters)
+VALUE_GETTER(get_track, track)
+VALUE_GETTER(get_disc, disc)
+VALUE_GETTER(get_bitrate, bitrate)
+VALUE_GETTER(get_file_size, file_size)
+VALUE_GETTER(get_play_count, play_count)
+VALUE_GETTER(get_skip_count, skip_count)
+VALUE_GETTER(get_rating, rating)
+
+/* The date getters fill a DateTime; each has its own fixed moment. */
+static void fill_date(void *out, unsigned year, unsigned month, unsigned day,
+ unsigned hour, unsigned minute)
+{
+ uint8_t *w = out;
+ memset(w, 0, DateTime_bytes);
+ RV_FIELD(w, DateTime_year, uint16_t) = (uint16_t)year;
+ w[DateTime_month] = (uint8_t)month;
+ w[DateTime_day] = (uint8_t)day;
+ w[DateTime_hour] = (uint8_t)hour;
+ w[DateTime_minute] = (uint8_t)minute;
+}
+
+#define DATE_GETTER(name, y, mo, d, h, mi) \
+ static int name(void *out, const void *i) \
+ { \
+ assert(i == item); \
+ fill_date(out, y, mo, d, h, mi); \
+ return 0; \
+ }
+DATE_GETTER(get_added, 2024, 3, 5, 14, 7)
+DATE_GETTER(get_modified, 2024, 4, 6, 9, 30)
+DATE_GETTER(get_played, 2025, 1, 2, 23, 59)
+DATE_GETTER(get_skipped, 2025, 2, 3, 0, 1)
+
+static int get_release(const void *i, void *out)
+{
+ assert(i == item);
+ if (fake.release)
+ fill_date(out, 2019, 12, 24, 18, 0);
+ return fake.release;
+}
+
+static void set(uint32_t slot, void *fn)
+{
+ methods[slot / sizeof(void *)] = (uintptr_t)fn;
+}
+
+static void reset(uint32_t kind, float sample_rate, uint16_t tracks, uint16_t discs)
+{
+ info_release();
+ memset(&fake, 0, sizeof fake);
+ fake.title = "Song A";
+ fake.artist = "Artist A";
+ fake.album = "Album A";
+ fake.genre = "Rock";
+ fake.composer = "Composer A";
+ fake.grouping = "Set 1";
+ fake.kind = "AAC audio file";
+ fake.comment = "A note";
+ fake.category = "Technology";
+ fake.description = "About the episode";
+ fake.show = "The Show";
+ fake.release = 1;
+ fake.year = 1999;
+ fake.duration = 3723000;
+ fake.chapters = 5;
+ fake.track = 3;
+ fake.disc = 1;
+ fake.bitrate = 256;
+ fake.file_size = 5767168;
+ fake.rating = 80;
+ fake.play_count = 0;
+ fake.skip_count = 2;
+ memset(track_record, 0, sizeof track_record);
+ RV_FIELD(track_record, MediaRecord_media_kind, uint32_t) = kind;
+ memcpy(track_record + MediaRecord_sample_rate, &sample_rate, 4);
+ RV_FIELD(track_record, MediaRecord_track_total, uint16_t) = tracks;
+ RV_FIELD(track_record, MediaRecord_disc_total, uint16_t) = discs;
+ RV_FIELD(track_record, MediaRecord_volume, int16_t) = -51;
+ RV_FIELD(track_record, MediaRecord_date_added, uint32_t) = 1;
+ RV_FIELD(track_record, MediaRecord_date_modified, uint32_t) = 1;
+ RV_FIELD(track_record, MediaRecord_last_played, uint32_t) = 1;
+ RV_FIELD(track_record, MediaRecord_last_skipped, uint32_t) = 1;
+ memset(item, 0, sizeof item);
+ RV_FIELD(item, 0, void *) = methods;
+ RV_FIELD(item, MediaItem_record, void *) = track_record;
+ RV_FIELD(item, MediaItem_generation, uint32_t)++;
+ item_valid = 1;
+}
+
+/* The label and value of row `index`. */
+static const char *label_of(uint32_t index, const char **value)
+{
+ return info_row(item, index, value);
+}
+
+static void expect(uint32_t index, const char *label, const char *value)
+{
+ const char *got;
+ const char *l = label_of(index, &got);
+ if (strcmp(l, label) || strcmp(got, value))
+ fprintf(stderr, "row %u: got %s = %s, want %s = %s\n", index, l, got, label,
+ value);
+ assert(!strcmp(l, label) && !strcmp(got, value));
+}
+
+static void expect_labels(const char *const *labels, uint32_t count)
+{
+ assert(info_rows(item) == count);
+ for (uint32_t i = 0; i < count; i++) {
+ const char *value;
+ assert(!strcmp(label_of(i, &value), labels[i]));
+ assert(value && *value);
+ }
+}
+
+int main(void)
+{
+ info_init(&fake_api);
+ set(MediaItem_title_method, get_title);
+ set(MediaItem_artist_method, get_artist);
+ set(MediaItem_album_method, get_album);
+ set(MediaItem_genre_method, get_genre);
+ set(MediaItem_composer_method, get_composer);
+ set(MediaItem_grouping_method, get_grouping);
+ set(MediaItem_file_type_method, get_kind);
+ set(MediaItem_comment_method, get_comment);
+ set(MediaItem_category_method, get_category);
+ set(MediaItem_description_method, get_description);
+ set(MediaItem_show_name_method, get_show);
+ set(MediaItem_date_added_method, get_added);
+ set(MediaItem_date_modified_method, get_modified);
+ set(MediaItem_last_played_method, get_played);
+ set(MediaItem_last_skipped_method, get_skipped);
+ set(MediaItem_release_date_method, get_release);
+ set(MediaItem_year_method, get_year);
+ set(MediaItem_duration_method, get_duration);
+ set(MediaItem_chapter_count_method, get_chapters);
+ set(MediaItem_track_number_method, get_track);
+ set(MediaItem_disc_number_method, get_disc);
+ set(MediaItem_bitrate_method, get_bitrate);
+ set(MediaItem_file_size_method, get_file_size);
+ set(MediaItem_play_count_method, get_play_count);
+ set(MediaItem_skip_count_method, get_skip_count);
+ set(MediaItem_rating_method, get_rating);
+
+ /* A song with every field. */
+ reset(0, 44100.0f, 12, 0);
+ assert(info_rows(item) == 23);
+ expect(0, "Title", "Song A");
+ expect(1, "Artist", "Artist A");
+ expect(2, "Album", "Album A");
+ expect(3, "Year", "1999");
+ expect(4, "Genre", "Rock");
+ expect(5, "Composer", "Composer A");
+ expect(6, "Grouping", "Set 1");
+ expect(7, "Comment", "A note");
+ expect(8, "Duration", "1:02:03");
+ expect(9, "Track", "3 of 12");
+ expect(10, "Disc", "1");
+ expect(11, "Kind", "AAC audio file");
+ expect(12, "Sample Rate", "44.1 kHz");
+ expect(13, "Bitrate", "256 kbps");
+ expect(14, "File Size", "5.5 MiB");
+ expect(15, "Volume Adjustment", "-20%");
+ expect(16, "Rating", "4/5");
+ expect(17, "Play Count", "0");
+ expect(18, "Last Played", "2025-01-02 23:59");
+ expect(19, "Skip Count", "2");
+ expect(20, "Last Skipped", "2025-02-03 00:01");
+ expect(21, "Date Added", "2024-03-05 14:07");
+ expect(22, "Date Modified", "2024-04-06 09:30");
+ /* The rows are kept for the same item; the last text value's string stays
+ * until the next text value, a new item or release. */
+ assert(info_rows(item) == 23 && strings_live == 1);
+ expect(0, "Title", "Song A");
+ assert(strings_live == 1);
+ info_release();
+ assert(strings_live == 0);
+
+ /* Fields without a value are left out; a disc total below the ordinal is
+ * ignored; an unset date word skips its getter. */
+ reset(0, 48000.0f, 0, 1);
+ fake.year = 0;
+ fake.composer = "";
+ fake.grouping = NULL;
+ fake.comment = "";
+ fake.kind = "";
+ fake.disc = 2;
+ fake.rating = 0;
+ RV_FIELD(track_record, MediaRecord_volume, int16_t) = 0;
+ RV_FIELD(track_record, MediaRecord_last_played, uint32_t) = 0;
+ RV_FIELD(track_record, MediaRecord_last_skipped, uint32_t) = 0;
+ RV_FIELD(track_record, MediaRecord_date_modified, uint32_t) = 0;
+ static const char *const song_short[] = {
+ "Title", "Artist", "Album", "Genre", "Duration",
+ "Track", "Disc", "Sample Rate", "Bitrate", "File Size",
+ "Rating", "Play Count", "Skip Count", "Date Added",
+ };
+ expect_labels(song_short, 14);
+ expect(5, "Track", "3");
+ expect(6, "Disc", "2");
+ expect(7, "Sample Rate", "48 kHz");
+ expect(10, "Rating", "Unrated");
+
+ /* Short durations, odd sample rates, large files, full ratings, loud tracks. */
+ reset(0, 22050.0f, 0, 0);
+ fake.duration = 187000;
+ fake.rating = 100;
+ fake.file_size = 1048576 * 1000 + 943718;
+ RV_FIELD(track_record, MediaRecord_volume, int16_t) = 255;
+ expect(8, "Duration", "3:07");
+ expect(10, "Disc", "1");
+ expect(12, "Sample Rate", "22 kHz");
+ expect(14, "File Size", "1000.8 MiB");
+ expect(15, "Volume Adjustment", "+100%");
+ expect(16, "Rating", "5/5");
+ reset(0, -44100.0f, 0, 0);
+ assert(info_rows(item) == 22); /* a negative rate is no rate */
+
+ /* Each media kind has its own rows; audiobooks relabel artist and album,
+ * videos show their series and release date. */
+ reset(MediaKind_Podcast, 44100.0f, 0, 0);
+ static const char *const podcast[] = {
+ "Title", "Podcast", "Artist", "Category", "Genre",
+ "Description", "Release Date", "Duration", "Chapters", "Kind",
+ "Sample Rate", "Bitrate", "File Size", "Volume Adjustment", "Play Count",
+ "Last Played", "Date Added",
+ };
+ expect_labels(podcast, 17);
+ expect(1, "Podcast", "Album A");
+ expect(6, "Release Date", "2019-12-24 18:00");
+ expect(8, "Chapters", "5");
+ fake.release = 0;
+ RV_FIELD(item, MediaItem_generation, uint32_t)++;
+ assert(info_rows(item) == 16);
+ reset(MediaKind_ITunesU, 44100.0f, 0, 0);
+ static const char *const lecture[] = {
+ "Title", "Album", "Artist", "Category", "Genre",
+ "Description", "Release Date", "Duration", "Chapters", "Kind",
+ "Sample Rate", "Bitrate", "File Size", "Volume Adjustment", "Play Count",
+ "Last Played", "Date Added",
+ };
+ expect_labels(lecture, 17);
+ reset(MediaKind_Audiobook, 44100.0f, 0, 0);
+ static const char *const audiobook[] = {
+ "Title", "Author", "Book", "Genre",
+ "Description", "Duration", "Chapters", "Kind",
+ "Sample Rate", "Bitrate", "File Size", "Volume Adjustment",
+ "Play Count", "Last Played", "Date Added",
+ };
+ expect_labels(audiobook, 15);
+ expect(1, "Author", "Artist A");
+ expect(2, "Book", "Album A");
+ reset(MediaKind_MusicVideo, 44100.0f, 0, 0);
+ static const char *const music_video[] = {
+ "Title",
+ "Artist",
+ "Album",
+ "Year",
+ "Genre",
+ "Comment",
+ "Duration",
+ "Kind",
+ "Bitrate",
+ "File Size",
+ "Volume Adjustment",
+ "Rating",
+ "Play Count",
+ "Last Played",
+ "Date Added",
+ };
+ expect_labels(music_video, 15);
+ static const char *const video[] = {
+ "Title",
+ "Show",
+ "Year",
+ "Genre",
+ "Description",
+ "Release Date",
+ "Duration",
+ "Kind",
+ "Bitrate",
+ "File Size",
+ "Volume Adjustment",
+ "Rating",
+ "Play Count",
+ "Last Played",
+ "Date Added",
+ };
+ reset(MediaKind_Movie, 44100.0f, 0, 0);
+ expect_labels(video, 15);
+ expect(1, "Show", "The Show");
+ reset(MediaKind_TVShow, 44100.0f, 0, 0);
+ expect_labels(video, 15);
+ reset(MediaKind_Rental | MediaKind_Movie, 44100.0f, 0, 0);
+ fake.show = "";
+ assert(info_rows(item) == 14);
+ /* Audiobook wins over the other bits, as the Music menu files it. */
+ reset(MediaKind_Audiobook | MediaKind_Podcast, 44100.0f, 0, 0);
+ expect_labels(audiobook, 15);
+
+ /* An item that is no longer valid keeps its rows with blank values; one
+ * that was never valid has none. */
+ reset(0, 44100.0f, 0, 0);
+ assert(info_rows(item) == 23);
+ item_valid = 0;
+ expect(0, "Title", "");
+ expect(13, "Bitrate", "");
+ assert(strings_live == 0);
+ reset(0, 44100.0f, 0, 0);
+ item_valid = 0;
+ assert(info_rows(item) == 0);
+ assert(info_rows(NULL) == 0);
+ const char *none;
+ assert(!strcmp(info_row(item, 0, &none), "") && none == NULL);
+
+ /* Album Artist shows after Artist while the Album Artists extension runs
+ * and has one for the song; an absent service or an empty answer leaves
+ * the row out. */
+ reset(0, 44100.0f, 0, 0);
+ album_artists_present = 1;
+ album_artist_text = "Various Artists";
+ assert(info_rows(item) == 24);
+ expect(1, "Artist", "Artist A");
+ expect(2, "Album Artist", "Various Artists");
+ expect(3, "Album", "Album A");
+ assert(strings_live == 1);
+ reset(MediaKind_MusicVideo, 44100.0f, 0, 0);
+ assert(info_rows(item) == 16);
+ expect(2, "Album Artist", "Various Artists");
+ reset(MediaKind_Podcast, 44100.0f, 0, 0);
+ assert(info_rows(item) == 17);
+ reset(0, 44100.0f, 0, 0);
+ album_artist_text = NULL;
+ assert(info_rows(item) == 23);
+ album_artists_present = 0;
+ album_artist_text = "Various Artists";
+ reset(0, 44100.0f, 0, 0);
+ assert(info_rows(item) == 23);
+ album_artist_text = NULL;
+ info_release();
+ assert(strings_live == 0);
+
+ /* A different item replaces the rows; release forgets them. */
+ reset(0, 44100.0f, 0, 0);
+ assert(info_rows(item) == 23);
+ RV_FIELD(item, MediaItem_generation, uint32_t)++;
+ fake.year = 0;
+ assert(info_rows(item) == 22);
+ info_release();
+ assert(strings_live == 0);
+ fake.year = 2001;
+ assert(info_rows(item) == 23);
+ info_release();
+ assert(strings_live == 0);
+ return 0;
+}
diff --git a/extensions/file-info/tests/run.py b/extensions/file-info/tests/run.py
new file mode 100644
index 0000000..8469e29
--- /dev/null
+++ b/extensions/file-info/tests/run.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
+"""Run the row and formatting tests with a staged SDK: python3 tests/run.py SDK."""
+
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+root = Path(__file__).resolve().parent
+sdk = Path(sys.argv[1]).resolve()
+with tempfile.TemporaryDirectory(prefix="file-info-tests-") as name:
+ work = Path(name)
+ # Widen the pointer-bearing native layouts for the host; record offsets stay.
+ header = (sdk / "osos-2.0.5.h").read_text()
+
+ def widen(match):
+ key, value = match.groups()
+ if key.startswith(("MediaItem_", "NativeString_")):
+ return f"#define {key} {int(value, 16) * 2:#x}"
+ return match[0]
+
+ (work / "osos-2.0.5.h").write_text(
+ re.sub(r"#define (\w+) (0x[0-9a-f]+)", widen, header)
+ )
+ (work / "rv_api.h").write_text((sdk / "rv_api.h").read_text())
+ (work / "rv_libc.h").write_text((sdk / "rv_libc.h").read_text())
+ (work / "rv_media.h").write_text((sdk / "rv_media.h").read_text())
+ executable = work / "contracts"
+ subprocess.run(
+ [
+ "cc",
+ "-std=c11",
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-g",
+ "-fsanitize=address,undefined",
+ "-I",
+ str(work),
+ str(root / "contracts.c"),
+ "-o",
+ str(executable),
+ ],
+ check=True,
+ )
+ subprocess.run([str(executable)], check=True)
+print("File Info contracts passed")
diff --git a/extensions/homebrew/Makefile b/extensions/homebrew/Makefile
new file mode 100644
index 0000000..cb973a7
--- /dev/null
+++ b/extensions/homebrew/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c
+include $(SDK)/rv.mk
diff --git a/extensions/homebrew/README.md b/extensions/homebrew/README.md
new file mode 100644
index 0000000..acad91b
--- /dev/null
+++ b/extensions/homebrew/README.md
@@ -0,0 +1,32 @@
+# Homebrew
+
+Based on the RepriseOS core's [homebrew patch](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/homebrew.c), by lgreitis.
+
+Lists apps and games from folders under `/Reprise/` and lets Apple's game runtime start them unsigned. A package is a folder with the program, a `Manifest.plist` and an icon, built with the [eApp SDK](https://github.com/RepriseOS/repriseos/tree/main/eapp-sdk).
+
+| Folder | Appears |
+|---|---|
+| `/Reprise/Games//` | Extras > Games, with the built-in games and those from iTunes |
+| `/Reprise/Apps//` | Extras > Apps |
+
+Apple builds one games list. Opening Apps sets it aside and builds an apps list from `/Reprise/Apps/`; leaving Apps frees that and restores the games list without a rescan. When disk mode ends, Apple rebuilds the games list from the stock folders and `/Reprise/Games/`. The Apps count in the Extras pane is recounted with each build. The list is never rebuilt while a package runs.
+
+Only manifests under `/Reprise/Games//` and `/Reprise/Apps//` skip the signature check; games under `iPod_Control/` keep it. The id is one folder name, without `\` or `:` and not starting with a dot. A package with the id of a game under `iPod_Control/` replaces that game in the list.
+
+| Apple's folder | Game | App |
+|---|---|---|
+| `iPod_Control/gamedata_RW//` | `/Reprise/Data/Games/gamedata_RW//` | `/Reprise/Data/Apps/appdata_RW//` |
+| `iPod_Control/gamestats_WO//` | `/Reprise/Data/Games/gamestats_WO//` | `/Reprise/Data/Apps/appstats_WO//` |
+| `iPod_Control/gamedata_ShareRW/` | `/Reprise/Data/Games/gamedata_ShareRW/` | `/Reprise/Data/Apps/appdata_ShareRW/` |
+
+The shared folder has no id, so all games share one and all apps another.
+
+On other firmware the same package uses Apple's folders like any game.
+
+Turned off, the Apps row and both folders' packages disappear at the next list build.
+
+| | |
+|---|---|
+| Default | on |
+| Memory | image only; the ids of the listed folder while a list holds them, and the games list beside the apps one while Apps is open |
+| Settings | none |
diff --git a/extensions/homebrew/assets/LICENSE.cupertino-icons b/extensions/homebrew/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/homebrew/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/homebrew/assets/apps.png b/extensions/homebrew/assets/apps.png
new file mode 100644
index 0000000..ff197d6
Binary files /dev/null and b/extensions/homebrew/assets/apps.png differ
diff --git a/extensions/homebrew/assets/render.py b/extensions/homebrew/assets/render.py
new file mode 100644
index 0000000..a4ee76d
--- /dev/null
+++ b/extensions/homebrew/assets/render.py
@@ -0,0 +1,386 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
+"""Render apps.png, the Extras pane picture of the Apps row: a slate sheet-metal
+toolbox with a chrome handle, seen from the front-right, lit like the stock
+Extras pictures and standing in a soft contact shadow on a transparent 142 x 87
+canvas. The scene is a signed-distance model marched and shaded with numpy; no
+image assets go in.
+
+ python3 assets/render.py
+ python3 assets/render.py --check
+"""
+
+import argparse
+import math
+import struct
+import sys
+import zlib
+from pathlib import Path
+
+import numpy as np
+
+HERE = Path(__file__).resolve().parent
+OUT = HERE / "apps.png"
+WIDTH, HEIGHT, SUPERSAMPLE = 142, 87, 4
+
+# The toolbox, in a frame where y is up and the tray stands on y = 0.
+TRAY = (1.4, 0.85, 0.55) # half length, height, half width
+LID_SKIRT, LID_RISE, RIDGE_HALF = 0.12, 0.30, 0.20
+LID_LAP, LID_DROP = 0.012, 0.06 # the skirt stands proud of, and drops over, the tray wall
+FOLD = 0.016 # bend radius of the lid's folds
+HANDLE = (0.5, 0.26, 0.13, 0.045) # half width, height, corner radius, tube radius
+YAW = -30 # degrees the box turns from square-on, showing its right end
+CAMERA, LOOK, FOV = (0.11, 1.84, 4.38), (0.0, 0.435, 0.0), 30
+KEY_LIGHT, KEY_POWER = (-1.4, 4.0, 2.2), 4.0
+SHADOW = 0.75
+
+
+def length(v):
+ return np.linalg.norm(v, axis=-1)
+
+
+def unit(v):
+ return v / np.maximum(length(v)[..., None], 1e-9)
+
+
+def rotation(yaw):
+ """Rotation about y by `yaw` degrees."""
+ c, s = math.cos(math.radians(yaw)), math.sin(math.radians(yaw))
+ return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
+
+
+def linear(hex_color):
+ """A #rrggbb sRGB colour as linear light."""
+ c = np.array([int(hex_color[i : i + 2], 16) / 255 for i in (0, 2, 4)])
+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
+
+
+# ---- distance fields -------------------------------------------------------
+
+
+def sd_box(q, half, radius):
+ d = np.abs(q) - (np.array(half) - radius)
+ return length(np.maximum(d, 0)) + np.minimum(d.max(-1), 0) - radius
+
+
+def sd_capsule(q, a, b, radius):
+ a, b = np.array(a), np.array(b)
+ pa, ba = q - a, b - a
+ h = np.clip((pa @ ba) / (ba @ ba), 0, 1)
+ return length(pa - ba * h[..., None]) - radius
+
+
+def sd_round_rect(xy, hw, hh, radius):
+ d = np.abs(xy) - np.array([hw - radius, hh - radius])
+ return length(np.maximum(d, 0)) + np.minimum(d.max(-1), 0) - radius
+
+
+def smooth_min(a, b, k):
+ h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1)
+ return b * (1 - h) + a * h - k * h * (1 - h)
+
+
+def smooth_max(a, b, k):
+ return -smooth_min(-a, -b, k)
+
+
+class Material:
+ def __init__(self, color, rough=0.05, metal=False, coat=1.0, tint=1.0):
+ self.color, self.rough, self.metal, self.coat, self.tint = (
+ linear(color),
+ rough,
+ metal,
+ coat,
+ tint,
+ )
+
+
+class Shape:
+ """A distance function in its own frame, placed in the world."""
+
+ def __init__(self, fn, material, pos=(0, 0, 0), yaw=0.0):
+ self.fn, self.material = fn, material
+ self.pos, self.rot = np.array(pos, float), rotation(yaw)
+
+ def local(self, p):
+ return (p - self.pos) @ self.rot
+
+ def sdf(self, p):
+ return self.fn(self.local(p))
+
+
+SLATE = Material("33475c")
+STEEL = Material("d8dbe0", rough=0.08, metal=True, tint=1.25)
+RUBBER = Material("1a1a1c", rough=0.3, coat=0.3)
+
+
+def toolbox(yaw=YAW):
+ """Tray, a hip-roof lid with the tray's footprint, two latches over the seam,
+ and a chrome handle with a rubber grip on two mounting plates."""
+ hx, top, hz = TRAY
+ turn = rotation(yaw)
+
+ def placed(x, y, z):
+ return turn @ np.array([x, y, z])
+
+ tray = Shape(lambda q: sd_box(q, (hx, top / 2, hz), 0.04), SLATE, (0, top / 2, 0), yaw)
+
+ slope = (hz - RIDGE_HALF) / LID_RISE
+ slope_norm = math.sqrt(1 + slope * slope)
+ lx, lz = hx + LID_LAP, hz + LID_LAP
+
+ def lid_fn(q):
+ x, y, z = q[..., 0], q[..., 1], q[..., 2] # y = 0 at the skirt's bottom
+ planes = (
+ -y,
+ y - (LID_SKIRT + LID_RISE),
+ np.abs(x) - lx,
+ np.abs(z) - lz,
+ (z + slope * (y - LID_SKIRT) - lz) / slope_norm,
+ (-z + slope * (y - LID_SKIRT) - lz) / slope_norm,
+ )
+ d = planes[0]
+ for plane in planes[1:]:
+ d = smooth_max(d, plane, FOLD)
+ return d
+
+ lid_base = top - LID_DROP
+ lid = Shape(lid_fn, SLATE, (0, lid_base, 0), yaw)
+ ridge = lid_base + LID_SKIRT + LID_RISE
+
+ hw, hh, corner, tube = HANDLE
+
+ def plates_fn(q):
+ return np.minimum(
+ sd_box(q - np.array([-hw, 0, 0]), (0.09, 0.02, 0.12), 0.015),
+ sd_box(q - np.array([hw, 0, 0]), (0.09, 0.02, 0.12), 0.015),
+ )
+
+ plates = Shape(plates_fn, STEEL, (0, ridge + 0.02, 0), yaw)
+
+ def latches_fn(q):
+ return np.minimum(
+ sd_box(q - np.array([-0.62, 0, 0]), (0.055, 0.08, 0.022), 0.015),
+ sd_box(q - np.array([0.62, 0, 0]), (0.055, 0.08, 0.022), 0.015),
+ )
+
+ latches = Shape(latches_fn, STEEL, placed(0, lid_base, hz + 0.03), yaw)
+
+ def loop_fn(q):
+ d2 = sd_round_rect(q[..., [0, 1]], hw, hh, corner)
+ loop = np.sqrt(d2 * d2 + q[..., 2] ** 2) - tube
+ return np.maximum(loop, -q[..., 1] - 0.02)
+
+ handle_y = ridge + 0.03
+ loop = Shape(loop_fn, STEEL, (0, handle_y, 0), yaw)
+ grip = Shape(
+ lambda q: sd_capsule(q, (-hw * 0.55, hh, 0), (hw * 0.55, hh, 0), tube * 1.9),
+ RUBBER,
+ (0, handle_y, 0),
+ yaw,
+ )
+ return [tray, lid, plates, latches, loop, grip]
+
+
+# ---- marching and shading --------------------------------------------------
+
+
+def scene_sdf(shapes, p):
+ ds = np.stack([s.sdf(p) for s in shapes], -1)
+ return ds.min(-1), ds.argmin(-1)
+
+
+def march(shapes, ro, rd, tmax=20.0, steps=128):
+ t = np.zeros(ro.shape[:-1])
+ hit = np.zeros(t.shape, bool)
+ idx = np.zeros(t.shape, int)
+ for _ in range(steps):
+ d, i = scene_sdf(shapes, ro + rd * t[..., None])
+ new = (d < 7e-4) & ~hit
+ hit |= new
+ idx = np.where(new, i, idx)
+ t = np.where(hit, t, np.minimum(t + np.maximum(d, 7e-4) * 0.8, tmax))
+ return t, hit, idx
+
+
+def normal(shapes, p, e=6e-4):
+ return unit(
+ np.stack(
+ [
+ scene_sdf(shapes, p + np.eye(3)[k] * e)[0]
+ - scene_sdf(shapes, p - np.eye(3)[k] * e)[0]
+ for k in range(3)
+ ],
+ -1,
+ )
+ )
+
+
+def soft_shadow(shapes, ro, rd, k=6.0, tmin=0.02, tmax=8.0, steps=48):
+ res = np.ones(ro.shape[:-1])
+ t = np.full(res.shape, tmin)
+ for _ in range(steps):
+ d, _ = scene_sdf(shapes, ro + rd * t[..., None])
+ res = np.minimum(res, np.clip(k * d / t, 0, 1))
+ t = np.minimum(t + np.clip(d, 0.015, 0.25), tmax)
+ return res
+
+
+def ambient_occlusion(shapes, p, n):
+ occ, scale = 0.0, 1.0
+ for i in range(1, 6):
+ h = 0.03 + 0.14 * i
+ d, _ = scene_sdf(shapes, p + n * h)
+ occ += (h - d) * scale
+ scale *= 0.75
+ return np.clip(1 - 2.2 * occ, 0, 1)
+
+
+# A studio in linear light: a graded sky over a dark floor, and softbox strips
+# (direction, long axis, width tightness, length tightness, power).
+SKY_TOP, SKY_HORIZON, SKY_FLOOR = (
+ np.array([0.8, 0.82, 0.88]),
+ np.array([0.2, 0.21, 0.24]),
+ np.array([0.01, 0.01, 0.012]),
+)
+STRIPS = (
+ ((-0.35, 0.75, 0.55), (1, 0, -0.4), 60.0, 4.0, 6.0), # key, upper left front
+ ((-0.25, 0.85, -0.45), (1, 0, 0.5), 18.0, 2.5, 5.0), # top back, seen in the lid
+ ((0.75, 0.45, 0.25), (0, 0.3, -1), 90.0, 6.0, 2.5), # right rim
+ ((0.0, 0.2, 1.0), (1, 0, 0), 25.0, 3.0, 0.8), # soft front fill
+)
+
+
+def environment(d, blur=0.0):
+ y = np.clip(d[..., 1], -1, 1)
+ up, down = np.clip(y, 0, 1)[..., None], np.clip(-y, 0, 1)[..., None]
+ out = SKY_HORIZON + (SKY_TOP - SKY_HORIZON) * up**0.7 + (SKY_FLOOR - SKY_HORIZON) * down**0.5
+ sharp = 1 - 0.85 * min(blur, 1.0)
+ for direction, axis, width, span, power in STRIPS:
+ c = unit(np.array(direction, float))
+ a = unit(np.array(axis, float) - np.array(axis, float) @ c * c)
+ along, across = (d * a).sum(-1), (d * np.cross(c, a)).sum(-1)
+ facing = np.clip((d * c).sum(-1), 0, 1)
+ glow = power * facing**2 * np.exp(-(across**2) * width * sharp - along**2 * span * sharp)
+ out = out + glow[..., None]
+ return out
+
+
+def shade(shapes):
+ """Linear RGB and alpha of the scene at SUPERSAMPLE times the output size."""
+ w, h = WIDTH * SUPERSAMPLE, HEIGHT * SUPERSAMPLE
+ ys, xs = np.mgrid[0:h, 0:w]
+ uv = np.stack([(xs + 0.5 - w / 2) / h, -(ys + 0.5 - h / 2) / h], -1)
+ cam, look = np.array(CAMERA, float), np.array(LOOK, float)
+ fwd = unit(look - cam)
+ right = unit(np.cross(fwd, [0, 1, 0]))
+ up = np.cross(right, fwd)
+ focal = 1 / math.tan(math.radians(FOV) / 2) / 2
+ rd = unit(uv[..., 0:1] * right + uv[..., 1:2] * up + focal * fwd)
+ ro = np.broadcast_to(cam, rd.shape)
+
+ t, hit, idx = march(shapes, ro, rd)
+ p = ro + rd * t[..., None]
+ n = normal(shapes, p)
+ key = np.array(KEY_LIGHT, float)
+ ldir = unit(key - p)
+ v = -rd
+ half = unit(ldir + v)
+ ndl = np.clip((n * ldir).sum(-1), 0, 1)
+ ndh = np.clip((n * half).sum(-1), 0, 1)
+ ndv = np.clip((n * v).sum(-1), 1e-3, 1)
+ falloff = 12.0 / np.maximum(length(key - p) ** 2, 1.0)
+ shadow = soft_shadow(shapes, p + n * 0.02, ldir)
+ occlusion = ambient_occlusion(shapes, p, n)
+ reflected = unit(rd - 2 * (n * rd).sum(-1)[..., None] * n)
+ wrap = np.clip(((n * ldir).sum(-1) + 0.3) / 1.3, 0, 1) ** 1.5
+ hemisphere = environment(n, blur=1.0) * 0.35
+
+ rgb = np.zeros(p.shape)
+ for k, shape in enumerate(shapes):
+ mask = idx == k
+ if not mask.any():
+ continue
+ m = shape.material
+ base = np.broadcast_to(m.color, p.shape)
+ f0 = base if m.metal else np.full_like(base, 0.04)
+ fresnel = f0 + (1 - f0) * ((1 - ndv) ** 5)[..., None]
+ a2 = max(m.rough, 0.03) ** 2
+ dn = ndh * ndh * (a2 - 1) + 1
+ ggx = a2 / (math.pi * dn * dn)
+ specular = (ggx * ndl * shadow * falloff)[..., None] * fresnel * 0.9
+ mirror = environment(reflected, blur=m.rough * 1.5) * fresnel * occlusion[..., None]
+ diffuse = base * (
+ (wrap * shadow * KEY_POWER * falloff)[..., None] * np.array([1.0, 0.96, 0.9]) / math.pi
+ + hemisphere * (occlusion * occlusion)[..., None]
+ )
+ if m.metal:
+ color = mirror * m.tint + specular * base * KEY_POWER / 3
+ else:
+ color = diffuse * (1 - fresnel) + mirror * m.coat + specular * KEY_POWER / 3
+ rgb = np.where(mask[..., None], color, rgb)
+
+ # The contact shadow on the invisible floor.
+ gt = -ro[..., 1] / np.where(np.abs(rd[..., 1]) < 1e-6, 1e-6, rd[..., 1])
+ gp = ro + rd * gt[..., None]
+ ground_shadow = soft_shadow(shapes, gp + np.array([0, 0.02, 0]), unit(key - gp), k=3.0)
+ gd, _ = scene_sdf(shapes, gp)
+ contact = np.clip(1 - gd / 0.4, 0, 1) ** 2
+ floor = np.clip(0.5 * (1 - ground_shadow) * contact**0.5 + 0.6 * contact**1.5, 0, 1) * SHADOW
+ alpha = np.where(hit, 1.0, np.where(gt > 0, floor, 0))
+ return rgb, hit, alpha
+
+
+def to_png(rgb, hit, alpha):
+ """Tone-map, encode as sRGB, box-filter down to the output size, and pack a PNG."""
+ x = np.clip(rgb, 0, None)
+ x = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)
+ x = np.clip(x, 0, 1)
+ srgb = np.where(x <= 0.0031308, x * 12.92, 1.055 * x ** (1 / 2.4) - 0.055)
+ color = np.where(hit[..., None], srgb, 0.0)
+ premultiplied = np.concatenate([color * alpha[..., None], alpha[..., None]], -1)
+ small = premultiplied.reshape(HEIGHT, SUPERSAMPLE, WIDTH, SUPERSAMPLE, 4).mean((1, 3))
+ a = small[..., 3:4]
+ straight = np.where(a > 1e-4, small[..., :3] / np.maximum(a, 1e-4), 0)
+ rgba = (np.clip(np.concatenate([straight, a], -1), 0, 1) * 255 + 0.5).astype(np.uint8)
+ raw = b"".join(b"\x00" + rgba[y].tobytes() for y in range(HEIGHT))
+
+ def chunk(kind, data):
+ return (
+ struct.pack(">I", len(data))
+ + kind
+ + data
+ + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
+ )
+
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", WIDTH, HEIGHT, 8, 6, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 9))
+ + chunk(b"IEND", b"")
+ )
+
+
+def render():
+ return to_png(*shade(toolbox()))
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="render in memory and compare with the committed file",
+ )
+ args = parser.parse_args()
+ png = render()
+ if not args.check:
+ OUT.write_bytes(png)
+ return
+ if OUT.read_bytes() != png:
+ sys.exit(f"render.py: {OUT.name} differs from a fresh render")
+ print(f"{OUT.name} matches")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/extensions/homebrew/assets/settings-homebrew.png b/extensions/homebrew/assets/settings-homebrew.png
new file mode 100644
index 0000000..2b816b1
Binary files /dev/null and b/extensions/homebrew/assets/settings-homebrew.png differ
diff --git a/extensions/homebrew/assets/settings-homebrew.svg b/extensions/homebrew/assets/settings-homebrew.svg
new file mode 100644
index 0000000..9f87f69
--- /dev/null
+++ b/extensions/homebrew/assets/settings-homebrew.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/homebrew/listing.toml b/extensions/homebrew/listing.toml
new file mode 100644
index 0000000..ad16d03
--- /dev/null
+++ b/extensions/homebrew/listing.toml
@@ -0,0 +1,15 @@
+details = "In disk mode, copy a package folder to /Reprise/Games// or /Reprise/Apps//. Games appear in Extras > Games beside the stock ones; Apps gets its own row under Extras. Manifests in those two folders skip Apple's signature check; games under iPod_Control keep it."
+
+icon = "assets/settings-homebrew.png"
+
+[[screenshots]]
+file = "screenshots/apps-row.png"
+alt = "Extras with the Apps row selected and its picture in the pane."
+
+[[screenshots]]
+file = "screenshots/apps.png"
+alt = "The Apps list with a homebrew app."
+
+[[screenshots]]
+file = "screenshots/games.png"
+alt = "Extras > Games listing a homebrew game beside the stock games."
diff --git a/extensions/homebrew/main.c b/extensions/homebrew/main.c
new file mode 100644
index 0000000..5592c82
--- /dev/null
+++ b/extensions/homebrew/main.c
@@ -0,0 +1,466 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Packages under /Reprise/Games/ and /Reprise/Apps/ in Apple's Games list. The
+ * games service builds its one list once, so the build entry clears it whenever
+ * what it holds is not what is wanted (games, or apps while the Apps screen is
+ * open) and Apple scans again before a screen draws it; Apps scans before its
+ * screen is pushed. Opening Apps sets a built games list aside instead and
+ * closing it puts the list back, so Games is not scanned again for a visit to
+ * Apps. The manifest reader is handed no signature path for a package, which is
+ * how Apple itself reads a manifest it does not verify.
+ *
+ * Adapted from RepriseOS payload/homebrew.c (fd5d367) by lgreitis. */
+
+#include
+
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_libc.h"
+#include "rv_menus.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+
+#define PATH_BYTES 258 /* the text of Apple's legacy path, as the core's file layer */
+
+static const struct rv_api *api;
+static rv_extension_handle self;
+
+/* A root as the games service scans it, as the manifest's content folder, and
+ * where the packages under it keep their data: one folder under `data` for each
+ * of Apple's UserData, Stats and SharedData, named as on Apple's disk for games
+ * and with app in place of game for apps. */
+struct root {
+ const char *path;
+ const char *content;
+ const char *data;
+ const char *user_data, *stats, *shared_data;
+};
+static const struct root games_root = {"/Reprise/Games/", "Games", "/Reprise/Data/Games/",
+ "gamedata_RW/", "gamestats_WO/", "gamedata_ShareRW/"};
+static const struct root apps_root = {"/Reprise/Apps/", "Apps", "/Reprise/Data/Apps/",
+ "appdata_RW/", "appstats_WO/", "appdata_ShareRW/"};
+
+/* The root the last scan listed and its ids, NUL separated, ending in an empty
+ * name; what GameFiles_BuildPath redirects. */
+static const struct root *listed_root;
+static char *listed_ids;
+
+/* What the list is wanted as, and what it holds: games, or apps while the Apps
+ * screen is open. A list built before the extension loaded is dropped at the
+ * first build after, so it is scanned again with the hooks in place. */
+enum listing { GAMES, APPS };
+static enum listing wanted, built;
+static int fresh = 1;
+/* The games service, from its first list build through the hooks; NULL until then. */
+static void *service;
+/* The games list set aside while the Apps screen is open: the words of Apple's
+ * list that hold its entries, and its ids. Every reader of the list indexes it
+ * afresh, so exchanging these words swaps the whole list. */
+static const uint32_t list_words[] = {GameList_count, GameList_storage, GameList_capacity};
+static uint32_t kept_words[RV_COUNT(list_words)];
+static char *kept_ids;
+static int kept;
+/* The apps scans since the games list was kept. */
+static unsigned apps_scans;
+/* The packages under /Reprise/Apps/, counted again whenever a list build reads
+ * the disk anyway, so the Extras pane does not; -1 until first counted. */
+static int apps_count = -1;
+
+/* 1 for the `n` bytes of a folder name that is one package id: not empty, not
+ * starting with a dot, no path or drive separator. */
+static int is_package_id(const char *name, unsigned n)
+{
+ if (!n || name[0] == '.')
+ return 0;
+ for (unsigned i = 0; i < n; i++)
+ if (name[i] == '/' || name[i] == '\\' || name[i] == ':')
+ return 0;
+ return 1;
+}
+
+/* 1 for root + id + "/Manifest.plist" under one of the roots. */
+static int is_homebrew_manifest(const char *path)
+{
+ const struct root *const roots[] = {&games_root, &apps_root};
+
+ if (!path)
+ return 0;
+ for (unsigned r = 0; r < RV_COUNT(roots); r++) {
+ unsigned n = strlen(roots[r]->path);
+ if (memcmp(path, roots[r]->path, n) != 0)
+ continue;
+ const char *id = path + n, *end = id;
+ while (*end && *end != '/')
+ end++;
+ return is_package_id(id, end - id) && strcmp(end, "/Manifest.plist") == 0;
+ }
+ return 0;
+}
+
+static uint32_t on_manifest_reader(void *reader, const char *manifest, uint32_t volume,
+ const char *signature, const void *next)
+{
+ if (volume == FileVolume_Disk && is_homebrew_manifest(manifest))
+ signature = 0;
+ return api->hook_next(next, (uint32_t)reader, (uint32_t)manifest, volume,
+ (uint32_t)signature, 0, 0);
+}
+
+struct folders {
+ uint32_t bytes;
+ int ids;
+ char *out;
+};
+
+static void count_folder(const char *name, int is_folder, void *arg)
+{
+ struct folders *f = arg;
+ if (is_folder && is_package_id(name, strlen(name))) {
+ f->bytes += strlen(name) + 1;
+ f->ids++;
+ }
+}
+
+static void copy_folder(const char *name, int is_folder, void *arg)
+{
+ struct folders *f = arg;
+ if (!is_folder || !is_package_id(name, strlen(name)))
+ return;
+ unsigned n = strlen(name) + 1;
+ memcpy(f->out, name, n);
+ f->out += n;
+}
+
+static void count_package(const char *name, int is_folder, void *arg)
+{
+ if (is_folder && is_package_id(name, strlen(name)))
+ ++*(int *)arg;
+}
+
+/* A pane that showed another count of /Reprise/Apps/ reads it again. */
+static void set_apps_count(int count)
+{
+ int shown = apps_count;
+ apps_count = count;
+ if (shown >= 0 && count != shown)
+ api->ui_pane_refresh(self);
+}
+
+static void count_apps(void)
+{
+ int count = 0;
+ api->content_list(self, apps_root.content, count_package, &count);
+ set_apps_count(count);
+}
+
+/* Remembers the ids under `root`, then lets Apple scan it. Without memory for
+ * the ids the root is not scanned, but the list still counts as built from it. */
+static void scan_root(void *games, void *list, const struct root *root)
+{
+ struct folders f = {1, 0, NULL};
+ api->content_list(self, root->content, count_folder, &f);
+ if (root == &apps_root)
+ set_apps_count(f.ids);
+ char *ids = api->alloc(self, f.bytes);
+ if (listed_ids)
+ api->free(self, listed_ids);
+ listed_ids = ids;
+ listed_root = root;
+ if (!ids)
+ return;
+ f.out = ids;
+ api->content_list(self, root->content, copy_folder, &f);
+ *f.out = 0;
+ GamesService_ScanRoot(games, list, FileVolume_Disk, root->path);
+}
+
+static uint32_t on_build_list(void *games, const void *next)
+{
+ service = games;
+ if (fresh || built != wanted) {
+ GamesService_ClearList(games);
+ built = wanted;
+ fresh = 0;
+ }
+ return api->hook_next(next, (uint32_t)games, 0, 0, 0, 0, 0);
+}
+
+static uint32_t on_scan_built_in_root(void *games, void *list, uint32_t volume,
+ const char *root, const void *next)
+{
+ if (wanted == APPS)
+ return 0;
+ return api->hook_next(next, (uint32_t)games, (uint32_t)list, volume, (uint32_t)root, 0, 0);
+}
+
+static uint32_t on_scan_disk_root(void *games, void *list, uint32_t volume, const char *root,
+ const void *next)
+{
+ if (wanted == APPS) {
+ apps_scans++;
+ scan_root(games, list, &apps_root);
+ return 0;
+ }
+ uint32_t result =
+ api->hook_next(next, (uint32_t)games, (uint32_t)list, volume, (uint32_t)root, 0, 0);
+ scan_root(games, list, &games_root);
+ count_apps();
+ return result;
+}
+
+static int listed(const char *id)
+{
+ if (!listed_ids)
+ return 0;
+ for (const char *name = listed_ids; *name; name += strlen(name) + 1)
+ if (strcmp(name, id) == 0)
+ return 1;
+ return 0;
+}
+
+/* The folder under the listed root's data folder for UserData, Stats or
+ * SharedData. */
+static const char *data_folder(uint32_t kind)
+{
+ switch (kind) {
+ case GameDirectory_UserData:
+ return listed_root->user_data;
+ case GameDirectory_Stats:
+ return listed_root->stats;
+ default:
+ return listed_root->shared_data;
+ }
+}
+
+/* Appends `text` at `*at`, leaving room for the NUL before `end`; 0 when it
+ * does not fit. */
+static int append(char **at, char *end, const char *text)
+{
+ unsigned n = strlen(text);
+ if (n >= (unsigned)(end - *at))
+ return 0;
+ memcpy(*at, text, n);
+ *at += n;
+ return 1;
+}
+
+/* A listed id's package is / and its data /, the
+ * shared folder without the id as on Apple's disk; Apple's games and a path
+ * that does not fit stay Apple's. */
+static uint32_t on_build_path(struct NativeString *out, uint32_t kind, struct NativeString *id,
+ uint32_t storage, const void *next, const char *leaf)
+{
+ const char *name = id ? NativeString_GetUtf8(id) : NULL;
+ char path[PATH_BYTES], *at = path, *end = path + sizeof path;
+ int fits = 0;
+ if (leaf && *leaf == '/')
+ leaf++;
+ if (kind <= GameDirectory_SharedData && storage == GameStorage_Disk && name &&
+ listed(name)) {
+ if (kind == GameDirectory_Package)
+ fits = append(&at, end, listed_root->path) && append(&at, end, name) &&
+ append(&at, end, "/");
+ else
+ fits = append(&at, end, listed_root->data) &&
+ append(&at, end, data_folder(kind)) &&
+ (kind == GameDirectory_SharedData ||
+ (append(&at, end, name) && append(&at, end, "/")));
+ }
+ if (fits && append(&at, end, leaf ? leaf : "")) {
+ *at = 0;
+ NativeString_InitUtf8(out, path);
+ return 0;
+ }
+ return api->hook_next(next, (uint32_t)out, kind, (uint32_t)id, storage, (uint32_t)leaf, 0);
+}
+
+/* The caption of a row while the list is apps: Apple's words for the play count
+ * with Opened in place of Played, the last still formatted by Apple. */
+static uint32_t on_played_string(void *resources, uint32_t id, const void *next)
+{
+ if (wanted == APPS) {
+ if (id == RES_GamesMenu_NeverPlayed_String)
+ return (uint32_t)"Never Opened";
+ if (id == RES_GamesMenu_PlayedOnce_String)
+ return (uint32_t)"Opened Once";
+ if (id == RES_GamesMenu_PlayedTimes_String)
+ return (uint32_t)"Opened %d Times";
+ }
+ return api->hook_next(next, (uint32_t)resources, id, 0, 0, 0, 0);
+}
+
+/* Apple keeps loaded row icons by artwork id, row + 1, across screens, so the
+ * rows of the apps list take Apple's id plus APPS_ARTWORK_BASE and Games and
+ * Apps never show each other's icons. */
+#define APPS_ARTWORK_BASE 0x10000
+
+static uint32_t on_artwork_id(void *games, uint32_t row, uint32_t *out_id, const void *next)
+{
+ uint32_t found = api->hook_next(next, (uint32_t)games, row, (uint32_t)out_id, 0, 0, 0);
+ if (found && listed_root == &apps_root)
+ *out_id += APPS_ARTWORK_BASE;
+ return found;
+}
+
+/* Apple's artwork id, row + 1, for an artwork id of the list held; 0 for an id
+ * of the other list. */
+static uint32_t apple_artwork_id(uint32_t id)
+{
+ if (listed_root != &apps_root)
+ return id < APPS_ARTWORK_BASE ? id : 0;
+ return id > APPS_ARTWORK_BASE ? id - APPS_ARTWORK_BASE : 0;
+}
+
+static uint32_t on_artwork_path(void *games, uint32_t id, void *out, const void *next)
+{
+ id = apple_artwork_id(id);
+ if (!id)
+ return 0;
+ return api->hook_next(next, (uint32_t)games, id, (uint32_t)out, 0, 0, 0);
+}
+
+static uint32_t on_artwork_storage(void *games, uint32_t id, const void *next)
+{
+ id = apple_artwork_id(id);
+ if (!id)
+ return 0;
+ return api->hook_next(next, (uint32_t)games, id, 0, 0, 0, 0);
+}
+
+/* Empties Apple's list, which frees its entries, and forgets their ids. */
+static void clear_list(void)
+{
+ GamesService_ClearList(service);
+ if (listed_ids)
+ api->free(self, listed_ids);
+ listed_ids = NULL;
+}
+
+/* Exchanges the entries of Apple's list with the kept ones, ids included. */
+static void swap_list(void)
+{
+ for (unsigned i = 0; i < RV_COUNT(list_words); i++) {
+ uint32_t *word = &RV_FIELD(service, GamesService_list + list_words[i], uint32_t);
+ uint32_t held = *word;
+ *word = kept_words[i];
+ kept_words[i] = held;
+ }
+ char *ids = listed_ids;
+ listed_ids = kept_ids;
+ kept_ids = ids;
+}
+
+/* Ends the keeping: Apple's clear frees the entries of the list it holds, the
+ * apps, and the games come back; `restore` keeps them as built, otherwise they
+ * are freed too and Games is scanned again. */
+static void end_keeping(int restore)
+{
+ clear_list();
+ swap_list();
+ memset(kept_words, 0, sizeof kept_words);
+ listed_root = &games_root;
+ kept = 0;
+ if (restore) {
+ RV_FIELD(service, GamesService_list_built, uint32_t) = 1;
+ built = GAMES;
+ return;
+ }
+ clear_list();
+}
+
+/* Back to games once the Apps screen closed: the kept games list returns when
+ * the apps were scanned once and are still listed. Anything else means Apple
+ * cleared the list, as it does when disk mode ends; the kept list is out of date
+ * then and goes. */
+static void apps_closed(const struct rv_context *ctx)
+{
+ (void)ctx;
+ wanted = GAMES;
+ if (kept)
+ end_keeping(apps_scans == 1 && RV_FIELD(service, GamesService_list_built, uint32_t));
+}
+
+/* The Apps row: the list is wanted as apps from before the push until the
+ * screen closes. A games list built through the hooks is set aside for an empty
+ * one (the kept words start zero), so Games is not scanned again after Apps.
+ * The apps are scanned before the push: the screen starts Apple's artwork
+ * session as it activates, before its first count, and the session loads the
+ * icons of as many rows as the list holds then. */
+static void open_apps(const struct rv_context *ctx)
+{
+ if (service && !fresh && built == GAMES &&
+ RV_FIELD(service, GamesService_list_built, uint32_t)) {
+ swap_list();
+ listed_root = &apps_root;
+ RV_FIELD(service, GamesService_list_built, uint32_t) = 0;
+ built = APPS;
+ apps_scans = 0;
+ kept = 1;
+ }
+ wanted = APPS;
+ GamesService_BuildList(GamesService_Get());
+ if (api->ui_push(ctx->self, "apps", NULL) == RV_OK)
+ return;
+ wanted = GAMES;
+ if (kept)
+ end_keeping(1); /* the kept games list is still as built */
+}
+
+/* The Extras pane beside the Apps row: how many packages the folder holds. */
+static const char *apps_caption(const struct rv_context *ctx)
+{
+ static char caption[16];
+ (void)ctx;
+ if (apps_count < 0)
+ count_apps();
+ rv_format_int(caption, sizeof caption, apps_count, apps_count == 1 ? " App" : " Apps");
+ return caption;
+}
+
+/* Apple builds the list once, so what it holds follows the hooks that were bound
+ * when it was built: dropped here so Apple builds it again on demand without
+ * them. A list never built through the hooks holds nothing of ours. */
+static void unload(void)
+{
+ if (kept)
+ end_keeping(0);
+ else if (service)
+ clear_list();
+}
+
+static const struct rv_hook hooks[] = {
+ RV_HOOK_FILTER(RV_SITE_GameManifest_InitReader_call, on_manifest_reader),
+ RV_HOOK_FILTER(RV_SITE_GamesService_BuildList_entry, on_build_list),
+ RV_HOOK_FILTER(RV_SITE_GamesService_ScanBuiltInRoot_call, on_scan_built_in_root),
+ RV_HOOK_FILTER(RV_SITE_GamesService_ScanDiskRoot_call, on_scan_disk_root),
+ RV_HOOK_FILTER(RV_SITE_GameFiles_BuildPath_entry, on_build_path),
+ RV_HOOK_FILTER(RV_SITE_GamesService_PlayedString_call, on_played_string),
+ RV_HOOK_FILTER(RV_SITE_GamesService_PlayedTimesString_call, on_played_string),
+ RV_HOOK_FILTER(RV_SITE_GamesService_GetArtworkId_entry, on_artwork_id),
+ RV_HOOK_FILTER(RV_SITE_GamesService_GetArtworkPath_entry, on_artwork_path),
+ RV_HOOK_FILTER(RV_SITE_GamesService_GetArtworkStorage_entry, on_artwork_storage),
+};
+
+static const struct rv_screen screens[] = {
+ RV_SCREEN_STOCK("apps", "Apps", RV_STOCK_SCREEN_GAMES, .closed = apps_closed),
+};
+
+static const struct rv_menu_entry entries[] = {
+ RV_MENU_ENTRY(RV_MENU_EXTRAS, RV_EXTRAS_GAMES, RV_ROW_ACTION("Apps", open_apps),
+ .pane = RV_PANE(.caption_text = apps_caption, .bitmap = RV_BITMAP("apps"))),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+ RV_SCREENS(screens),
+ RV_ENTRIES(entries),
+ .unload = unload,
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core, rv_extension_handle handle)
+{
+ api = core;
+ self = handle;
+ return &extension;
+}
diff --git a/extensions/homebrew/manifest.toml b/extensions/homebrew/manifest.toml
new file mode 100644
index 0000000..65c45e2
--- /dev/null
+++ b/extensions/homebrew/manifest.toml
@@ -0,0 +1,19 @@
+id = "homebrew"
+name = "Homebrew"
+description = "Apps and games from /Reprise/Apps and /Reprise/Games under Extras, started without an Apple signature."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "system"
+content = ["Games", "Apps"]
+
+[[module]]
+name = "main"
+trigger = "always"
+
+[[asset]]
+name = "apps"
+file = "assets/apps.png"
+pane = "picture"
diff --git a/extensions/homebrew/screenshots/apps-row.png b/extensions/homebrew/screenshots/apps-row.png
new file mode 100644
index 0000000..2e7e959
Binary files /dev/null and b/extensions/homebrew/screenshots/apps-row.png differ
diff --git a/extensions/homebrew/screenshots/apps.png b/extensions/homebrew/screenshots/apps.png
new file mode 100644
index 0000000..356d6e1
Binary files /dev/null and b/extensions/homebrew/screenshots/apps.png differ
diff --git a/extensions/homebrew/screenshots/games.png b/extensions/homebrew/screenshots/games.png
new file mode 100644
index 0000000..ca57d85
Binary files /dev/null and b/extensions/homebrew/screenshots/games.png differ
diff --git a/extensions/iap-auth-bypass/Makefile b/extensions/iap-auth-bypass/Makefile
new file mode 100644
index 0000000..cb973a7
--- /dev/null
+++ b/extensions/iap-auth-bypass/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c
+include $(SDK)/rv.mk
diff --git a/extensions/iap-auth-bypass/README.md b/extensions/iap-auth-bypass/README.md
new file mode 100644
index 0000000..cc65173
--- /dev/null
+++ b/extensions/iap-auth-bypass/README.md
@@ -0,0 +1,15 @@
+# iAP Auth Bypass
+
+Based on the RepriseOS core's [iAP auth bypass](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/iap_auth.c), by RaduTek.
+
+Lets accessories use authentication-gated iPod Accessory Protocol (iAP) lingos and commands without an Apple authentication coprocessor. Both signature verifiers report success, but accessories must still answer the certificate and signature requests of the handshake.
+
+Disabling it restores signature verification for later handshakes; accessories already authenticated stay connected.
+
+The handshake, the verification gate and the hook calling conventions are in the [iAP reversing notes](https://github.com/RepriseOS/repriseos/blob/b9b1c62/docs/iap-auth.md).
+
+| | |
+|---|---|
+| Default | off |
+| Memory | image only |
+| Settings | none |
diff --git a/extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons b/extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png
new file mode 100644
index 0000000..2713d8f
Binary files /dev/null and b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png differ
diff --git a/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg
new file mode 100644
index 0000000..700982c
--- /dev/null
+++ b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/iap-auth-bypass/listing.toml b/extensions/iap-auth-bypass/listing.toml
new file mode 100644
index 0000000..fcc3d45
--- /dev/null
+++ b/extensions/iap-auth-bypass/listing.toml
@@ -0,0 +1,3 @@
+details = "Enable the extension and connect an accessory without an Apple authentication chip; its authentication-gated iAP commands then work. Nothing is added to the menus."
+
+icon = "assets/settings-iap-auth-bypass.png"
diff --git a/extensions/iap-auth-bypass/main.c b/extensions/iap-auth-bypass/main.c
new file mode 100644
index 0000000..fa79cb9
--- /dev/null
+++ b/extensions/iap-auth-bypass/main.c
@@ -0,0 +1,50 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Both accessory signature verifiers return zero on success. The General Lingo
+ * 0x18 handler then acknowledges success and marks the accessory authenticated.
+ *
+ * Adapted from RepriseOS payload/iap_auth.c (c99dc33) by RaduTek. */
+
+#include "rv_api.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+
+static uint32_t verify_rsa(void *manager, uint32_t channel, uint32_t key_id,
+ void *signature, const void *next, uint32_t signature_bytes)
+{
+ (void)manager;
+ (void)channel;
+ (void)key_id;
+ (void)signature;
+ (void)next;
+ (void)signature_bytes;
+ return 0;
+}
+
+static uint32_t verify_alternate(void *authentication, void *signature,
+ uint32_t signature_bytes, const void *next)
+{
+ (void)authentication;
+ (void)signature;
+ (void)signature_bytes;
+ (void)next;
+ return 0;
+}
+
+static const struct rv_hook hooks[] = {
+ RV_HOOK_REPLACE(RV_SITE_IAP_VerifyDeviceSignatureRSA_call, verify_rsa),
+ RV_HOOK_REPLACE(RV_SITE_IAP_VerifyDeviceSignatureAlternate_call, verify_alternate),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ (void)core;
+ (void)handle;
+ return &extension;
+}
diff --git a/extensions/iap-auth-bypass/manifest.toml b/extensions/iap-auth-bypass/manifest.toml
new file mode 100644
index 0000000..7c5f399
--- /dev/null
+++ b/extensions/iap-auth-bypass/manifest.toml
@@ -0,0 +1,13 @@
+id = "iap-auth-bypass"
+name = "iAP Auth Bypass"
+description = "Let accessories use authentication-gated iAP commands without an Apple authentication chip."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "system"
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/night-shift/manifest.toml b/extensions/night-shift/manifest.toml
index fd37372..f6f6e5b 100644
--- a/extensions/night-shift/manifest.toml
+++ b/extensions/night-shift/manifest.toml
@@ -1,12 +1,15 @@
id = "night-shift"
name = "Night Shift"
description = "Warm the display manually or follow sunset and sunrise in the iPod's time zone."
-version = "0.1.2"
+version = "0.1.3"
author = "RepriseOS and RevolaOS contributors"
license = "GPL-3.0-only"
-api = "1.81"
+api = "1.89"
category = "system"
+[libraries]
+optional = ["reprise"]
+
[[module]]
name = "main"
trigger = "always"
diff --git a/extensions/playback-log/README.md b/extensions/playback-log/README.md
index d856b77..2d1e3c7 100644
--- a/extensions/playback-log/README.md
+++ b/extensions/playback-log/README.md
@@ -50,7 +50,8 @@ is left; an unfinished play is lost on an abrupt reset or power loss.
| `percent` | `listened_ms` as a percentage of `length_ms`; rewinding can make it exceed 100. |
| `ended` | `end` (played to the end), `skip` (next/previous button), `change` (another selection or stop). |
| `apple` | `played` or `skipped` when the stock firmware updated that counter, otherwise `none`. |
-| `artist`, `album_artist`, `album`, `title` | Tags from the iTunesDB. |
+| `artist`, `album`, `title` | Tags from the iTunesDB. |
+| `album_artist` | The Album Artist from the Album Artists extension while it runs, when it differs from the artist; otherwise empty. |
| `track`, `disc`, `year` | Numbers from the iTunesDB, `0` when missing. |
| `genre`, `composer` | Tags from the iTunesDB. |
| `bitrate` | Average kbps from the iTunesDB. |
diff --git a/extensions/playback-log/main.c b/extensions/playback-log/main.c
index 81db894..1bc4aba 100644
--- a/extensions/playback-log/main.c
+++ b/extensions/playback-log/main.c
@@ -1,4 +1,5 @@
/* SPDX-License-Identifier: GPL-3.0-only */
+#include "../album-artists/service.h"
#include "../shared/legacy.h"
#include "native.h"
#include "playback_log_config.h"
@@ -118,8 +119,10 @@ static void field_media_text(struct osos_media_item *item, enum osos_media_text
if (field) {
osos_media_item_text(item, field, &string);
} else {
+ const struct album_artists_service *albums =
+ api->extension_service(ALBUM_ARTISTS_ID);
uint16_t text[255];
- uint32_t units = api->album_artist_read(item->record, text, 255);
+ uint32_t units = albums ? albums->read(item->record, text, 255) : 0;
osos_native_string_assign_utf16(&string, text, units);
}
const char *text = osos_native_string_data(&string);
@@ -657,8 +660,6 @@ static const struct rv_descriptor extension = {
const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
rv_extension_handle handle)
{
- if (!rv_has_reprise_services(core))
- return NULL;
api = core;
self = handle;
load_config();
diff --git a/extensions/playback-log/manifest.toml b/extensions/playback-log/manifest.toml
index 73fed35..d1b4915 100644
--- a/extensions/playback-log/manifest.toml
+++ b/extensions/playback-log/manifest.toml
@@ -1,12 +1,15 @@
id = "playback-log"
name = "Playback Log"
description = "Write a scrobbler log and optional detailed listening reports."
-version = "0.1.1"
+version = "0.1.3"
author = "RepriseOS contributors"
license = "GPL-3.0-only"
-api = "1.82"
+api = "1.89"
category = "media"
+[libraries]
+optional = ["reprise"]
+
[[module]]
name = "main"
trigger = "always"
diff --git a/extensions/playback-log/test.c b/extensions/playback-log/test.c
index 44b56db..d2b44fa 100644
--- a/extensions/playback-log/test.c
+++ b/extensions/playback-log/test.c
@@ -138,6 +138,8 @@ static int mock_seek(void *h, uint64_t n, int w)
#define osos_file_read mock_read
#define osos_file_close(h) ((void)(h))
#define osos_file_seek mock_seek
+/* Weak like the optional.h of the build, so the tests against NULL stay. */
+#pragma weak reprise_legacy_preference
#include "main.c"
enum { FINISH, COMPLETE };
@@ -168,14 +170,20 @@ static int32_t mock_enabled(rv_extension_handle ext, uint16_t key)
return 0;
}
-static uint32_t read_artist(void *r, uint16_t *s, uint32_t n)
+uint32_t (reprise_legacy_preference)(uint32_t key, void *data, uint32_t capacity)
{
- (void)r;
- (void)s;
- (void)n;
+ (void)key;
+ (void)data;
+ (void)capacity;
return 0;
}
+static const void *mock_service(const char *id)
+{
+ assert(!strcmp(id, ALBUM_ARTISTS_ID));
+ return NULL;
+}
+
static void configure(const char *text)
{
cfw_log_config_parse(&config, text, (uint32_t)strlen(text));
@@ -194,8 +202,8 @@ int main(void)
{
static const struct rv_api mock = {
.hook_next = mock_next,
- .album_artist_read = read_artist,
.setting_get_int = mock_enabled,
+ .extension_service = mock_service,
};
api = &mock;
load_config();
diff --git a/extensions/playback-queue/Makefile b/extensions/playback-queue/Makefile
new file mode 100644
index 0000000..c08c2fc
--- /dev/null
+++ b/extensions/playback-queue/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-3.0-only
+main_SOURCES := main.c queue.c
+include $(SDK)/rv.mk
diff --git a/extensions/playback-queue/README.md b/extensions/playback-queue/README.md
new file mode 100644
index 0000000..adba849
--- /dev/null
+++ b/extensions/playback-queue/README.md
@@ -0,0 +1,27 @@
+# Playback Queue
+
+Partly adapted from the RepriseOS core's [Play Next](https://github.com/RepriseOS/repriseos/blob/c997a51/payload/play_next.c) and [queue selection](https://github.com/RepriseOS/repriseos/blob/c997a51/payload/queue_selection.c), by lgreitis and brilliant-alien. The Up Next screen follows the one Alex Ball added in [e501359](https://github.com/RepriseOS/repriseos/commit/e501359).
+
+Adds Play Next and Play Last to the context menu of a song, album, artist or audio podcast episode, and an Up Next screen. Play Next inserts at the front of the queue, Play Last at the end; albums and artists keep their order. Up Next lists the upcoming items' titles and artists or publishers, without the current item, or "No Upcoming Items".
+
+| Action | Result |
+|---|---|
+| Select an item | plays it in Now Playing; it and the items before it leave the queue but stay in the history for Previous |
+| Hold Select on an item | move it up or down, send it to the top or bottom, remove it, browse its album and artist, or open File Info; moves that would change nothing are hidden |
+| Clear Up Next, from the Up Next or Now Playing context menu | removes every upcoming item after a confirmation; the current item and repeat are kept |
+
+Browse Album and Browse Artist go through Music as the stock song menus do; a compilation track gets Browse Compilation in their place when the stock menus offer it. File Info shows while the File Info extension runs.
+
+After a removal the highlight moves to the item above, or stays at the top. Returning to Up Next highlights the first item. The list follows playback.
+
+Adding items while nothing plays builds the queue without starting playback; Play/Pause starts the first item. Adding items while paused keeps playback paused. Playing a selection from the library replaces the queue.
+
+Podcast episodes keep Apple's saved position and played status. Video podcasts and whole shows cannot be added. Only a player-owned list of media entries without nested groups can be edited; other lists are left alone.
+
+Up Next shows in Music and not on the Main Menu by default; Settings > Music Menu and Settings > Main Menu change that. On first start a saved Main Menu checkbox of the Up Next row that earlier RepriseOS releases built in carries over, and Up Next then stays out of Music as it did there. Its code stays loaded while the extension is on.
+
+| | |
+|---|---|
+| Default | on |
+| Memory | image only |
+| Settings | the two menu visibility flags |
diff --git a/extensions/playback-queue/assets/LICENSE.cupertino-icons b/extensions/playback-queue/assets/LICENSE.cupertino-icons
new file mode 100644
index 0000000..581f84c
--- /dev/null
+++ b/extensions/playback-queue/assets/LICENSE.cupertino-icons
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Vladimir Kharlampidi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/extensions/playback-queue/assets/settings-playback-queue.png b/extensions/playback-queue/assets/settings-playback-queue.png
new file mode 100644
index 0000000..b5a827f
Binary files /dev/null and b/extensions/playback-queue/assets/settings-playback-queue.png differ
diff --git a/extensions/playback-queue/assets/settings-playback-queue.svg b/extensions/playback-queue/assets/settings-playback-queue.svg
new file mode 100644
index 0000000..0649138
--- /dev/null
+++ b/extensions/playback-queue/assets/settings-playback-queue.svg
@@ -0,0 +1,5 @@
+
diff --git a/extensions/playback-queue/listing.toml b/extensions/playback-queue/listing.toml
new file mode 100644
index 0000000..80b4a62
--- /dev/null
+++ b/extensions/playback-queue/listing.toml
@@ -0,0 +1,15 @@
+details = "Hold Select on a song, album, artist or podcast episode and choose Play Next or Play Last. Choose Up Next in Music, or from the Now Playing context menu, to reorder, remove or clear the upcoming items."
+
+icon = "assets/settings-playback-queue.png"
+
+[[screenshots]]
+file = "screenshots/up-next.png"
+alt = "Up Next listing the upcoming songs with their artists."
+
+[[screenshots]]
+file = "screenshots/item-menu.png"
+alt = "Holding Select on an Up Next item: Move to Top, Move Up, Remove, Browse Compilation, File Info and Clear Up Next."
+
+[[screenshots]]
+file = "screenshots/clear.png"
+alt = "The Clear Up Next question with its Clear and Cancel buttons."
diff --git a/extensions/playback-queue/main.c b/extensions/playback-queue/main.c
new file mode 100644
index 0000000..fb85d4a
--- /dev/null
+++ b/extensions/playback-queue/main.c
@@ -0,0 +1,428 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* Play Next and Play Last in music and audio podcast episode context menus,
+ * and Up Next: pending items in Music, the Main menu and the
+ * Now Playing context menu.
+ *
+ * The Play Last flag around Add to On-The-Go is adapted from RepriseOS
+ * payload/queue_selection.c (11e5ba7, c997a51) by brilliant-alien and lgreitis.
+ * Up Next is based on RepriseOS payload/up_next.c (e501359) by Alex Ball. */
+
+#include "queue.h"
+#include "../file-info/service.h"
+#include "../shared/menu_visibility.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_media.h"
+#include "rv_menus.h"
+#include "rv_sites.h"
+#include "rv_ui.h"
+#include
+
+#define KEY_IN_MUSIC 1 /* Settings > Music Menu and Main Menu flip these two */
+#define KEY_IN_MAIN 2
+
+static const struct rv_api *api;
+static rv_extension_handle self;
+
+/* Play Last flag of the Add to On-The-Go in progress, -1 when none is. */
+static int32_t adding = -1;
+
+/* Album and artist rows reuse Add to On-The-Go: it filters the library to the
+ * selection and hands it to the On-The-Go playlist here. */
+static uint32_t on_the_go_add(uint32_t otg, uint32_t row, uint32_t browser,
+ uint32_t save, const void *next)
+{
+ if (adding < 0)
+ return api->hook_next(next, otg, row, browser, save, 0, 0);
+ if ((int32_t)row == -1)
+ queue_add_browser((void *)browser, adding);
+ return 1;
+}
+
+static void add_selection(const struct rv_context *ctx, int last)
+{
+ adding = last;
+ MediaListController_AddSelectionToOnTheGo(ctx->controller);
+ adding = -1;
+}
+
+static void song_next(const struct rv_context *ctx)
+{
+ queue_add_item(ctx->item, 0);
+}
+
+static void song_last(const struct rv_context *ctx)
+{
+ queue_add_item(ctx->item, 1);
+}
+
+static void selection_next(const struct rv_context *ctx)
+{
+ add_selection(ctx, 0);
+}
+
+static void selection_last(const struct rv_context *ctx)
+{
+ add_selection(ctx, 1);
+}
+
+static int available(const struct rv_context *ctx)
+{
+ (void)ctx;
+ return queue_available();
+}
+
+static int can_add(const struct rv_context *ctx)
+{
+ (void)ctx;
+ return queue_can_add();
+}
+
+static int can_add_item(const struct rv_context *ctx)
+{
+ return queue_can_add_item(ctx->item);
+}
+
+static uint32_t toggle_stopped(uint32_t player, const void *next)
+{
+ if (queue_start_idle())
+ return 1;
+ return api->hook_next(next, player, 0, 0, 0, 0, 0);
+}
+
+static int upcoming(const struct rv_context *ctx)
+{
+ (void)ctx;
+ return queue_rows() != 0;
+}
+
+/* Up Next */
+
+static char title[128], artist[128];
+static struct rv_timer *refresh_timer;
+static uint32_t queue_views;
+
+static void refresh_queue(void *arg)
+{
+ (void)arg;
+ if (queue_changed())
+ api->ui_refresh(self, "queue");
+}
+
+static void queue_opened(const struct rv_context *ctx)
+{
+ (void)ctx;
+ if (queue_views++)
+ return;
+ queue_changed();
+ refresh_timer = api->timer_start(self, 500, 1, refresh_queue, NULL);
+}
+
+static void queue_closed(const struct rv_context *ctx)
+{
+ (void)ctx;
+ if (--queue_views)
+ return;
+ rv_timer_cancel(api, self, &refresh_timer);
+}
+
+static uint32_t song_count(const struct rv_context *ctx)
+{
+ (void)ctx;
+ return queue_rows();
+}
+
+static const char *song_row(const struct rv_context *ctx, uint32_t index,
+ const char **detail)
+{
+ (void)ctx;
+ queue_text(index, 0, title, sizeof title);
+ queue_text(index, 1, artist, sizeof artist);
+ *detail = artist;
+ return title;
+}
+
+static uint32_t song_first(const struct rv_context *ctx)
+{
+ (void)ctx;
+ return 0;
+}
+
+static int song_select(const struct rv_context *ctx, uint32_t index)
+{
+ queue_play(index);
+ void *created = ControllerRegistry_InvokeControllerFactory(
+ UI_GetControllerRegistry(), "TMediaNowPlayingCntlr", "TMediaNowPlayingCntlr");
+ if (created)
+ rv_controller_push(ctx->controller, created);
+ api->ui_select(self, "queue", 0);
+ return 0;
+}
+
+static int can_remove(const struct rv_context *ctx)
+{
+ return ctx->row >= 0 && queue_capture(ctx->row);
+}
+
+static int can_move_up(const struct rv_context *ctx)
+{
+ return ctx->row > 0 && can_remove(ctx);
+}
+
+static int can_move_down(const struct rv_context *ctx)
+{
+ return can_remove(ctx) && (uint32_t)ctx->row + 1 < queue_rows();
+}
+
+static void move_top(const struct rv_context *ctx)
+{
+ queue_move(ctx->row, 0);
+ api->ui_refresh(self, "queue");
+}
+
+static void move_up(const struct rv_context *ctx)
+{
+ if (ctx->row > 0)
+ queue_move(ctx->row, ctx->row - 1);
+ api->ui_refresh(self, "queue");
+}
+
+static void move_down(const struct rv_context *ctx)
+{
+ if (ctx->row >= 0)
+ queue_move(ctx->row, ctx->row + 1);
+ api->ui_refresh(self, "queue");
+}
+
+static void move_bottom(const struct rv_context *ctx)
+{
+ uint32_t count = queue_rows();
+ if (count)
+ queue_move(ctx->row, count - 1);
+ api->ui_refresh(self, "queue");
+}
+
+static void remove_song(const struct rv_context *ctx)
+{
+ queue_remove(ctx->row);
+ api->ui_refresh(self, "queue");
+ api->ui_select(self, "queue", ctx->row > 0 ? (uint32_t)ctx->row - 1 : 0);
+}
+
+/* Browse Album, Artist and Compilation as the stock song list offers them:
+ * not for audiobooks, videos, iTunes U or records with flag 8F01, and a
+ * compilation with preference 0x60bc set gets Browse Compilation in place
+ * of the other two. The name goes to the navigator as
+ * the pending selection; the stock menus follow it down from the main
+ * screen. */
+enum browse { BROWSE_NONE, BROWSE_ALBUM_ARTIST, BROWSE_COMPILATION };
+
+static enum browse browse_kind(const struct rv_context *ctx)
+{
+ void *record =
+ ctx->row >= 0 && queue_capture(ctx->row) ? queue_record(ctx->row) : NULL;
+ if (!record)
+ return BROWSE_NONE;
+ _Alignas(uint32_t) uint8_t storage[MediaItem_bytes];
+ struct MediaItem *item =
+ MediaItem_InitFromRecord((struct MediaItem *)storage, record, 0);
+ enum browse kind = BROWSE_NONE;
+ if (!MediaItem_HasRecordFlag8F01(item) && !MediaItem_HasKind200000(item) &&
+ !MediaItem_HasKind8(item) && !MediaItem_HasKind8062(item)) {
+ void *preferences = PreferencesService_Get();
+ kind = MediaItem_IsCompilation(item) && preferences &&
+ PreferencesService_Get60BC(preferences)
+ ? BROWSE_COMPILATION
+ : BROWSE_ALBUM_ARTIST;
+ }
+ MediaItem_Destroy(item);
+ return kind;
+}
+
+static int can_browse_pair(const struct rv_context *ctx)
+{
+ return browse_kind(ctx) == BROWSE_ALBUM_ARTIST;
+}
+
+static int can_browse_compilation(const struct rv_context *ctx)
+{
+ return browse_kind(ctx) == BROWSE_COMPILATION;
+}
+
+/* ARM: Runtime_OperatorNew returns with mov pc, lr. The screen that takes
+ * the selection deletes the copy. */
+RV_ARM static void request(const char *key, const struct NativeString *name)
+{
+ struct NativeString *copy = Runtime_OperatorNew(NativeString_bytes);
+ if (!copy)
+ return;
+ NativeString_InitCopy(copy, name);
+ _Alignas(uint32_t) uint8_t storage[CppString_bytes];
+ CppString_Init(storage, key);
+ NavigatorProperties_SetPointer(NavigatorProperties, storage, copy);
+ CppString_Destroy(storage);
+}
+
+static void browse(const struct rv_context *ctx, const char *key, int artist)
+{
+ void *record = ctx->row >= 0 ? queue_record(ctx->row) : NULL;
+ if (!record)
+ return;
+ _Alignas(uint32_t) uint8_t storage[MediaItem_bytes];
+ _Alignas(uint32_t) uint8_t text[NativeString_bytes];
+ struct MediaItem *item =
+ MediaItem_InitFromRecord((struct MediaItem *)storage, record, 0);
+ struct NativeString *name = (struct NativeString *)text;
+ NativeString_InitEmpty(name);
+ if (artist)
+ MediaItem_GetArtist(item, name);
+ else
+ MediaItem_GetAlbum(item, name);
+ request(key, name);
+ Navigator_PopToMainScreenOnly();
+ NativeString_Destroy(name);
+ MediaItem_Destroy(item);
+}
+
+static void browse_album(const struct rv_context *ctx)
+{
+ browse(ctx, "SelectAlbum", 0);
+}
+
+static void browse_artist(const struct rv_context *ctx)
+{
+ browse(ctx, "SelectArtist", 1);
+}
+
+static void browse_compilation(const struct rv_context *ctx)
+{
+ browse(ctx, "SelectCompilation", 0);
+}
+
+static const struct file_info_service *file_info(void)
+{
+ return api->extension_service(FILE_INFO_ID);
+}
+
+static int can_show_info(const struct rv_context *ctx)
+{
+ return ctx->row >= 0 && file_info() && queue_capture(ctx->row);
+}
+
+static void show_info(const struct rv_context *ctx)
+{
+ const struct file_info_service *info = file_info();
+ void *record = ctx->row >= 0 ? queue_record(ctx->row) : NULL;
+ if (info && record)
+ info->open(record);
+}
+
+static const struct rv_context_row song_menu[] = {
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Move to Top", move_top), .available = can_move_up),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Move Up", move_up), .available = can_move_up),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Move Down", move_down), .available = can_move_down),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Move to Bottom", move_bottom),
+ .available = can_move_down),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Remove", remove_song), .available = can_remove),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Browse Album", browse_album),
+ .available = can_browse_pair),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Browse Artist", browse_artist),
+ .available = can_browse_pair),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("Browse Compilation", browse_compilation),
+ .available = can_browse_compilation),
+ RV_CONTEXT_ROW(RV_ROW_ACTION("File Info", show_info), .available = can_show_info),
+ RV_CONTEXT_ROW(RV_ROW_PUSH("Clear Up Next", "clear"), .available = upcoming),
+};
+
+/* Clear is button 0. */
+static int clear_chosen(const struct rv_context *ctx, uint32_t index)
+{
+ (void)ctx;
+ if (index == 0) {
+ queue_clear();
+ api->ui_refresh(self, "queue");
+ }
+ return 1;
+}
+
+static const char *const clear_buttons[] = {"Clear", "Cancel"};
+
+static const struct rv_screen screens[] = {
+ RV_SCREEN_DYNAMIC_LIST(
+ "queue", "Up Next", song_count, song_row, .dynamic.select = song_select,
+ .layout = RV_LAYOUT_FULL, .dynamic.detail = RV_DETAIL_BELOW,
+ .dynamic.initial = song_first, .dynamic.empty = "No Upcoming Items",
+ RV_SCREEN_CONTEXT(song_menu), .opened = queue_opened, .closed = queue_closed),
+ RV_SCREEN_DIALOG("clear", "Up Next", "Clear Up Next?",
+ "The items after the current one are removed from the queue.",
+ clear_buttons, clear_chosen, .dialog.initial = 1),
+};
+
+/* The menus that hand over one song, and the ones that hand over an album or
+ * artist. */
+#define ITEM_MENUS \
+ (RV_MENU_BIT(RV_MENU_SONG_CONTEXT) | RV_MENU_BIT(RV_MENU_PODCAST_EPISODE_CONTEXT))
+#define SELECTION_MENUS \
+ (RV_MENU_BIT(RV_MENU_ALBUM_CONTEXT) | RV_MENU_BIT(RV_MENU_ARTIST_CONTEXT))
+
+static const struct rv_menu_entry entries[] = {
+ RV_MENUS_ENTRY(ITEM_MENUS, 0, RV_ROW_ACTION("Play Next", song_next),
+ .available = can_add_item),
+ RV_MENUS_ENTRY(ITEM_MENUS, 0, RV_ROW_ACTION("Play Last", song_last),
+ .available = can_add_item),
+ RV_MENUS_ENTRY(SELECTION_MENUS, 0, RV_ROW_ACTION("Play Next", selection_next),
+ .available = can_add),
+ RV_MENUS_ENTRY(SELECTION_MENUS, 0, RV_ROW_ACTION("Play Last", selection_last),
+ .available = can_add),
+ RV_MENU_ENTRY(RV_MENU_NOW_PLAYING_CONTEXT, 0, RV_ROW_PUSH("Up Next", "queue"),
+ .available = available),
+ RV_MENU_ENTRY(RV_MENU_NOW_PLAYING_CONTEXT, 0, RV_ROW_PUSH("Clear Up Next", "clear"),
+ .available = upcoming),
+ RV_MENU_ENTRY(RV_MENU_MUSIC, RV_MUSIC_AUDIOBOOKS, RV_ROW_PUSH("Up Next", "queue"),
+ .shown_by = KEY_IN_MUSIC),
+ RV_MENU_ENTRY(RV_MENU_MAIN, RV_MAIN_AUDIOBOOKS, RV_ROW_PUSH("Up Next", "queue"),
+ .shown_by = KEY_IN_MAIN, .preview = RV_PREVIEW_MUSIC),
+};
+
+static const struct rv_setting settings[] = {
+ RV_SETTING_BOOL(KEY_IN_MUSIC, "Up Next in Music", 1),
+ RV_SETTING_BOOL(KEY_IN_MAIN, "Up Next in Main Menu", 0),
+};
+
+/* The old core's built-in Up Next row in its menu visibility record. */
+#define OLD_MENU_KEY 0x857127e6
+
+static int first_load = 1;
+
+static void changed(uint16_t key)
+{
+ if (key == RV_SETTING_KEY_ALL) {
+ int import = first_load;
+ first_load = 0;
+ migrate_menu_visibility(api, self, import, OLD_MENU_KEY, KEY_IN_MUSIC, 1,
+ KEY_IN_MAIN, 0);
+ }
+}
+
+static const struct rv_hook hooks[] = {
+ RV_HOOK_FILTER(RV_SITE_MediaPlayer_ToggleStopped_call, toggle_stopped),
+ RV_HOOK_FILTER(RV_SITE_MediaList_OnTheGoAdd_call, on_the_go_add),
+};
+
+static const struct rv_descriptor extension = {
+ .size = sizeof extension,
+ RV_HOOKS(hooks),
+ RV_SETTINGS(settings),
+ .setting_changed = changed,
+ RV_SCREENS(screens),
+ RV_ENTRIES(entries),
+};
+
+const struct rv_descriptor *rv_module_entry(const struct rv_api *core,
+ rv_extension_handle handle)
+{
+ api = core;
+ self = handle;
+ return &extension;
+}
diff --git a/extensions/playback-queue/manifest.toml b/extensions/playback-queue/manifest.toml
new file mode 100644
index 0000000..7343192
--- /dev/null
+++ b/extensions/playback-queue/manifest.toml
@@ -0,0 +1,16 @@
+id = "playback-queue"
+name = "Playback Queue"
+description = "Queue songs, albums, artists or podcast episodes with Play Next or Play Last. View and edit queued items at any time."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+stability = "beta"
+category = "media"
+
+[libraries]
+optional = ["reprise"]
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/playback-queue/queue.c b/extensions/playback-queue/queue.c
new file mode 100644
index 0000000..2323e7c
--- /dev/null
+++ b/extensions/playback-queue/queue.c
@@ -0,0 +1,510 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* The player's playing list: inserting after the current song or at the end,
+ * removing, moving, and making the player drop the track it prepared.
+ *
+ * Insertion adapted from RepriseOS payload/play_next.c and
+ * payload/queue_selection.c (34fad44, 11e5ba7, c997a51) by lgreitis and
+ * brilliant-alien. */
+
+#include "queue.h"
+#include "osos-2.0.5.h"
+#include "rv_api.h"
+#include "rv_libc.h"
+#include "rv_media.h"
+#include
+
+static void *view_of(void *player)
+{
+ return (uint8_t *)player + MediaPlayer_playback_view;
+}
+
+static struct MediaList *list_of(void *player)
+{
+ return RV_FIELD(view_of(player), MediaListView_list, struct MediaList *);
+}
+
+static struct MediaEntry *root_of(struct MediaList *list)
+{
+ return RV_FIELD(list, MediaList_root, struct MediaEntry *);
+}
+
+static uint32_t tracks_of(struct MediaList *list)
+{
+ return RV_FIELD(root_of(list), MediaEntry_tracks, uint16_t);
+}
+
+static uint32_t count_of(void *player)
+{
+ return tracks_of(list_of(player));
+}
+
+static int32_t *current_index(void *player)
+{
+ return &RV_FIELD(player, MediaPlayer_current_index, int32_t);
+}
+
+static int shuffled(struct MediaList *list)
+{
+ return RV_FIELD(list, MediaList_flags, uint8_t) & MediaListFlags_Shuffled;
+}
+
+static int reversed(struct MediaList *list)
+{
+ return (RV_FIELD(list, MediaList_order_flags, uint8_t) &
+ MediaListOrderFlags_Reversed) != 0;
+}
+
+static uint32_t rank_of(struct MediaEntry *entry)
+{
+ return RV_FIELD(entry, MediaEntry_song_shuffle_rank, uint32_t);
+}
+
+/* The current song when the list is a flat song list the queue can change. */
+static struct MediaEntry *current_entry(void *player)
+{
+ void *view = view_of(player);
+ if (!RV_FIELD(player, MediaPlayer_current_track, void *) ||
+ !MediaListView_IsValid(view))
+ return NULL;
+ struct MediaList *list = list_of(player);
+ uint32_t count = count_of(player);
+ if (!(RV_FIELD(list, MediaList_flags, uint8_t) & MediaListFlags_PlaybackList))
+ return NULL;
+ if (*current_index(player) < 0 || (uint32_t)*current_index(player) >= count)
+ return NULL;
+ struct MediaEntry *current =
+ PlaybackList_GetEntryByIndex(view, *current_index(player));
+ if (!current ||
+ RV_FIELD(current, MediaEntry_parent, struct MediaEntry *) != root_of(list) ||
+ (RV_FIELD(current, MediaEntry_flags, uint32_t) & MediaEntryFlags_Group))
+ return NULL;
+ if (shuffled(list)) {
+ void *order = RV_FIELD(list, MediaList_shuffle_index, void *);
+ if (!order || RV_FIELD(order, MediaOrder_count, uint32_t) != count)
+ return NULL;
+ }
+ return current;
+}
+
+static int editable(void *player)
+{
+ if (RV_FIELD(player, MediaPlayer_current_track, void *))
+ return current_entry(player) != NULL;
+ if (!MediaListView_IsValid(view_of(player)))
+ return 0;
+ struct MediaList *list = list_of(player);
+ if (!root_of(list) ||
+ !(RV_FIELD(list, MediaList_flags, uint8_t) & MediaListFlags_PlaybackList))
+ return 0;
+ uint32_t count = count_of(player);
+ if (count) {
+ struct MediaEntry *entry = PlaybackList_GetEntryByIndex(view_of(player), 0);
+ if (!entry ||
+ RV_FIELD(entry, MediaEntry_parent, struct MediaEntry *) != root_of(list) ||
+ (RV_FIELD(entry, MediaEntry_flags, uint32_t) & MediaEntryFlags_Group))
+ return 0;
+ }
+ if (shuffled(list) && count) {
+ void *order = RV_FIELD(list, MediaList_shuffle_index, void *);
+ if (!order || RV_FIELD(order, MediaOrder_count, uint32_t) != count)
+ return 0;
+ }
+ return 1;
+}
+
+static uint32_t first_pending(void *player)
+{
+ return RV_FIELD(player, MediaPlayer_current_track, void *)
+ ? (uint32_t)*current_index(player) + 1
+ : 0;
+}
+
+static uint32_t upcoming(void *player)
+{
+ return count_of(player) - first_pending(player);
+}
+
+static int prepare_queue(void *player)
+{
+ if (editable(player))
+ return 1;
+ if (RV_FIELD(player, MediaPlayer_current_track, void *))
+ return 0;
+ /* Native initialization attaches the list and playback source without
+ * loading a current track. Repeat 3 preserves the native preference. */
+ MediaPlayer_InitializePlaybackList(player, 0, 3);
+ return editable(player);
+}
+
+/* Artwork is indexed by list position: stopped before a change, rebuilt after. */
+static void stop_artwork(void *player)
+{
+ ArtworkSession_Stop((uint8_t *)player + MediaPlayer_artwork_session);
+}
+
+/* After a change the prepared next track may be the wrong one, and the source
+ * caches the track order. */
+static void changed(void *player)
+{
+ if (RV_FIELD(player, MediaPlayer_current_track, void *))
+ MediaPlayer_RebuildArtwork(player);
+ MediaPlayer_ClearPreparedTrack(player);
+ Audio_SetPlaybackSource(RV_FIELD(player, MediaPlayer_playback_source, void *));
+}
+
+/* A copy of `entry` that ends up at playback index `position`. */
+static struct MediaEntry *insert_at(void *player, struct MediaEntry *entry,
+ uint32_t position)
+{
+ struct MediaList *list = list_of(player);
+ uint32_t count = count_of(player);
+ int reverse = reversed(list);
+ uint32_t rank = reverse ? count - position : position;
+ struct MediaEntry *after =
+ reverse && !position
+ ? RV_FIELD(root_of(list), MediaEntry_group_last, struct MediaEntry *)
+ : NULL;
+ if (position) {
+ after = PlaybackList_GetEntryByIndex(view_of(player), position - 1);
+ if (reverse)
+ after = RV_FIELD(after, MediaEntry_previous, struct MediaEntry *);
+ }
+ struct MediaEntry *cursor[] = {root_of(list), after};
+
+ void *track_data = RV_FIELD(list, MediaList_track_data, void *);
+ TrackData_AcquireStringCaches(track_data);
+ if (shuffled(list)) {
+ /* The shuffle order sorts by rank; leave a gap at `rank`. */
+ void *order = RV_FIELD(list, MediaList_shuffle_index, void *);
+ struct MediaEntry **entries =
+ (struct MediaEntry **)((uint8_t *)order + MediaOrder_entries);
+ for (uint32_t i = 0; i < count; i++)
+ RV_FIELD(entries[i], MediaEntry_song_shuffle_rank, uint32_t) =
+ i + (i >= rank);
+ }
+ struct MediaEntry *inserted = MediaList_CopyEntryAtPosition(entry, list, cursor, 0);
+ if (inserted && shuffled(list)) {
+ RV_FIELD(inserted, MediaEntry_song_shuffle_rank, uint32_t) = rank;
+ /* Copy notifications may rebuild the order before the rank is set. */
+ MediaList_InvalidateOrderCache(list, MediaOrderMode_Shuffle);
+ }
+ TrackData_ReleaseStringCaches(track_data);
+ return inserted;
+}
+
+/* Removes the songs strictly between `from` and `to` in playback order, to the
+ * end when `to` is NULL. One pass over the list: each removal drops the order
+ * caches, so looking songs up by index in between would rebuild them every
+ * time. A removed entry is freed at once. */
+static void remove_between(struct MediaList *list, struct MediaEntry *from,
+ struct MediaEntry *to)
+{
+ int reverse = reversed(list);
+ if (shuffled(list)) {
+ /* Shuffled songs play by rank, descending when reversed. */
+ uint32_t start = from ? rank_of(from) : 0, end = to ? rank_of(to) : 0;
+ struct MediaEntry *entry =
+ RV_FIELD(root_of(list), MediaEntry_group_first, struct MediaEntry *);
+ while (entry) {
+ struct MediaEntry *next =
+ RV_FIELD(entry, MediaEntry_next, struct MediaEntry *);
+ uint32_t rank = rank_of(entry);
+ int between = reverse ? (!from || rank < start) && (!to || rank > end)
+ : (!from || rank > start) && (!to || rank < end);
+ if (between)
+ MediaEntry_Remove(entry);
+ entry = next;
+ }
+ } else {
+ uint32_t step = reverse ? MediaEntry_previous : MediaEntry_next;
+ struct MediaEntry *entry =
+ from ? RV_FIELD(from, step, struct MediaEntry *)
+ : RV_FIELD(root_of(list),
+ reverse ? MediaEntry_group_last : MediaEntry_group_first,
+ struct MediaEntry *);
+ while (entry && entry != to) {
+ struct MediaEntry *next = RV_FIELD(entry, step, struct MediaEntry *);
+ MediaEntry_Remove(entry);
+ entry = next;
+ }
+ }
+ MediaList_NotifyChanged(list);
+}
+
+/* Removes one song at playback index `index`, never the current one. */
+static void remove_one(void *player, uint32_t index)
+{
+ struct MediaEntry *entry = PlaybackList_GetEntryByIndex(view_of(player), index);
+ if (!entry)
+ return;
+ MediaEntry_Remove(entry);
+ MediaList_NotifyChanged(list_of(player));
+ if ((int32_t)index < *current_index(player))
+ --*current_index(player);
+}
+
+static struct MediaEntry *item_entry(struct MediaItem *item)
+{
+ struct MediaEntry *entry = RV_FIELD(item, MediaItem_entry, struct MediaEntry *);
+ void *record = RV_FIELD(item, MediaItem_record, void *);
+ if (!entry && record)
+ entry = RV_FIELD(record, MediaRecord_entries, struct MediaEntry *);
+ return entry;
+}
+
+static int is_queueable(struct MediaItem *item)
+{
+ struct MediaEntry *entry = item_entry(item);
+ return entry &&
+ !(RV_FIELD(entry, MediaEntry_flags, uint32_t) & MediaEntryFlags_Group) &&
+ !MediaItem_HasKind200000(item) && !MediaItem_HasKind8(item) &&
+ !MediaItem_HasKind8062(item);
+}
+
+int queue_available(void)
+{
+ void *player = rv_player_lock();
+ int available = editable(player);
+ rv_player_unlock(player);
+ return available;
+}
+
+int queue_can_add(void)
+{
+ void *player = rv_player_lock();
+ int allowed =
+ !RV_FIELD(player, MediaPlayer_current_track, void *) || editable(player);
+ rv_player_unlock(player);
+ return allowed;
+}
+
+int queue_can_add_item(const void *item)
+{
+ return item && is_queueable((struct MediaItem *)item) && queue_can_add();
+}
+
+int queue_start_idle(void)
+{
+ void *player = rv_player_lock();
+ int start = MediaPlayer_IsStopped(player) && editable(player) && upcoming(player);
+ if (start)
+ MediaPlayer_PlayIndex(player, first_pending(player), 0, 0, 0);
+ rv_player_unlock(player);
+ return start;
+}
+
+void queue_add_item(const void *item, int last)
+{
+ struct MediaItem *song = (struct MediaItem *)item;
+ void *player = rv_player_lock();
+ if (song && is_queueable(song) && prepare_queue(player)) {
+ uint32_t position = last ? count_of(player) : first_pending(player);
+ stop_artwork(player);
+ if (insert_at(player, item_entry(song), position))
+ changed(player);
+ else
+ MediaPlayer_RebuildArtwork(player);
+ }
+ rv_player_unlock(player);
+}
+
+void queue_add_browser(void *browser, int last)
+{
+ void *player = rv_player_lock();
+ struct MediaList *source = browser ? MediaBrowser_GetCurrentList(browser) : NULL;
+ if (!source || !root_of(source) || !prepare_queue(player)) {
+ rv_player_unlock(player);
+ return;
+ }
+ /* The songs and order Add to On-The-Go would take for this selection. */
+ MediaBrowser_BuildSongs(browser);
+ uint32_t mode =
+ shuffled(source) ? MediaOrderMode_Shuffle : MediaBrowser_GetOrderMode(browser);
+ uint32_t grouped = RV_FIELD(browser, MediaBrowser_order_flag, uint8_t) != 0;
+ uint32_t count = tracks_of(source);
+
+ stop_artwork(player);
+ int inserted = 0;
+ for (uint32_t i = 0; i < count; i++) {
+ /* Play Next puts each song right after the current one: walk backwards. */
+ uint32_t index = last ? i : count - 1 - i;
+ struct MediaEntry *entry =
+ MediaList_GetEntryByOrderIndex(source, mode, grouped, index);
+ if (!entry || !RV_FIELD(entry, MediaEntry_song_record, void *) ||
+ !MediaBrowser_EvaluateEntryFilters(browser, entry, source))
+ continue;
+ if (!editable(player))
+ break;
+ uint32_t position = last ? count_of(player) : first_pending(player);
+ if (insert_at(player, entry, position))
+ inserted = 1;
+ }
+ if (inserted)
+ changed(player);
+ else
+ MediaPlayer_RebuildArtwork(player);
+ rv_player_unlock(player);
+}
+
+uint32_t queue_rows(void)
+{
+ void *player = rv_player_lock();
+ uint32_t rows = editable(player) ? upcoming(player) : 0;
+ rv_player_unlock(player);
+ return rows;
+}
+
+int queue_changed(void)
+{
+ static void *last_list, *last_track;
+ static uint32_t last_count;
+ static int32_t last_index;
+ static uint8_t last_order;
+ void *player = rv_player_lock();
+ int valid = editable(player);
+ void *list = valid ? list_of(player) : NULL;
+ void *track = valid ? RV_FIELD(player, MediaPlayer_current_track, void *) : NULL;
+ uint32_t count = valid ? count_of(player) : 0;
+ int32_t index = valid ? *current_index(player) : -1;
+ uint8_t order = valid ? (shuffled(list) != 0) | (reversed(list) << 1) : 0;
+ int changed = list != last_list || track != last_track || count != last_count ||
+ index != last_index || order != last_order;
+ last_list = list;
+ last_track = track;
+ last_count = count;
+ last_index = index;
+ last_order = order;
+ rv_player_unlock(player);
+ return changed;
+}
+
+void queue_text(uint32_t row, int artist, char *out, uint32_t capacity)
+{
+ if (!capacity)
+ return;
+ out[0] = 0;
+ void *player = rv_player_lock();
+ if (editable(player) && row < upcoming(player)) {
+ _Alignas(uint32_t) uint8_t item[MediaItem_bytes];
+ _Alignas(uint32_t) uint8_t text[NativeString_bytes];
+ MediaItem_InitFromRecord((struct MediaItem *)item, NULL, 0);
+ if (MediaPlayer_GetItemAtIndex(player, first_pending(player) + row,
+ (struct MediaItem *)item)) {
+ const char *utf8 = rv_item_text(
+ item, artist ? MediaItem_artist_method : MediaItem_title_method,
+ (struct NativeString *)text);
+ rv_copy_utf8(out, capacity, utf8);
+ NativeString_Destroy((struct NativeString *)text);
+ }
+ MediaItem_Destroy((struct MediaItem *)item);
+ }
+ rv_player_unlock(player);
+}
+
+void queue_play(uint32_t row)
+{
+ void *player = rv_player_lock();
+ if (editable(player) && row < upcoming(player)) {
+ struct MediaEntry *current = current_entry(player);
+ uint32_t first = first_pending(player);
+ struct MediaEntry *selected =
+ PlaybackList_GetEntryByIndex(view_of(player), first + row);
+ if (selected) {
+ stop_artwork(player);
+ if (row)
+ remove_between(list_of(player), current, selected);
+ /* Keep the old current entry alive until Apple has saved its
+ * position and installed the selected track. */
+ if (MediaPlayer_PlayIndex(player, first, 0, 0, 0) && current)
+ remove_one(player, first - 1);
+ changed(player);
+ }
+ }
+ rv_player_unlock(player);
+}
+
+/* Playback can advance while a context menu is open. Never edit a different
+ * song that has since taken the captured row's place. */
+static struct MediaEntry *menu_entry;
+static struct MediaList *menu_list;
+
+int queue_capture(uint32_t row)
+{
+ void *player = rv_player_lock();
+ menu_entry = NULL;
+ menu_list = NULL;
+ if (editable(player) && row < upcoming(player)) {
+ menu_list = list_of(player);
+ menu_entry =
+ PlaybackList_GetEntryByIndex(view_of(player), first_pending(player) + row);
+ }
+ rv_player_unlock(player);
+ return menu_entry != NULL;
+}
+
+void *queue_record(uint32_t row)
+{
+ void *record = NULL;
+ void *player = rv_player_lock();
+ if (editable(player) && row < upcoming(player) && list_of(player) == menu_list &&
+ PlaybackList_GetEntryByIndex(view_of(player), first_pending(player) + row) ==
+ menu_entry) {
+ _Alignas(uint32_t) uint8_t item[MediaItem_bytes];
+ MediaItem_InitFromRecord((struct MediaItem *)item, NULL, 0);
+ if (MediaPlayer_GetItemAtIndex(player, first_pending(player) + row,
+ (struct MediaItem *)item))
+ record = RV_FIELD(item, MediaItem_record, void *);
+ MediaItem_Destroy((struct MediaItem *)item);
+ }
+ rv_player_unlock(player);
+ return record;
+}
+
+void queue_move(uint32_t from, uint32_t to)
+{
+ void *player = rv_player_lock();
+ if (editable(player) && from != to && from < upcoming(player) &&
+ to < upcoming(player)) {
+ uint32_t first = first_pending(player);
+ struct MediaEntry *entry =
+ PlaybackList_GetEntryByIndex(view_of(player), first + from);
+ if (list_of(player) != menu_list || entry != menu_entry) {
+ rv_player_unlock(player);
+ return;
+ }
+ stop_artwork(player);
+ /* A copy at the new place, then the original goes. */
+ if (insert_at(player, entry, first + to + (to > from))) {
+ MediaEntry_Remove(entry);
+ MediaList_NotifyChanged(list_of(player));
+ }
+ changed(player);
+ }
+ rv_player_unlock(player);
+}
+
+void queue_remove(uint32_t row)
+{
+ void *player = rv_player_lock();
+ if (editable(player) && row < upcoming(player) && list_of(player) == menu_list &&
+ PlaybackList_GetEntryByIndex(view_of(player), first_pending(player) + row) ==
+ menu_entry) {
+ stop_artwork(player);
+ remove_one(player, first_pending(player) + row);
+ changed(player);
+ }
+ rv_player_unlock(player);
+}
+
+void queue_clear(void)
+{
+ void *player = rv_player_lock();
+ struct MediaEntry *current = current_entry(player);
+ if (editable(player) && upcoming(player)) {
+ stop_artwork(player);
+ remove_between(list_of(player), current, NULL);
+ changed(player);
+ }
+ rv_player_unlock(player);
+}
diff --git a/extensions/playback-queue/queue.h b/extensions/playback-queue/queue.h
new file mode 100644
index 0000000..d2876ff
--- /dev/null
+++ b/extensions/playback-queue/queue.h
@@ -0,0 +1,56 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+#ifndef PLAYBACK_QUEUE_H
+#define PLAYBACK_QUEUE_H
+
+#include
+
+/* The native playback list, from the UI task. Queue access takes the player lock. */
+
+/* Whether the player has a list the queue can change, including an idle list. */
+int queue_available(void);
+int queue_can_add(void);
+int queue_can_add_item(const void *item);
+int queue_start_idle(void);
+
+/* Inserts a supported context item at the first pending position, or at the
+ * end with `last`. Creates an idle native list when needed. */
+void queue_add_item(const void *item, int last);
+
+/* Inserts the songs of an album or artist selection as Add to On-The-Go would
+ * add them; `browser` is what Apple hands to the On-The-Go playlist. */
+void queue_add_browser(void *browser, int last);
+
+/* Pending items, starting at row 0: all items when idle, otherwise those
+ * after the current one. */
+uint32_t queue_rows(void);
+
+/* Whether the playback list, current track, position, count or order changed since
+ * the previous check. Called on the UI task while Up Next is open. */
+int queue_changed(void);
+
+/* Title (or artist with `artist`) of row `row` into `out`, empty for a missing
+ * row. Capacity includes the terminator; UTF-8 characters are kept whole. */
+void queue_text(uint32_t row, int artist, char *out, uint32_t capacity);
+
+/* Plays row `row`: the songs before it, the current one included,
+ * leave the list. Earlier songs stay, so Previous still reaches them. */
+void queue_play(uint32_t row);
+
+/* Captures the row a context menu opens on; 0 for a missing row. */
+int queue_capture(uint32_t row);
+
+/* The media record of upcoming row `row`, if it still names the captured
+ * entry; NULL otherwise. */
+void *queue_record(uint32_t row);
+
+/* Upcoming row `from` to row `to`, if it still names the captured entry. */
+void queue_move(uint32_t from, uint32_t to);
+
+/* Removes upcoming row `row`. */
+void queue_remove(uint32_t row);
+
+/* Removes all pending items, preserving the current item and earlier history. */
+void queue_clear(void);
+
+#endif
diff --git a/extensions/playback-queue/screenshots/clear.png b/extensions/playback-queue/screenshots/clear.png
new file mode 100644
index 0000000..6efcf14
Binary files /dev/null and b/extensions/playback-queue/screenshots/clear.png differ
diff --git a/extensions/playback-queue/screenshots/item-menu.png b/extensions/playback-queue/screenshots/item-menu.png
new file mode 100644
index 0000000..ff8e694
Binary files /dev/null and b/extensions/playback-queue/screenshots/item-menu.png differ
diff --git a/extensions/playback-queue/screenshots/up-next.png b/extensions/playback-queue/screenshots/up-next.png
new file mode 100644
index 0000000..2e819e4
Binary files /dev/null and b/extensions/playback-queue/screenshots/up-next.png differ
diff --git a/extensions/reprise/manifest.toml b/extensions/reprise/manifest.toml
new file mode 100644
index 0000000..f4b6f12
--- /dev/null
+++ b/extensions/reprise/manifest.toml
@@ -0,0 +1,15 @@
+id = "reprise"
+name = "RepriseOS"
+description = "RepriseOS services its core provides to extensions. Nothing to install: list it under [libraries] optional."
+version = "0.1.0"
+author = "RepriseOS contributors"
+license = "GPL-3.0-only"
+api = "1.89"
+category = "library"
+exports = [
+ "reprise_legacy_preference",
+]
+
+[[module]]
+name = "main"
+trigger = "always"
diff --git a/extensions/reprise/reprise.h b/extensions/reprise/reprise.h
new file mode 100644
index 0000000..ab186bf
--- /dev/null
+++ b/extensions/reprise/reprise.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+
+/* What the RepriseOS core exports as the library `reprise`. There is no
+ * reprise.rvx: the core answers the id itself. List it under
+ * `[libraries] optional`, so the extension also runs on other cores, where
+ * these stay NULL; call them through RV_OPTIONAL or test them first. */
+
+#ifndef REPRISE_H
+#define REPRISE_H
+#include
+
+/* Copies the stored value of an old firmware preference `key` into `data`
+ * and returns its size, 0 when absent; at most `capacity` bytes. */
+uint32_t (reprise_legacy_preference)(uint32_t key, void *data, uint32_t capacity);
+
+#endif
diff --git a/extensions/shared/legacy.h b/extensions/shared/legacy.h
index 974435c..474e871 100644
--- a/extensions/shared/legacy.h
+++ b/extensions/shared/legacy.h
@@ -1,20 +1,22 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include "rv_api.h"
+#include "../reprise/reprise.h"
/* Only the initial load imports the old firmware switch. A later reset records
- * the extension default so rebooting cannot resurrect the old preference. */
+ * the extension default so rebooting cannot resurrect the old preference. On a
+ * core without the reprise library nothing is imported. */
static inline void migrate_switch(const struct rv_api *api, rv_extension_handle self,
int first_load, uint16_t key, uint32_t old_key,
uint32_t old_on, int on, int off, uint8_t type)
{
uint32_t value;
- if (!rv_has_reprise_services(api) ||
+ if (!reprise_legacy_preference ||
api->setting_read(self, key, &value, sizeof value) == sizeof value)
return;
int32_t mode = off;
if (first_load &&
- api->legacy_preference(old_key, &value, sizeof value) == sizeof value &&
+ (reprise_legacy_preference)(old_key, &value, sizeof value) == sizeof value &&
value == old_on)
mode = on;
api->setting_write(self, key, type, &mode, sizeof mode);
diff --git a/extensions/shared/menu_visibility.h b/extensions/shared/menu_visibility.h
new file mode 100644
index 0000000..24f5414
--- /dev/null
+++ b/extensions/shared/menu_visibility.h
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#pragma once
+#include "rv_api.h"
+#include "../reprise/reprise.h"
+
+/* The old core kept the Main and Music menu checkboxes of its own rows in one
+ * record, "MVIS": {key, visible} pairs, bit 0 Main and bit 1 Music. Only the
+ * initial load imports the row's pair; without one, and on a later reset, the
+ * extension defaults are recorded so rebooting cannot resurrect the old value.
+ * On a core without the reprise library nothing is imported. */
+static inline void migrate_menu_visibility(const struct rv_api *api,
+ rv_extension_handle self, int first_load,
+ uint32_t old_key, uint16_t music_key,
+ int music_default, uint16_t main_key,
+ int main_default)
+{
+ uint32_t value;
+ if (!reprise_legacy_preference ||
+ api->setting_read(self, music_key, &value, sizeof value) == sizeof value ||
+ api->setting_read(self, main_key, &value, sizeof value) == sizeof value)
+ return;
+ int32_t music = music_default, main = main_default;
+ uint32_t pairs[16];
+ uint32_t bytes =
+ first_load ? (reprise_legacy_preference)(0x5349564d, pairs, sizeof pairs) : 0;
+ for (uint32_t i = 0; i + 1 < bytes / 4; i += 2)
+ if (pairs[i] == old_key && pairs[i + 1] <= 3) {
+ music = (pairs[i + 1] >> 1) & 1;
+ main = pairs[i + 1] & 1;
+ break;
+ }
+ api->setting_write(self, music_key, RV_SETTING_TYPE_BOOL, &music, sizeof music);
+ api->setting_write(self, main_key, RV_SETTING_TYPE_BOOL, &main, sizeof main);
+}
diff --git a/tests/test_catalog.py b/tests/test_catalog.py
index fd4de66..94c96a8 100644
--- a/tests/test_catalog.py
+++ b/tests/test_catalog.py
@@ -40,8 +40,9 @@ def test_preview_packages_and_referenced_images(self):
for entry in entries.values():
assets = [entry["package"]]
if entry["category"] != "library":
- self.assertTrue(entry["screenshots"][0]["alt"])
- self.assertEqual(entry["screenshots"][0]["width"], 320)
+ for shot in entry["screenshots"]:
+ self.assertTrue(shot["alt"])
+ self.assertEqual(shot["width"], 320)
assets += [entry["icon"], *entry["screenshots"]]
for asset in assets:
data = (self.out / asset["url"]).read_bytes()
@@ -55,7 +56,7 @@ def test_remote_release_and_failed_update_retains_all_assets(self):
folder = catalog.ROOT / source["path"]
package = (self.packages / "balance.rvx").read_bytes()
release = {
- "tag_name": "balance/v0.1.0",
+ "tag_name": "balance/v0.1.1",
"published_at": "2026-11-24T00:00:00Z",
"assets": [
{"name": "balance.rvx", "size": len(package), "state": "uploaded"}
@@ -77,7 +78,7 @@ def download(url, limit):
):
self.assertEqual(catalog.generate(sources, self.out, catalog.remote), [])
before = self.entries()
- release["tag_name"] = "balance/v0.1.1"
+ release["tag_name"] = "balance/v0.1.2"
self.assertTrue(catalog.generate(sources, self.out, catalog.remote))
self.assertEqual(before, self.entries())
self.assertTrue((self.out / before["balance"]["package"]["url"]).exists())
@@ -182,7 +183,7 @@ def test_corrupt_package_is_rejected(self):
catalog.snapshot(
"balance",
source,
- "0.1.0",
+ "0.1.1",
lambda path: (folder / path).read_bytes(),
package,
None,
diff --git a/tools/catalog.py b/tools/catalog.py
index 4c698d2..a099275 100644
--- a/tools/catalog.py
+++ b/tools/catalog.py
@@ -162,7 +162,7 @@ def image(filename):
entry.update(
category=manifest.category(doc),
api=doc["api"],
- requires=manifest.requires(doc),
+ requires=manifest.libraries(doc)[0],
firmware_id=f"{header['firmware']:08x}",
repo=source["repo"],
source_path=source.get("path", ""),
@@ -359,7 +359,7 @@ def local_manifest(identifier, source):
doc = tomllib.loads((folder / "manifest.toml").read_text())
if doc["id"] != identifier or not (folder / "listing.toml").is_file():
raise ValueError(f"{identifier}: expected matching local manifest and listing")
- return {"category": manifest.category(doc), "requires": manifest.requires(doc)}
+ return {"category": manifest.category(doc), "requires": manifest.libraries(doc)[0]}
def review(sources, previous, body=None, index=None):