From dbd026ca648dd1028b1b3716e811ad23da36d578 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Wed, 25 Nov 2026 18:42:00 +0000 Subject: [PATCH 01/20] feat: add the reprise library stub The RepriseOS core answers the library id reprise itself. Its manifest and header let rv.mk build extensions that import from it; there is no reprise.rvx. --- extensions/reprise/manifest.toml | 16 ++++++++++++++++ extensions/reprise/reprise.h | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 extensions/reprise/manifest.toml create mode 100644 extensions/reprise/reprise.h diff --git a/extensions/reprise/manifest.toml b/extensions/reprise/manifest.toml new file mode 100644 index 0000000..adc41ce --- /dev/null +++ b/extensions/reprise/manifest.toml @@ -0,0 +1,16 @@ +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.84" +category = "library" +exports = [ + "reprise_legacy_preference", + "reprise_album_artist_read", +] + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/reprise/reprise.h b/extensions/reprise/reprise.h new file mode 100644 index 0000000..20dd966 --- /dev/null +++ b/extensions/reprise/reprise.h @@ -0,0 +1,19 @@ +/* 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); +/* Copies the album artist of a library record as UTF-16 units into `text` and + * returns how many, at most `capacity`. */ +uint32_t (reprise_album_artist_read)(void *record, uint16_t *text, uint32_t capacity); + +#endif From e7346c2dcab2253e7827365e9add0cf4b2ac228a Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Wed, 25 Nov 2026 18:42:00 +0000 Subject: [PATCH 02/20] feat: use the reprise library when the core provides it SDK 1.84 drops the RepriseOS slots from rv_api and lists libraries in a [libraries] table. Night Shift, Crossfeed and Playback Log list reprise as an optional library. On a core without it they skip the settings migration, and Playback Log leaves the album artist empty instead of refusing to load. Crossfeed lists dsp as required, and the catalog keeps listing the required ids as requires. All three get a patch release. --- extensions/crossfeed/manifest.toml | 9 ++++++--- extensions/dsp/rv_dsp.h | 2 +- extensions/night-shift/manifest.toml | 7 +++++-- extensions/playback-log/main.c | 4 +--- extensions/playback-log/manifest.toml | 7 +++++-- extensions/playback-log/test.c | 14 ++++++++++++-- extensions/shared/legacy.h | 8 +++++--- tools/catalog.py | 4 ++-- 8 files changed, 37 insertions(+), 18 deletions(-) diff --git a/extensions/crossfeed/manifest.toml b/extensions/crossfeed/manifest.toml index 1109dc6..4813240 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.84" stability = "beta" category = "effects" -requires = ["dsp"] + +[libraries] +required = ["dsp"] +optional = ["reprise"] [[module]] name = "main" 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/night-shift/manifest.toml b/extensions/night-shift/manifest.toml index fd37372..0173f6e 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.84" category = "system" +[libraries] +optional = ["reprise"] + [[module]] name = "main" trigger = "always" diff --git a/extensions/playback-log/main.c b/extensions/playback-log/main.c index 81db894..f369469 100644 --- a/extensions/playback-log/main.c +++ b/extensions/playback-log/main.c @@ -119,7 +119,7 @@ static void field_media_text(struct osos_media_item *item, enum osos_media_text osos_media_item_text(item, field, &string); } else { uint16_t text[255]; - uint32_t units = api->album_artist_read(item->record, text, 255); + uint32_t units = RV_OPTIONAL(reprise_album_artist_read, 0, item->record, text, 255); osos_native_string_assign_utf16(&string, text, units); } const char *text = osos_native_string_data(&string); @@ -657,8 +657,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..73fb9a2 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.2" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.82" +api = "1.84" 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..2a24e0f 100644 --- a/extensions/playback-log/test.c +++ b/extensions/playback-log/test.c @@ -138,6 +138,9 @@ 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 +#pragma weak reprise_album_artist_read #include "main.c" enum { FINISH, COMPLETE }; @@ -168,7 +171,15 @@ 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)key; + (void)data; + (void)capacity; + return 0; +} + +uint32_t (reprise_album_artist_read)(void *r, uint16_t *s, uint32_t n) { (void)r; (void)s; @@ -194,7 +205,6 @@ int main(void) { static const struct rv_api mock = { .hook_next = mock_next, - .album_artist_read = read_artist, .setting_get_int = mock_enabled, }; api = &mock; 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/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): From 9d0443e7789cf0b13f38f63a70d18335dc5c583c Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Thu, 26 Nov 2026 18:41:18 +0000 Subject: [PATCH 03/20] feat: build against API 1.86 rv_row and rv_menu_entry grew in SDK 1.86, so a core at that API refuses images an older SDK packed, and the SDK refuses a manifest api below 1.86. Every manifest asks for 1.86. Balance and dsp get a patch release with the rebuild, 0.1.1 each, beside Crossfeed 0.1.1, Night Shift 0.1.3 and Playback Log 0.1.2; reprise stays 0.1.0, it has no release. --- extensions/balance/manifest.toml | 4 ++-- extensions/crossfeed/manifest.toml | 2 +- extensions/dsp/manifest.toml | 4 ++-- extensions/night-shift/manifest.toml | 2 +- extensions/playback-log/manifest.toml | 2 +- extensions/reprise/manifest.toml | 2 +- tests/test_catalog.py | 6 +++--- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/extensions/balance/manifest.toml b/extensions/balance/manifest.toml index 2e4aa37..d0d54db 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.86" stability = "beta" category = "effects" diff --git a/extensions/crossfeed/manifest.toml b/extensions/crossfeed/manifest.toml index 4813240..4e6777d 100644 --- a/extensions/crossfeed/manifest.toml +++ b/extensions/crossfeed/manifest.toml @@ -5,7 +5,7 @@ version = "0.1.1" author = "RevolaOS" note = "Ported from Rockbox" license = "GPL-3.0-only" -api = "1.84" +api = "1.86" stability = "beta" category = "effects" diff --git a/extensions/dsp/manifest.toml b/extensions/dsp/manifest.toml index c1657c3..fa8adf8 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.86" stability = "beta" category = "library" exports = [ diff --git a/extensions/night-shift/manifest.toml b/extensions/night-shift/manifest.toml index 0173f6e..57d70d1 100644 --- a/extensions/night-shift/manifest.toml +++ b/extensions/night-shift/manifest.toml @@ -4,7 +4,7 @@ description = "Warm the display manually or follow sunset and sunrise in the iPo version = "0.1.3" author = "RepriseOS and RevolaOS contributors" license = "GPL-3.0-only" -api = "1.84" +api = "1.86" category = "system" [libraries] diff --git a/extensions/playback-log/manifest.toml b/extensions/playback-log/manifest.toml index 73fb9a2..ed2f635 100644 --- a/extensions/playback-log/manifest.toml +++ b/extensions/playback-log/manifest.toml @@ -4,7 +4,7 @@ description = "Write a scrobbler log and optional detailed listening reports." version = "0.1.2" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.84" +api = "1.86" category = "media" [libraries] diff --git a/extensions/reprise/manifest.toml b/extensions/reprise/manifest.toml index adc41ce..d49691f 100644 --- a/extensions/reprise/manifest.toml +++ b/extensions/reprise/manifest.toml @@ -4,7 +4,7 @@ description = "RepriseOS services its core provides to extensions. Nothing to in version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.84" +api = "1.86" category = "library" exports = [ "reprise_legacy_preference", diff --git a/tests/test_catalog.py b/tests/test_catalog.py index fd4de66..922385a 100644 --- a/tests/test_catalog.py +++ b/tests/test_catalog.py @@ -55,7 +55,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 +77,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 +182,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, From 25b991bfa6174a945591c80eec78117342379654 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 01:36:51 +0000 Subject: [PATCH 04/20] feat: build against API 1.89 rv_pane grew in SDK 1.89, so a core at that API refuses images an older SDK packed, and the SDK refuses a manifest api below 1.89. Every manifest asks for 1.89. The versions stay: the 1.86 rebuilds have not been released. --- extensions/balance/manifest.toml | 2 +- extensions/crossfeed/manifest.toml | 2 +- extensions/dsp/manifest.toml | 2 +- extensions/night-shift/manifest.toml | 2 +- extensions/playback-log/manifest.toml | 2 +- extensions/reprise/manifest.toml | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/extensions/balance/manifest.toml b/extensions/balance/manifest.toml index d0d54db..635b3c2 100644 --- a/extensions/balance/manifest.toml +++ b/extensions/balance/manifest.toml @@ -4,7 +4,7 @@ description = "Shift the sound towards the left or right ear in decibel steps, o version = "0.1.1" author = "RevolaOS" license = "GPL-3.0-only" -api = "1.86" +api = "1.89" stability = "beta" category = "effects" diff --git a/extensions/crossfeed/manifest.toml b/extensions/crossfeed/manifest.toml index 4e6777d..1449cb3 100644 --- a/extensions/crossfeed/manifest.toml +++ b/extensions/crossfeed/manifest.toml @@ -5,7 +5,7 @@ version = "0.1.1" author = "RevolaOS" note = "Ported from Rockbox" license = "GPL-3.0-only" -api = "1.86" +api = "1.89" stability = "beta" category = "effects" diff --git a/extensions/dsp/manifest.toml b/extensions/dsp/manifest.toml index fa8adf8..14b074b 100644 --- a/extensions/dsp/manifest.toml +++ b/extensions/dsp/manifest.toml @@ -5,7 +5,7 @@ version = "0.1.1" author = "RevolaOS" note = "Partly adapted from RepriseOS" license = "GPL-3.0-only" -api = "1.86" +api = "1.89" stability = "beta" category = "library" exports = [ diff --git a/extensions/night-shift/manifest.toml b/extensions/night-shift/manifest.toml index 57d70d1..f6f6e5b 100644 --- a/extensions/night-shift/manifest.toml +++ b/extensions/night-shift/manifest.toml @@ -4,7 +4,7 @@ description = "Warm the display manually or follow sunset and sunrise in the iPo version = "0.1.3" author = "RepriseOS and RevolaOS contributors" license = "GPL-3.0-only" -api = "1.86" +api = "1.89" category = "system" [libraries] diff --git a/extensions/playback-log/manifest.toml b/extensions/playback-log/manifest.toml index ed2f635..77324e3 100644 --- a/extensions/playback-log/manifest.toml +++ b/extensions/playback-log/manifest.toml @@ -4,7 +4,7 @@ description = "Write a scrobbler log and optional detailed listening reports." version = "0.1.2" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.86" +api = "1.89" category = "media" [libraries] diff --git a/extensions/reprise/manifest.toml b/extensions/reprise/manifest.toml index d49691f..dd8d996 100644 --- a/extensions/reprise/manifest.toml +++ b/extensions/reprise/manifest.toml @@ -4,7 +4,7 @@ description = "RepriseOS services its core provides to extensions. Nothing to in version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.86" +api = "1.89" category = "library" exports = [ "reprise_legacy_preference", From d5a32c0d36c629d91e7d72d4af606edf0e7e86a7 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Thu, 26 Nov 2026 05:21:52 +0000 Subject: [PATCH 05/20] feat: add Album Artists, File Info and Playback Queue The three features that leave the RepriseOS core, as extensions: the library by Album Artist with Artist as the fallback, and a service that reads a record's Album Artist; an item's tags and file properties from its context menu, with a service other extensions open it through; and Play Next, Play Last and Up Next with move, remove, browse and Clear Up Next. shared/menu_visibility.h takes the Main and Music Menu checkboxes over from the old core's MVIS record on first start. The root Makefile, the catalog sources and the README list them; .gitignore covers the per-extension build directories. --- .gitignore | 2 +- Makefile | 5 +- NOTICE | 8 +- README.md | 3 + catalog/sources.toml | 15 + extensions/album-artists/Makefile | 3 + extensions/album-artists/README.md | 21 + .../assets/LICENSE.cupertino-icons | 20 + .../assets/settings-album-artists.png | Bin 0 -> 1261 bytes .../assets/settings-album-artists.svg | 5 + extensions/album-artists/browser.c | 928 ++++++++++++++++++ extensions/album-artists/browser.h | 44 + extensions/album-artists/fields.c | 290 ++++++ extensions/album-artists/fields.h | 36 + extensions/album-artists/listing.toml | 11 + extensions/album-artists/main.c | 132 +++ extensions/album-artists/manifest.toml | 16 + .../album-artists/screenshots/albums.png | Bin 0 -> 17553 bytes extensions/album-artists/screenshots/list.png | Bin 0 -> 7015 bytes extensions/album-artists/service.h | 17 + extensions/album-artists/shared.h | 22 + .../album-artists/tests/browser_contracts.c | 536 ++++++++++ extensions/album-artists/tests/contracts.c | 329 +++++++ extensions/album-artists/tests/run.py | 51 + extensions/file-info/Makefile | 3 + extensions/file-info/README.md | 33 + .../file-info/assets/LICENSE.cupertino-icons | 20 + .../file-info/assets/settings-file-info.png | Bin 0 -> 1287 bytes .../file-info/assets/settings-file-info.svg | 5 + extensions/file-info/info.c | 390 ++++++++ extensions/file-info/info.h | 17 + extensions/file-info/listing.toml | 11 + extensions/file-info/main.c | 122 +++ extensions/file-info/manifest.toml | 13 + .../file-info/screenshots/context-menu.png | Bin 0 -> 10195 bytes extensions/file-info/screenshots/song.png | Bin 0 -> 11807 bytes extensions/file-info/service.h | 16 + extensions/file-info/tests/contracts.c | 489 +++++++++ extensions/file-info/tests/run.py | 49 + extensions/playback-queue/Makefile | 3 + extensions/playback-queue/README.md | 27 + .../assets/LICENSE.cupertino-icons | 20 + .../assets/settings-playback-queue.png | Bin 0 -> 1005 bytes .../assets/settings-playback-queue.svg | 5 + extensions/playback-queue/listing.toml | 15 + extensions/playback-queue/main.c | 428 ++++++++ extensions/playback-queue/manifest.toml | 16 + extensions/playback-queue/queue.c | 510 ++++++++++ extensions/playback-queue/queue.h | 56 ++ .../playback-queue/screenshots/clear.png | Bin 0 -> 10170 bytes .../playback-queue/screenshots/item-menu.png | Bin 0 -> 9742 bytes .../playback-queue/screenshots/up-next.png | Bin 0 -> 16119 bytes extensions/shared/menu_visibility.h | 34 + 53 files changed, 4773 insertions(+), 3 deletions(-) create mode 100644 extensions/album-artists/Makefile create mode 100644 extensions/album-artists/README.md create mode 100644 extensions/album-artists/assets/LICENSE.cupertino-icons create mode 100644 extensions/album-artists/assets/settings-album-artists.png create mode 100644 extensions/album-artists/assets/settings-album-artists.svg create mode 100644 extensions/album-artists/browser.c create mode 100644 extensions/album-artists/browser.h create mode 100644 extensions/album-artists/fields.c create mode 100644 extensions/album-artists/fields.h create mode 100644 extensions/album-artists/listing.toml create mode 100644 extensions/album-artists/main.c create mode 100644 extensions/album-artists/manifest.toml create mode 100644 extensions/album-artists/screenshots/albums.png create mode 100644 extensions/album-artists/screenshots/list.png create mode 100644 extensions/album-artists/service.h create mode 100644 extensions/album-artists/shared.h create mode 100644 extensions/album-artists/tests/browser_contracts.c create mode 100644 extensions/album-artists/tests/contracts.c create mode 100644 extensions/album-artists/tests/run.py create mode 100644 extensions/file-info/Makefile create mode 100644 extensions/file-info/README.md create mode 100644 extensions/file-info/assets/LICENSE.cupertino-icons create mode 100644 extensions/file-info/assets/settings-file-info.png create mode 100644 extensions/file-info/assets/settings-file-info.svg create mode 100644 extensions/file-info/info.c create mode 100644 extensions/file-info/info.h create mode 100644 extensions/file-info/listing.toml create mode 100644 extensions/file-info/main.c create mode 100644 extensions/file-info/manifest.toml create mode 100644 extensions/file-info/screenshots/context-menu.png create mode 100644 extensions/file-info/screenshots/song.png create mode 100644 extensions/file-info/service.h create mode 100644 extensions/file-info/tests/contracts.c create mode 100644 extensions/file-info/tests/run.py create mode 100644 extensions/playback-queue/Makefile create mode 100644 extensions/playback-queue/README.md create mode 100644 extensions/playback-queue/assets/LICENSE.cupertino-icons create mode 100644 extensions/playback-queue/assets/settings-playback-queue.png create mode 100644 extensions/playback-queue/assets/settings-playback-queue.svg create mode 100644 extensions/playback-queue/listing.toml create mode 100644 extensions/playback-queue/main.c create mode 100644 extensions/playback-queue/manifest.toml create mode 100644 extensions/playback-queue/queue.c create mode 100644 extensions/playback-queue/queue.h create mode 100644 extensions/playback-queue/screenshots/clear.png create mode 100644 extensions/playback-queue/screenshots/item-menu.png create mode 100644 extensions/playback-queue/screenshots/up-next.png create mode 100644 extensions/shared/menu_visibility.h 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..1bdbd3c 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 crossfeed dsp file-info night-shift playback-log \ + playback-queue .PHONY: all $(extensions) all: $(extensions) @@ -13,9 +14,11 @@ $(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/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..113d9c8 100644 --- a/NOTICE +++ b/NOTICE @@ -4,7 +4,13 @@ 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. 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..b8fa8e0 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,9 @@ 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/). 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..3ef89f3 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -22,3 +22,18 @@ 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" 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 0000000000000000000000000000000000000000..81097bb73484bbe0f09db716b1d8f0ec554ebed7 GIT binary patch literal 1261 zcmVv000EENklp>b=^dA>oN6G#0eS?r(0a^jG`H6gy>chyshoOl4Qr|B?N@*qlYA zkPJAAPPDW&gng7ENEKY&{AtfkA_#olua%LwgoLqgN5G~d?x1e}pEn(p`W4v`I?yM<{7inxAQ8IBaVX?{-AG??5 z?`X9)Gl0qeBz7CRc{yxBntkx| z=*?TVevQ;-QK_6KOip#jPuF@HODt%d%Y3o6@nlt@lSu7+B7{IeVbDqM`hc^F4xaok zhb2gRDiCI;FBrj|n zu;PyQOwA_EbcW%148+pr$n-2Cdihwc;c*>(=Je2v!gS9e8*Fh##pTJFM@^4>S}LgD z^7}p-ol+XCgy#?$I3Bq%wTI}XutRn4Hw;fIO|)i%G{RrkH@UZHN4X83&R!9TB7S%Q zj*h#!H;Oa~K6sR?BoG3ku{5K4m2H`&MF!8SJ_v&FL8k zuMswnvUoGFTn3e@8!dR#5jOd0PFp?c7?MG)CHnITLS%c$0x4K_W~s29ue$Sa`FMW5^WB?tmakiXuq@?F|3~`~Zdtpr7Vy zqeqZ?ju3!Szcnb9<5+rELO@b9O{F>$aH(uz&@aLz#L8ioN+} + + + + 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..2fd5150 --- /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.85" +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 0000000000000000000000000000000000000000..b340477b390c76351b4dbe733e885142404a6c89 GIT binary patch literal 17553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g7(KBfSCtAr%%6b;yGCwBh^B83(y}F|4NOkf5Z)kl zXT=QT6Dqa8xgs%GxIVufc=Wo_OQRNI=DOKETwlt2A#=bBU#oOlYLq0j7rdgeYx)rmfxsH-x3Trb#!-8c~+|EgRMa9kWQC25+*|;JSJ^!1`(9mt zZuxi7D!>aWov}n!5)J;dnOsH7OxH!l~agd3o{=eeIQxFqE-a?n2ZEzoNmA zBaQG}%225{eWGBP_&T?%OETaB)$stPB_Rxk_8m~6q%_ZT|lRI_OTq}r&hr?U&b@&VRV|H?$t+w6|g3X zIZNJjv`{i3&DM?W^o6U+Ces0GA^D#R@_+-b4Ra8xd@FMFg=r%!bkb0N|75I8_G)H@ z+Nu`24pSiH{k@mZ%A-T$UAY-uG2nh0r6LCN_rS(~Fa z1BMDdLRGG_P25#`%I{lAtESS`P+7o;QjVNW=I)AzyFqQ1S15Y2zc8PRBUn;Ue4V`K zGwe%!Z;BaQw*-=-JYS(=o6Id=B7)_x~J}bP^IcWaq6yPa$!k+7ccJGVkR8+K{75i@|o^2 z;QV{{``*u9TX#SBb>{k&vYWt^;<$Hjgs;ffNo8B}b)$pVrA|n#yczlPYF?=8wN(t(1A$qitl#$6{r}oT${!dF<9Zh98fn^B;gQu&X%Q~loCIFWx BGsFM@ literal 0 HcmV?d00001 diff --git a/extensions/album-artists/screenshots/list.png b/extensions/album-artists/screenshots/list.png new file mode 100644 index 0000000000000000000000000000000000000000..b74540a255e9713606305a8241b0e065ea38d319 GIT binary patch literal 7015 zcmb7pcQjmG+xH+OAtOYC)Tt?NQG!4qYE2FJLlB5W z3HZNtg%tQb*S#YL0x=6~!v8Y#N#B@pv12x_r`VE&2(g61qMI?`+SmNTChV9lF1?gr zDhz%tl$H@Hl-L!Fg*cUEL&)gnm$I3lE~EO_i3a0l)Kw@->PPSYqV$X-m4qL^wz=`J zF1^P88fYtC4j)ZQam3mVYmaK5mw<5e?i^WlFz46EynMt~P}d;MaqHL> z{y;=aZO824W}U)OQ6DMYeT4v8fs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RQ9 zCxF6$?=OIjkm5CF8~2J*EG1>_bJKSmTT&*(db!aextension_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/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 0000000000000000000000000000000000000000..eef5690df265a46f917cc2130aa40156684c2a5f GIT binary patch literal 1287 zcmV+i1^D`jP)v000EeNklJ<0O+)&Wzvi-8SuqkoG zM2#2_r6{bzWFUj!cvyikMFuG7P~yhaWq-!F@3n((?;1W=e%OBK>nHO4ly{D6xu;4b zF)=a!6=KP1QyP=q<@r~RULsNHqK?UuHht0FGZHd;d6zn1&6ieAj^o;+%gYWr-yr_YvKsAO}y=4U>MrYFxIdxH6$%RPE>??@Cq z)oT+An8$}uZf;>=`iM<*PggYi2WB4S%6?n?ajMcP6`3Q;?mxynJcx2=_169rkv-Bo zJCB*GU~|FMv2u|;(tGa_<^h-ERv(Uv?2+E-In3L5C*_SM)N0v@Kz|5fB(rQ3d zk1YN5KIZO6D7Uow)81tGL53`un88dRU~|h?2SxPAlJUEkNj4XUtqyoC&>s2T?P<)! zhind8o$4u01m}L4#N6R>1A*oITa3`$&l8yO3X?>lc5lMH>4g3JlJAb*!Hl1>E-ouH z;iSOa@NHact|I!=4*5>t7A|nirC3F7Xe`XYu?@~7b2uF^H#iz@sIBhvPs0>3uv~Hf zh=Ab$Zs-GO?q&dB5SlCM8v^Lx56e+Sy@MeGe4){g(A?WS{YYQ)H`P2RFNUV&&|LRT zOs@qebC&EK2}#DEi_iX=tJWkXs)ocm*sy&BX~iSeGZMg_d;_WKd`#W zElL@W-0*4(8sC8Cc3$sB8cXs$JnOgAcA;tK`_No_7pMJF9Z$W#lN)yI0p@nJeGhOQ zobz`8wC|1w=32i)+M7IyEPacdbcx2^eGR{cwYA7e>&4H~zAb4{%*U!h58>$DrsqVW|kG@<0jR5E0qG0Fk z^v@bDuIxk}@Q%g2<4paE&hN28Z)elXPhVKUnS;41=v9h3ZF9x(>Y9kY{_^n7EE0az zBV`=!=Ql>Q-jik$d8DD=Y@V2wi%X_#b;(gBr1Tp^bC$`jh)Bg3=T6AfH}s=-5lCzot7^y*@dPqGcadNbF$JH z!PiSE2R8=36*9w`wJbX&{6W=N(RghX+%$vIzB2i1)duTWgLi#0Om*#XilL6Q37*vjle-z x%llqS0nMrTR7yoS=;IIm6BMOfO7IE%>ObsrWe!{1nBM>Z002ovPDHLkV1h;ieB}TD literal 0 HcmV?d00001 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..deef704 --- /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.85" +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 0000000000000000000000000000000000000000..006318cd7643acf89e647b6a31ec36bbcb056280 GIT binary patch literal 10195 zcmb_?by!s4zV4!t4v{V?rE@?+U=$E3Nu^6*Xprt!X^?Jd1W5^Ll$K_IA*2yz1f*-I zyFB|m``qW8efPb8+<)d-vu5V|)_n2)-uNP4s4Ec@&=CLtK&<@isTKfW$br}U_?Y19 zjRv;Nx~DCBL!pDVt2CTEVz zJ1mEF6y&N=YMVQ6z%03YlK)J2?2d`Z+0UelQHU`DgY~rO4@QTN_O7`_3ZGGUd5d4xzce=lS+(-zs0$_~7z~=F3M`Caaz<-)^yu7ppv+FrbFo z#aais_WF-|6lt=aVChaILkP*M?`Eai9kIFW%YNHgmUSpkNC`GuI^4+32iKbY?Vfl9tR}bwUM{k;qJS7-L z)wjw!3Bq~bk`)Z6rICu1r`0~<+Os|+CFoc;aWt8cvrmsnC$tU3)~m2vWSKYN^87wa z3+$g<^aU~C0g}bu8VrxcKR+M<1anlco*PN9>zL?Bw=+3cH(j+E`Du9j*2YqI?)x`;67;TC%>r5sFzdvuEqkHUqlGP^m2 zGv-N^Ub2mF_lM`Yb`1&0GtEHRyVgM7>e81o-!ZdNfM5CPxd@~KuzK{OHE8_XM4`j4-wyTcP!P#=#~ zf7~SE1P|^ML8^(fY4%Tj!%D+Y3#j2r)pLJ|V;@-iG9{FLY&Jz`457O2GWsXCjU%eb zEl&O2=K(;_lkNV+iDJG2Zq{!G zdSQ}DGopO{5C$3|K(1Iz`6g46DJ;!FOt8qC2zrY z?RMSErJx4?ks=HXkB)3IZv+H%jH6yCDJdoK$-}eC%&rBEo);$%U;4@A7f z2^27WS)&#>Ae52AaB0iyGR%DCKY((<#>MLG@7-Da{CPlq<__?I-8NLw6bMf8$ZUokPdZ|qUpQDqyC z9!9_MT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dNYp+P?4o$~rw} zxK?z34Q#GVs z#kfZft|52G^bK(AH$LG{C_(Sf)|`C~0nFkE5|*5Xg|Fb4g|`X%IQ z+N^Sg+XO@nc?v#k!0Chos74mH#k`b`o4KtieMfdF!g(z$e?jdt^?WoxUBfpUAQb~Y ze|Te$?KgFUHhM{~Z8LAyn4;m<7Ic7OhW?Xw79n3}D!l+XjykSzlW@gw#J$p|TS}wz ztl)-(RJb%7i3E)Rav;pegqB{lsR{`AV3YD{go8=at1T`C7@OTc#&5oB%K-evX~nav z4`sVlY@Wh_9@+eql=%}SHW}a;R*e5s6_w=ye{a8S9tXwGCKRlE>4dSMtA8PWn;0zy>I+ zs+g!j^a*6HG@jbXQ3h2f2&{YS-CNytyjg{P)p3M)*iLv{40kCyd1WqEjim`O^VL3r z86WTL?629n)w*nfjiU%@zFvs@$T5>|RaV8KT8zI4w0|<@+yJb*E!z0GRnAQBM#GUt zU@9S|YuaV~`seX&iQx#GvrNDG;R?7+10TW#i4jg|CP}X1-gaR03NMlZo~acLpOiS4 zoZ!f~jy&ti2oSBX#9*6(UhjshXvo?H6q>j4!dl7w$w32|^gGr~NQSJ8#%EoASWsYBUI>>z!@PR@ z*jLCvim)jfEBpna8b2G31`dYVT2mzGL?aWx!v{NWhyc(83r{%JA9titLU6y=z7N1M zH_@{VZivz2UD1D)!ztL#k;&nUHOH_I2`^Y>|9B%MadbBs_4>!yP|IABLl`(?0}pCR{H(-xJ(T rOX~0ceQ5Px-on3&w*EhS>pEys?C^WhDD5VASPxKEP=8tlH4FV;vC6Vk literal 0 HcmV?d00001 diff --git a/extensions/file-info/screenshots/song.png b/extensions/file-info/screenshots/song.png new file mode 100644 index 0000000000000000000000000000000000000000..75ddfac7061e0692ca3b9b9778f0062b1d22b311 GIT binary patch literal 11807 zcmZv?1yoeu`|p1MfuTpF8$sz1=^TcVkdmQOLWT}WNd*B3QR+ho5(CoR-AH$rbR$UT zJ$}~rfA8Yu;^5uz08} zZlxjv89{{&UbQ<$1v=0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W(eaci@JFs4E$e z-HE0>NY_yhr~7ANQ-xzZN@C@4MHNX%g*;auxa$6&hDBdc^hTS>W(>m#uKtAH7TBV^ z!Z4~W)Wy^OWhFgUVN-|;WH9Uyovdg%TRD704ch2{GfSy0@J$^Ww1qta+KiXevCKbr zPmk%EPLz=wgJ21afT9affF}!^Q^|$G27-Mw~Jiz zOFM%-5(+zIQ{axS?g3jhhQk?Pj9dzAAcYH4Ad!@EwCohvBxQT#=#a?09Mhc?Q_2<1 zS4u|32lJHQLK;W4CouZvz*xM_dHuTjhs1COy=*HcxTI%O$fQWgextension_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/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 0000000000000000000000000000000000000000..b5a827f3c3906c0cbcbfcb134708b448fd29d386 GIT binary patch literal 1005 zcmVv000BDNklU`#x}Y(`ZyG)l@<8R!4R^iJ(Mi z&8gXit7>obZWCZ7oHN;H&a2qj`1H-U(Z7G{r$J)mwA|9obv>_!e~a_sUCzY_ce=HCBI@ck?#$1ETGp5WV=Nph5qm&M^y?%me} zUrwhat#SF4)w0SmqPeoSUlM#il{{zJH1I-JByVDPOwr5F35F-h(K%)EilaA(2@ZUU z8G6?rSu0Mq73HzgR0N-W95*!hyyr?y<$_su0y49~{-L4wub#Blu3h4D3Oohd|4guN zu&btgUY6a+V(^2B3G_Z#Y||2mPE027^lX~)vy72P#d432*c9)`*#UWl(Gk&sM~4;X zEbF_vWwk_?F&%h#NO6uUsFGLikVf}Fc}~L^^^`r*SQ~Q zuH%1lggiW!ySGnqj+~w+&u5Wx?R%9kd*G#B2ZIA>V2UfxQ#G`i4k<@b)a z$}`ha?#^yI!kI0+U4t-372eu~babsd5#|ib!aGpqa8B?a>q3&lv|@&@XiY<;b2~i8 zr1(l!*Iv5W-qF#q4VuHmx$7?83`g#biEM@D(n=db?NQ+^z?`|b@orcW+6c>Go}+g{ zF>Tc%D8~h_-j35+X@#xa^5(WU*O&63oUy#AHBNmV?0H95a`i?`^M-Wb%c1{ti=_GZ zTo$IJ&0*N@unTW}Ze;#C3MJ&!6k_q#7s$m&rT*1>^GERtB77 zQ~mi-UXcbr+<9|jJSO0WNHQv33)IGA9~Q<`}`CJcr>)U{cPaSDeG>B!6sir1T3j zulOAqXOsNFpqFx#QK$Tsn;?_GrJO;Fqnip1sppX9bS%nm0)&=9n&W7cIh;ZI0R*SX b$#VYyX5++r!LPq(00000NkvXXu0mjf=n(wT literal 0 HcmV?d00001 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..7c8530f --- /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.85" +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 0000000000000000000000000000000000000000..6efcf144292e850bba2f6bdc6193b19d289a78e4 GIT binary patch literal 10170 zcmeIYRZtvX6erwRa0w6~IKgFr;BLW#Tkt`G6Wrb12|+WsI|K+2+#$FVT!RO9*#3X@ zJ?zWYzU{tjP1T+5s-B+Pr_Vj-CpS_>Nd^;*7!3dbOgULeH2{DU1CRfqz=PwnGLsMh zPy%w2;u;=V$KUNONo1a1MDJ=tUo+I8V;xDLEv}23JmhpSacKwIN1W$`lgZYip=wcf*~l6Znk=z=l@2y=Y} zt6?w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qHoA1S5~depHy~EfCyRPL3iss20@vOyDK}OxeR?CIT!#0@luu!>qp8hx(qSI_yF*Z zZb%Vd?6#+bmhzvX&Bx96)qsNxMvd74!^)p@w|cRNDYLS+$&wc7SZ;^ZgKiG@d!Vmg zYYdv_M|d8v>I!M=s5K@oM*A6AJ_+7ZXH#8wa!0d?zOsyROcg6~K6G(Ll^-$>grnpE z92+XpOJ>xC!!6we*tlb>c>T)zf140rp)(Zr7a7}SEQOhia3kgZ(j^-J-6&2L0I;4+ z=|-cHJV*}l4O*ZN>!uR<-K39!aU2f_m2*_WmoQ&TwqRc&}nN&-{ARZL|{pTh@&t@6GB849D-^?6+Ev(6hwKoP*0Bn zhb2MP+DGyZv^2k9B0Ze+n$+;{7S7~-Rcl=@oY_Z{fuoL4mi63{)a$2_M5%p2>@c&* zgb$PNNY`t*mQbt^qK@#_{`k`;%&>45GLh z2gb&--57c4gx#Msy0gn){N?+25cRR;3B@0$W8bP6ykQ478>M13rAXlv5dJS!fx8#n YljC~=jy*nbPaYsAr6gG;VHET~00|^2bpQYW literal 0 HcmV?d00001 diff --git a/extensions/playback-queue/screenshots/item-menu.png b/extensions/playback-queue/screenshots/item-menu.png new file mode 100644 index 0000000000000000000000000000000000000000..ff8e694738fba69614bfd68e8452132453721333 GIT binary patch literal 9742 zcmd^lbxd4QxaZ(j9EuefTBOC@rMML-P~6?!T}qMS6ez{LgS%UCcXurgGr03^-)6JP z%jWIw-Zf#5y@*HBb=AU-S63xYsk zkgSBLnrHe+hJhtn|Jrj_>%Q?T=F-kk!u$;;ED5ThQdugzQAvVFF;izS`-d6Y&}Ua? zaGg?iovLNo-?!3ZL2n9Bv|B<|OF{`+CcuQGxt(N;20LIvm3*-%LK!GBUL5$FUbqp; z+lBSs0UNCsMgd5oTRY{~#f*%MR4#AM7x&CXGp*OC!H%@dKMdS)QG*xgnaA#inGr;B zbb5M+sSSfIzpwq_MF2U1dC2UERg{jMOV#LwEas{iWBvHmDc2g&gsx5q0yk^Aw>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zs_lK?woxlzfcuwkEB^hO_4W6g8jD@LnE*95U^T&nF5>7pKd{t9O#l4O1FPZ>_OiGM zSRMt#O@H`F$6Dz%t{T3vR$&DR&wT^hgy9&ipk}fak^?;zm$e@If+FRbpI>nr(WVXP zy}7l^H9@zB_UE_%!e`|fRI1L3cjJVGlH@;8VoF4sMYrYkH7s~N!*d9XUPuRB&2&68 zsK_XJss!vV`{WunDN>i^r8`FonrLRz)?NQjKgj+J@O9wy-dWJxLnCP!+u%sq7_0ux zHi(pkK{Ew*G|jQ;O&gT+th69|O!vh$OVgef@x@O{DUcjaR5ludUWw*63FVYYi=OoR zSe#>zJFuM&lu_H}eYP#&i6tjHA`eWT8kH%l7FS~On15=>XK{kLIzklj~75&}>X8(x(zH3^54ANAMRFcY5MMnXg&+d!>&Fvhd zQSr=k5)qt_1V2arVYXzKXHQraUT97Al(6AgVS!v)kOzOW4eNoazsKT=pcaYX!n_jdXR~zYEb{j96-?u>$r{D zOsMk_V4vP|fzzbcLgtA2LqJpE8C5=Xpe_4a-Al%7!?$Qv*xgFo?RHqfzZz77B++`- zxI%gB4FF#LA-h9Fvj31>hf=(hJXfBe82>qq*HyihCUL3-j->xXc+38S@V*Q$Ah~qz zQN(FP1(79^gW~aWAm&6z!Hz!z84{nWSi!i#W|<8#+}=V;LdOpF$5x2u0;a(%U|eKs z*{^f*?%E`0y#F7|Kt=ywEW?n|kei`Xt**&eb|^?~!FzjDdbadE9{2v~kwWnk zKPwt%!W|-mc$KqTc%_MJXa(cWG!dc84ki5=An~uB(K$26ANKq}z3c!*4X_1-P_vA= zXzc$q5CM`*Xja9_4T|JpH@y>w1EU_FQVaH7Z;`DGnJ;?%LfE;m|eiID4Q zsRsetting_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); +} From 739ae56f05181cf293e41af91ad098698578c6bc Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Thu, 26 Nov 2026 05:21:52 +0000 Subject: [PATCH 06/20] feat: read the album artist through the Album Artists service Playback Log 0.1.3 asks the Album Artists extension for the album artist on each write, so the column is empty when the extension is not running or when the Album Artist equals the Artist. It goes to api 1.85 for extension_service. reprise_album_artist_read leaves the reprise library and its header. --- extensions/playback-log/README.md | 3 ++- extensions/playback-log/main.c | 5 ++++- extensions/playback-log/manifest.toml | 2 +- extensions/playback-log/test.c | 10 ++++------ extensions/reprise/manifest.toml | 1 - extensions/reprise/reprise.h | 3 --- 6 files changed, 11 insertions(+), 13 deletions(-) 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 f369469..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 = RV_OPTIONAL(reprise_album_artist_read, 0, 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); diff --git a/extensions/playback-log/manifest.toml b/extensions/playback-log/manifest.toml index 77324e3..d1b4915 100644 --- a/extensions/playback-log/manifest.toml +++ b/extensions/playback-log/manifest.toml @@ -1,7 +1,7 @@ id = "playback-log" name = "Playback Log" description = "Write a scrobbler log and optional detailed listening reports." -version = "0.1.2" +version = "0.1.3" author = "RepriseOS contributors" license = "GPL-3.0-only" api = "1.89" diff --git a/extensions/playback-log/test.c b/extensions/playback-log/test.c index 2a24e0f..d2b44fa 100644 --- a/extensions/playback-log/test.c +++ b/extensions/playback-log/test.c @@ -140,7 +140,6 @@ static int mock_seek(void *h, uint64_t n, int w) #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 -#pragma weak reprise_album_artist_read #include "main.c" enum { FINISH, COMPLETE }; @@ -179,12 +178,10 @@ uint32_t (reprise_legacy_preference)(uint32_t key, void *data, uint32_t capacity return 0; } -uint32_t (reprise_album_artist_read)(void *r, uint16_t *s, uint32_t n) +static const void *mock_service(const char *id) { - (void)r; - (void)s; - (void)n; - return 0; + assert(!strcmp(id, ALBUM_ARTISTS_ID)); + return NULL; } static void configure(const char *text) @@ -206,6 +203,7 @@ int main(void) static const struct rv_api mock = { .hook_next = mock_next, .setting_get_int = mock_enabled, + .extension_service = mock_service, }; api = &mock; load_config(); diff --git a/extensions/reprise/manifest.toml b/extensions/reprise/manifest.toml index dd8d996..f4b6f12 100644 --- a/extensions/reprise/manifest.toml +++ b/extensions/reprise/manifest.toml @@ -8,7 +8,6 @@ api = "1.89" category = "library" exports = [ "reprise_legacy_preference", - "reprise_album_artist_read", ] [[module]] diff --git a/extensions/reprise/reprise.h b/extensions/reprise/reprise.h index 20dd966..ab186bf 100644 --- a/extensions/reprise/reprise.h +++ b/extensions/reprise/reprise.h @@ -12,8 +12,5 @@ /* 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); -/* Copies the album artist of a library record as UTF-16 units into `text` and - * returns how many, at most `capacity`. */ -uint32_t (reprise_album_artist_read)(void *record, uint16_t *text, uint32_t capacity); #endif From 9acf0f3eadc9243ad1772da50fac069fa5b6fab8 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Thu, 26 Nov 2026 06:46:31 +0000 Subject: [PATCH 07/20] feat: add Equalizer, Clicker Modes, iAP Auth Bypass and EU Volume Limit Four features that leave the RepriseOS core, as extensions: Apple's EQ presets through a filter chain with headroom plus a Custom preset of five bands with its own editor screen; Settings > Clicker cycling Off, Speaker, Headphones and Both; the accessory signature verifiers reporting success; and the EU volume cap, warning and automatic lowering turned off. On first start Equalizer imports the Custom EQ record the earlier core stored through the reprise library, moving the precut of layouts without Auto by one, and shows the Edit EQ row when Apple's EQ preference held the Custom row. Whatever the record holds, the values are stored so a later boot cannot import it. Custom EQ values that exist only in the pre-store CFWEQ file start from the defaults. The root Makefile, the catalog sources, the README and the NOTICE list them. Equalizer keeps the core's settings-eq art; the other three take Cupertino Icons glyphs rendered through the shared Settings icon pipeline. iAP Auth Bypass and EU Volume Limit add no screen, so their listings carry no screenshot and the catalog test checks screenshots only where a listing has them. --- Makefile | 5 +- NOTICE | 10 +- README.md | 4 + catalog/sources.toml | 20 + extensions/clicker-modes/Makefile | 3 + extensions/clicker-modes/README.md | 13 + .../assets/LICENSE.cupertino-icons | 20 + .../assets/settings-clicker-modes.png | Bin 0 -> 1490 bytes .../assets/settings-clicker-modes.svg | 5 + extensions/clicker-modes/listing.toml | 7 + extensions/clicker-modes/main.c | 126 +++++ extensions/clicker-modes/manifest.toml | 13 + .../clicker-modes/screenshots/settings.png | Bin 0 -> 33072 bytes extensions/equalizer/Makefile | 4 + extensions/equalizer/README.md | 25 + extensions/equalizer/assets/settings-eq.png | Bin 0 -> 1429 bytes extensions/equalizer/assets/settings-eq.svg | 11 + extensions/equalizer/editor.c | 322 ++++++++++++ extensions/equalizer/engine.c | 269 ++++++++++ extensions/equalizer/engine.h | 33 ++ extensions/equalizer/listing.toml | 5 + extensions/equalizer/main.c | 229 ++++++++ extensions/equalizer/manifest.toml | 27 + extensions/equalizer/presets.c | 50 ++ extensions/equalizer/presets.h | 26 + extensions/equalizer/screenshots/editor.png | Bin 0 -> 10908 bytes extensions/equalizer/shared.h | 82 +++ extensions/equalizer/tests/engine_test.c | 487 ++++++++++++++++++ extensions/equalizer/tests/run.py | 43 ++ extensions/eu-volume-limit/Makefile | 3 + extensions/eu-volume-limit/README.md | 24 + .../assets/LICENSE.cupertino-icons | 20 + .../assets/settings-eu-volume-limit.png | Bin 0 -> 2009 bytes .../assets/settings-eu-volume-limit.svg | 5 + extensions/eu-volume-limit/listing.toml | 3 + extensions/eu-volume-limit/main.c | 35 ++ extensions/eu-volume-limit/manifest.toml | 13 + extensions/iap-auth-bypass/Makefile | 3 + extensions/iap-auth-bypass/README.md | 15 + .../assets/LICENSE.cupertino-icons | 20 + .../assets/settings-iap-auth-bypass.png | Bin 0 -> 2118 bytes .../assets/settings-iap-auth-bypass.svg | 5 + extensions/iap-auth-bypass/listing.toml | 3 + extensions/iap-auth-bypass/main.c | 50 ++ extensions/iap-auth-bypass/manifest.toml | 13 + tests/test_catalog.py | 5 +- 46 files changed, 2050 insertions(+), 6 deletions(-) create mode 100644 extensions/clicker-modes/Makefile create mode 100644 extensions/clicker-modes/README.md create mode 100644 extensions/clicker-modes/assets/LICENSE.cupertino-icons create mode 100644 extensions/clicker-modes/assets/settings-clicker-modes.png create mode 100644 extensions/clicker-modes/assets/settings-clicker-modes.svg create mode 100644 extensions/clicker-modes/listing.toml create mode 100644 extensions/clicker-modes/main.c create mode 100644 extensions/clicker-modes/manifest.toml create mode 100644 extensions/clicker-modes/screenshots/settings.png create mode 100644 extensions/equalizer/Makefile create mode 100644 extensions/equalizer/README.md create mode 100644 extensions/equalizer/assets/settings-eq.png create mode 100644 extensions/equalizer/assets/settings-eq.svg create mode 100644 extensions/equalizer/editor.c create mode 100644 extensions/equalizer/engine.c create mode 100644 extensions/equalizer/engine.h create mode 100644 extensions/equalizer/listing.toml create mode 100644 extensions/equalizer/main.c create mode 100644 extensions/equalizer/manifest.toml create mode 100644 extensions/equalizer/presets.c create mode 100644 extensions/equalizer/presets.h create mode 100644 extensions/equalizer/screenshots/editor.png create mode 100644 extensions/equalizer/shared.h create mode 100644 extensions/equalizer/tests/engine_test.c create mode 100755 extensions/equalizer/tests/run.py create mode 100644 extensions/eu-volume-limit/Makefile create mode 100644 extensions/eu-volume-limit/README.md create mode 100644 extensions/eu-volume-limit/assets/LICENSE.cupertino-icons create mode 100644 extensions/eu-volume-limit/assets/settings-eu-volume-limit.png create mode 100644 extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg create mode 100644 extensions/eu-volume-limit/listing.toml create mode 100644 extensions/eu-volume-limit/main.c create mode 100644 extensions/eu-volume-limit/manifest.toml create mode 100644 extensions/iap-auth-bypass/Makefile create mode 100644 extensions/iap-auth-bypass/README.md create mode 100644 extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons create mode 100644 extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png create mode 100644 extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg create mode 100644 extensions/iap-auth-bypass/listing.toml create mode 100644 extensions/iap-auth-bypass/main.c create mode 100644 extensions/iap-auth-bypass/manifest.toml diff --git a/Makefile b/Makefile index 1bdbd3c..d9dd12d 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ # SPDX-License-Identifier: GPL-3.0-only SDK ?= ../osos-lab/rvx-sdk OUT ?= build -extensions := album-artists balance crossfeed dsp file-info night-shift playback-log \ - playback-queue +extensions := album-artists balance clicker-modes crossfeed dsp equalizer eu-volume-limit \ + file-info iap-auth-bypass night-shift playback-log playback-queue .PHONY: all $(extensions) all: $(extensions) @@ -18,6 +18,7 @@ check: $(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" diff --git a/NOTICE b/NOTICE index 113d9c8..a3f3941 100644 --- a/NOTICE +++ b/NOTICE @@ -9,8 +9,14 @@ 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. The original RevolaOS -notice follows. +(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. 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 b8fa8e0..d9be96f 100644 --- a/README.md +++ b/README.md @@ -9,5 +9,9 @@ This repository hosts the source for these RepriseOS extensions and accepts prop - [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. 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 3ef89f3..9f121ab 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -37,3 +37,23 @@ tag_prefix = "file-info/v" 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" 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 0000000000000000000000000000000000000000..5a650aa5f6beebd00a7da33fc08c68721edf6f3d GIT binary patch literal 1490 zcmZ{kdpOez7{`A?9FE&0d)((XhcH{QhGh=99k&c~johz|tuq`-)Xc3%vEj5Ox*QD? zlg1u$DT>MEaVJbs5ehjWc6RFFpzq+cv4ks7$J(v$%6glTwVA*Ahl!V8$tamUAs5h zDvQ0Bm^2MY{o)?>iUq; zBTD^;X*5lbE=Z9wJ$3qp zQg^~T<}FL~rQ+xX1<$erM)j$WSu?%f*jOq$qETRWQeS%*+0 zyGE?eZPx#6_PP!LYko;Cdf~TPVAW}gr$Y@)kgP1WzPmS=Y+xkSUCU?XX;Pm^(xVVF((Bmv8Pr#QBVK+%)AQ+ZM?{W zLDsUk$sR{1(nlTAlLC(IfRYtWIQ4rVP>ZTFh$YZn{1)7`rb>$(Cl+2ICe$=#bL#va zjBfMOmmN@zjqi=Wl2XOWq^EkwfM2U*vk$S+xh*1rIbK*F^Ck6nX8!#0n*~_KdOjS%7L}C_^RjfE=-}^!yXzpfM)k7)hKG6abVf<#SWoC0 zvnuNK9SgmXJO5tyt7548zXA4H$+WAjdJ@mwYmHpAyE427Vlv+&K(L?abN3L46eqIJ zRUdWE4BH1EpJa956rRKtEt$yFdB55(dh8aRX z0~FW1)DPMpql4XpZ&VK*N%f_xd{*`eGKd|#+#(<2IYARQy*9O6yR+(rHCXV!md7r0C}wGJ=Iknm6w|Rqi1liMf67W-Ashc{_`j5w|qOx zY5aZ(7cTPl&OK{C`dCZMso#SPOG$yVhtiWuW2Kvx S + + + + 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..2a10cec --- /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.28" +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 0000000000000000000000000000000000000000..069c01137107699a0dc889d37ac9149c450cede7 GIT binary patch literal 33072 zcmZs?Wl&sA*tI)2Bv^0=?ykYz-QC@t;7)+x8r)riySux)TX1*(_VbQjoCQF*<@mEN$D$%WiGasR@M#b+h!6)zkRnH5pl}8c+U3@0S(N`1 zrY??M^~kM3k*L5xDG&%mE4jwDa{AbIPk|_93tmc@$5+IBhOp>qf5ZoAzW1I>KRoxwv3!3a9S0%(hS^rnTqdjN`1Zbc?)u7>PLKBGr(cHj zRG(L`m@^?;v4Oy|rY#!_0tv)*DCDBG_v1w$dFXeyc(}(Cy*${CyA`E#p^5X>2YRoE z`<2-XCH-^oBWLai0=m^k-rF0QF4Ie8WTEn0V$h>nM8`7a!K>PAnO)P`p8fr!r~F5y z5-nPR7WCowJm!{C9d~3CqTi4>802t4M1e`_~bfC&LI6YeF z>tHlIF@o=>Wtn98f8$p&F^XOi!WQyU$2Oo5?6n9ku-Md57ag`~CTJ4t5^p+hX1kJT z$Npwi;QHQPy|vvoyt5|ttq#jG~qr8cD${wT4p{^VaJmwp;ov??87pA zS83jC46!Mt$h0e7usXPX-ksb%=ef~^sJSsIf%UIn_lKxM_>ZmkS4_m z>jW`{O5W`13Ms*KFm`G-6dZ=iCuPHs1#?RZrNV2uVWpSynA^?W@=}Ez8xsUeW~>4oMH>5_jpnKc4JI{K=P(q4#TC z?_9uN<7eyiYj>$zXkUeNIB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YZ0 zSku@GANn+4uTeVTZp9a7nl>h$g!<#^O)SaSj>K!U&JW2TyCx`GteqMfo`*MxP6}f5n)WQ-pMTUY-3z)cjmwuny&ja?6*b zGWqWkPQX`Oi$QCl?zC*elB14Z2w4lvA($y7Reh=nwG%eVrSnrq5v=Ub1KrOh6K=crVHBo1PnF%sA#3kyl!=KqAv&p8kQFOs>Q&PlHv%tsUzfuH`Su%zPKuz&gM+fk@@2cl}A>9cxCV z=lt3pMRzeH*V*IZT9b$Pc5tUv2|C|1v@0`uHCl6GY8|%&?XeZ&H#W^Ss*QrwGxH!j zJc9qXg+8b%bHkpx4iAInq3jJk{FfAjOE%orpD|s>gA30uAL?FEU`e5-E8vzu(&7qY JH6lho{ugn;df)&6 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..20644d38a06e6a24342072a52c3f4336a3ce37e8 GIT binary patch literal 1429 zcmV;G1#0?v000GCNkl2p(67>7AGxl5L&&C(<{H)(23WeR8;WK@zkj^m7@j-MSjM3Jo&S{4^T5frh0aT^Db z#xAx~yM~m~HnD{+Oe?k&OOZuvMN$6{FJ*@F-kWnS%=zX_o-euco8NhIo4hBTdzLNB zlP6CefTO&^#hT?J#ya|+Env$CIBReITkmDdNV?rO|M}F%mJxM-{$1~5%Lur3-T15C z&z2E&i#I;;vt@b^Lav>^|8c~xUcjYGnNCN@w3q{x(dc8x78g4c(P&kPfS1-?U-($B zBV<|vwS(F0=#_9y;Jb9A|x_Ajj*xDJ>|@OPHhUimFYN656g=+HI5 z#Nz^9dim-{IlA0TryIBm7zer?mo9&(*AX(E?$l+#D9~-6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uY03v6s j6GbyJ%s4>=2vGMQ!S18$vUWrj00000NkvXXu0mjfNS3iS literal 0 HcmV?d00001 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..5c0fd3e --- /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.84" +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 0000000000000000000000000000000000000000..89be12534ec87274b0638027e2989dabdd230c53 GIT binary patch literal 10908 zcmd6NRZtyKv}FT90>RxOgy0a|J-7vTLLkB29fCt}4ek&w?iSo3xI=KgxVuc})znPY z%zN{G=Vw>{-0r@8_E~$$3Hzidg^Ems3;+PCjPyqp0DutzuTPO+!TPL3F8}}(fXqix zHMjJm3|}*1*UTH?>`PjZaliO|DV58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hISRBfh-d94il!}h? zBXk>{H|hz&^s~AYK+L%jPa|J;=X+}i&B1xJA1AmX73Mb(a#oINt=Q`>zHG8pj!X~J zFVJp0NA7IuF5Y4w77%E+seX6qV>ZC~3II>UXiIn0x8+W?pJheCAx6PSt+`Qnu+k5+ z?L|`SzZR2rSC#f*)I{NVHW&DpL4cmcV3xJ+s^+-iHN%%bu(xP;9$VOR*Gg1_(c2v@ zFwL^0a8W&Cxk(-{*;@$O`gGTl5yw(No?io0f|+k%3w%m6$hBcs`-xAwr?s`mRAd8H z@N56-8i~tj3PW3<(2FTx&85YZWyHqgcY*m^)Wo9j2`mniE06EjC~k*`1jZ33yPM?w z?wQpYJ-5AQ>=%Bn{X1TLSm^sW+qG?(**7V&=#c07w&x z!q1dEXcfG8zHmtCGY_k^18Y80*0(Zq4b;@+5qCS>mwMp7;75+ zn9M!bW7SzMJbnpW_P@#I_U0A@hs%R{5{3~YesSiPIgX>F09(yNr#C!|Tv5HE;3*Uj zIzCXLY-sqGs~FqsRvpYpPtFYfDIla`P5k!lWGxkCrs=>@BUQK}Yh=<+-vAx}j6Z5% z1fu4iTC-Z0f0q+iaK;kC=bAPCTBB_(K^6E%FSWStgEa_CtUh_P;jAGB4mNt&Xe4k^ zps%iqQoJH_$@khDgRQxA;XymEmI&;dA$e44QX| + +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 0000000000000000000000000000000000000000..058fcd13e1b6d9070a713afd5b8ede17b241d227 GIT binary patch literal 2009 zcmZ`)dpHyN8~+Z?EtiyBvXoO4(Pm4P1mT@U4!vth zx%6bym(%)818$*ri1L!vZCCy86KCcSA0{G_qKx2NTF`ErvLw6j6_$}TLt&7(kFIgs zAO6NEFU50y97vnh-77;DN|*R*Sb)NowKrYK(qmtRGT|MRDzzoG(;VBtHDi3zrtEva zc{9-K+aey(jETOD=_Slj3_Fv;ucyady=yo5eu4l6Z+9r!{8gJSR34;04u0J+xNc2Y z)3WnB_JW(2E^Z1q1z#E3%>AV$;g1g%HW+ge<>-&Lo3~r0ZpidBCFh}{w~w_-=W#V; z0|4sL;)|iV_>J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{y+Z!Rz#dU literal 0 HcmV?d00001 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..d32163c --- /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.30" +stability = "beta" +category = "media" + +[[module]] +name = "main" +trigger = "always" 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 0000000000000000000000000000000000000000..2713d8f7b64169ed042efec73735f5c8ad3ba514 GIT binary patch literal 2118 zcmZ{ldpy&P7stPZg>s49;xX4mn2}g6a~o^9jmTYCZp|gLM7fkFjF^zMHl8PmQPfDy zwZapzTynof%0!4{VdJ;oKfl-SpXZNrKCg4m>wV7o>zphXC;P)93L*di97a0WqIv4X zvug)=4xqO>4DkdU?0|LzfJ99INKFTT9bPJR5dh*L0I(DY05B2&$i`3_UCnp}{vedS zEdW&AQG@a#5Dw{R2U-$U5YkcZC6H2iDGi+61zgBQ90nGA1;Y~n3V|By8W`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k`M2FSU zt|>3}1rz7-6yd+j_GM|FEI4#5i{o$X>F?CYov}=Q + + + + 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..ce10966 --- /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.29" +stability = "beta" +category = "system" + +[[module]] +name = "main" +trigger = "always" diff --git a/tests/test_catalog.py b/tests/test_catalog.py index 922385a..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() From e6cfa13871f993ae55f666a9478e9f880a0e93a1 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Thu, 26 Nov 2026 18:42:39 +0000 Subject: [PATCH 08/20] feat: build against API 1.89 The moved extensions ask for API 1.89 like the rest of the catalog: the core at that API refuses images an older SDK packed, and the SDK refuses a lower manifest api. --- extensions/album-artists/manifest.toml | 2 +- extensions/clicker-modes/manifest.toml | 2 +- extensions/equalizer/manifest.toml | 2 +- extensions/eu-volume-limit/manifest.toml | 2 +- extensions/file-info/manifest.toml | 2 +- extensions/iap-auth-bypass/manifest.toml | 2 +- extensions/playback-queue/manifest.toml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/extensions/album-artists/manifest.toml b/extensions/album-artists/manifest.toml index 2fd5150..7979545 100644 --- a/extensions/album-artists/manifest.toml +++ b/extensions/album-artists/manifest.toml @@ -4,7 +4,7 @@ description = "Browse the library by Album Artist, falling back to Artist, from version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.85" +api = "1.89" stability = "beta" category = "media" diff --git a/extensions/clicker-modes/manifest.toml b/extensions/clicker-modes/manifest.toml index 2a10cec..42eac75 100644 --- a/extensions/clicker-modes/manifest.toml +++ b/extensions/clicker-modes/manifest.toml @@ -4,7 +4,7 @@ description = "Choose where the click wheel sound plays: the iPod's speaker, hea version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.28" +api = "1.89" stability = "beta" category = "system" diff --git a/extensions/equalizer/manifest.toml b/extensions/equalizer/manifest.toml index 5c0fd3e..a797dfc 100644 --- a/extensions/equalizer/manifest.toml +++ b/extensions/equalizer/manifest.toml @@ -4,7 +4,7 @@ description = "Stop the EQ presets from distorting, and add a Custom preset with version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.84" +api = "1.89" stability = "beta" category = "effects" diff --git a/extensions/eu-volume-limit/manifest.toml b/extensions/eu-volume-limit/manifest.toml index d32163c..6bd47ab 100644 --- a/extensions/eu-volume-limit/manifest.toml +++ b/extensions/eu-volume-limit/manifest.toml @@ -4,7 +4,7 @@ description = "Turns off the EU volume cap: 15% more volume with the limit switc version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.30" +api = "1.89" stability = "beta" category = "media" diff --git a/extensions/file-info/manifest.toml b/extensions/file-info/manifest.toml index deef704..b4adea0 100644 --- a/extensions/file-info/manifest.toml +++ b/extensions/file-info/manifest.toml @@ -4,7 +4,7 @@ description = "Show a song, episode, audiobook or video's tags and file properti version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.85" +api = "1.89" stability = "beta" category = "media" diff --git a/extensions/iap-auth-bypass/manifest.toml b/extensions/iap-auth-bypass/manifest.toml index ce10966..7c5f399 100644 --- a/extensions/iap-auth-bypass/manifest.toml +++ b/extensions/iap-auth-bypass/manifest.toml @@ -4,7 +4,7 @@ description = "Let accessories use authentication-gated iAP commands without an version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.29" +api = "1.89" stability = "beta" category = "system" diff --git a/extensions/playback-queue/manifest.toml b/extensions/playback-queue/manifest.toml index 7c8530f..7343192 100644 --- a/extensions/playback-queue/manifest.toml +++ b/extensions/playback-queue/manifest.toml @@ -4,7 +4,7 @@ description = "Queue songs, albums, artists or podcast episodes with Play Next o version = "0.1.0" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.85" +api = "1.89" stability = "beta" category = "media" From 0f1c52d089519fa824ef8792cff636290efaa01d Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 02:39:10 +0000 Subject: [PATCH 09/20] feat: add Homebrew Apps and games from /Reprise/Apps// and /Reprise/Games//: games join Extras > Games, apps get an Apps row and pane under Extras, and manifests in those folders are read without a signature. Game data goes to /Reprise/Data/Games and /Reprise/Data/Apps instead of iPod_Control. The catalog icon is a Cupertino Icons glyph. --- Makefile | 2 +- NOTICE | 5 +- README.md | 1 + catalog/sources.toml | 5 + extensions/homebrew/Makefile | 3 + extensions/homebrew/README.md | 32 ++ .../homebrew/assets/LICENSE.cupertino-icons | 20 + extensions/homebrew/assets/apps.png | Bin 0 -> 8881 bytes extensions/homebrew/assets/render.py | 386 +++++++++++++++ .../homebrew/assets/settings-homebrew.png | Bin 0 -> 866 bytes .../homebrew/assets/settings-homebrew.svg | 5 + extensions/homebrew/listing.toml | 15 + extensions/homebrew/main.c | 466 ++++++++++++++++++ extensions/homebrew/manifest.toml | 19 + extensions/homebrew/screenshots/apps-row.png | Bin 0 -> 27521 bytes extensions/homebrew/screenshots/apps.png | Bin 0 -> 6539 bytes extensions/homebrew/screenshots/games.png | Bin 0 -> 24787 bytes 17 files changed, 957 insertions(+), 2 deletions(-) create mode 100644 extensions/homebrew/Makefile create mode 100644 extensions/homebrew/README.md create mode 100644 extensions/homebrew/assets/LICENSE.cupertino-icons create mode 100644 extensions/homebrew/assets/apps.png create mode 100644 extensions/homebrew/assets/render.py create mode 100644 extensions/homebrew/assets/settings-homebrew.png create mode 100644 extensions/homebrew/assets/settings-homebrew.svg create mode 100644 extensions/homebrew/listing.toml create mode 100644 extensions/homebrew/main.c create mode 100644 extensions/homebrew/manifest.toml create mode 100644 extensions/homebrew/screenshots/apps-row.png create mode 100644 extensions/homebrew/screenshots/apps.png create mode 100644 extensions/homebrew/screenshots/games.png diff --git a/Makefile b/Makefile index d9dd12d..fa9d5ae 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ SDK ?= ../osos-lab/rvx-sdk OUT ?= build extensions := album-artists balance clicker-modes crossfeed dsp equalizer eu-volume-limit \ - file-info iap-auth-bypass night-shift playback-log playback-queue + file-info homebrew iap-auth-bypass night-shift playback-log playback-queue .PHONY: all $(extensions) all: $(extensions) diff --git a/NOTICE b/NOTICE index a3f3941..9dac7e2 100644 --- a/NOTICE +++ b/NOTICE @@ -16,7 +16,10 @@ 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. The original RevolaOS notice follows. +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 d9be96f..472e1a0 100644 --- a/README.md +++ b/README.md @@ -13,5 +13,6 @@ This repository hosts the source for these RepriseOS extensions and accepts prop - [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 9f121ab..10f27b3 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -57,3 +57,8 @@ tag_prefix = "iap-auth-bypass/v" 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/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..8ac2d81 --- /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/paviro/revola-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 0000000000000000000000000000000000000000..ff197d6193fc487a4ffaacb834feb65de96b5801 GIT binary patch literal 8881 zcmV;iB2L|jP)!-uKvfezks8{^R?8=iGCQYyalbzbLO|sZl2fL zG<#m_^yy9YjZnCF3#L1XExe<*GQ!!=AG)yBYrca-V88c>K=FBF{nl&3uP0g6y zGzYV1&n0n|qN=JIF)?w-%`JHJ)t~;Vx_$Q#LjpbP+aJIFYx9H8|A@{bXRv8&8}jmt z5ET`T#DpXyC#N7SEgcydS;)@LMP6P33JZ(5Sf!<97&E2`uh*~-;e%||M?%^fAgn5|5NkO2t0$^+c!V* zyz%bGkH%I{grk!)tgNhHZ*LD57gxBsy20Je9Ukr;@bvJ+aL?iJ^76un5#I3j9tj^G zU-1+cZV1O3Qov9`9Zx3RH#M8MY8R*jvl9qjBR zm|P48dj~i;IKa`t5sr?IaB^}YoZ;;33>Rk?xRNX`E-w6j?D-rWo#Ex}i<+3wFTVPR)}hgOhPK7aU+#;EOXf*KKlUkZVm(NYxbBhFFe`o^Ly%~CFiDiK z>%{MPNVHm6SwBqA%*O|PcktEM{|G8sxX^VyY-mKDk!@^ELtjW(lsu^B9`#Hrm4asR zSefHOI2k6(H{yEr^xVeAwrA>$d3gB8f57Ko{uw9EbhiwR$TPANd!*mf5@(p7fAGWki&kLb%hC5{t)#3KR+PWF5w ze(vi$eYLHV?!!5KrJhh7Jk_h}IM!u!*`J!$K6j7dvN*r^wAjVftuHJhhMH%aA#ome zyYa~v^_Onm?mOM{;Wx)FzKcU=uj9b!w{eg-bVj06%~j69(dgU`lmSi_QyEY{UMH=e+T=v(HUXkQAkQoMSejs8mG>XXH~GGBj47+1&;1Ma2Xi}SD)~Q4(>jEwvMiS zHulbKRyOvn!>p`WNvl`Pss_B-*xHh~9z)_h&bE2~dC#L)?|yUa`U5CA+7HKX{+>&A zmP;K=2V(0=j?-e^C873!mHVS@G8So5@h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P9PU& z6awO?Z-!hSKKem&jOyEuRW8lt$4yQ+{QWJzg}h zysTMSSskbTh{~GBcg|ixKY9iy@rIa9#d)cU$oSF5*7j2|^?pm7z+@$Ajn28KGEqL$ z6z8Jk@}!i;ekg4QPlMfG8Y!pz$|if9Zds%LsK=Jd8udrtGi+?_Szq(cFzKu}JEgE* z%%EnA$Ce8*m8B_IG41vcuTLq>P}&Tlk~WYulFzHDbk>gKvbI@>@{%Y?GleY5HJTKi z2H00e7-u2)Q~Tz_&}Lks{?f?9KpKVUEI_6!n(Wa+j&Y*dE*CwMye<pALKt`P z+{$FJRrF}GG(#ooSI}S^OQQf$*207!5rQz0FoB|fk(*va(kMkyGPM0lN}6)Iul$&Z zmq;XUA&88(q9nN+>0xxG8QOjWCCx!cBo`rvjC`H5NG%6N4>KgqP#SR&WSI 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 0000000000000000000000000000000000000000..2b816b19f6cb448e323941cd820ec9d23f7a8074 GIT binary patch literal 866 zcmeAS@N?(olHy`uVBq!ia0vp^en4Ew0VEhU?en+-q?nSt-CY>|xA&jf59G0zc>21s zzv7l=5>V}IOxz3tPq1_o9J z223Z<)T3y~%}>cptHiCLcuL7(pau=N4JDbmsl_FUxdpiOs5FMk09{?=>EalYaqsOk z`;1^mndAG{YlbSC`c6~}6^d0_x$8)5*4IQPKGEr66FXEdE(%%ET`XH-V8QVy&ucX!`^;&2dP zaTLhnd75M)_2vbK0tdsHrqsxIdtI}|+~3r`eRsJf6BcH_XJ%z=#J_gk-B{@C5uWt6ezA0h7thC_su3bs1+w^Xq_&=*AAoS;^duEGobi^~h zJKeSQwmaLhw{Ioq?Gg!}#aOgSk3HdXPVIzAtD~QEc0ZbM^0hES*xO}&6)%%K=az-O z4e#{iE-Kc$^4I(E=>sMoDmdNFYrb1}SlQwBguOFAFFtjATlCjp&(E97TW`;f$!ATT z_G`Ie&huYCZ$@w3DSh#r@w6*5i@oj|Tbo_ZpY@DSA#K*Pn?}h!8{HWSqAuBn-dvRJ zWX2qm-{Z!ppz?B+pldpN$afpT;SDJgFWdAi|tqUwK+gPhYNygYahPCf0k;k@p&=T6}Z z8~%%bzF@jFH|%`dwd&Ug#TmcP`2Q^bm_+jXKBwM^npbyK{l?6$Z5eB+9T r)?3WKH literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..2e7e9593a22a751ab79cf539e53c9f78017398d9 GIT binary patch literal 27521 zcmZ^~b8sbZ)HQnIOst7*Clh00V`AGjC$??dwmGqF+qUzaU%mByRk!ZF|C~B?x=ugc zyZ7GD+H0*2lampHhrxyc008h3;=&3500=+u`wcWG@bgQS`ZoYT2#^pKQ2LvB;bm=x zyWI9Yo$~897)~k#j>|tkD?36+Jz?xdnoMOnnmA>JLk8eY8P6dm+{0_qIN`>r<^SK#wzN{4Zx2fAsG3%ZCJb zS_=ytWuOIh+7Ms>#qTIAZ4lbi}XHBtjmnl)-_v8>f(0ABLp-ZPJJg5+*9OW8m zCEk@G!Cyl^Zt;+B*t(w*Kg?~X#2?3epS?^?n1^z3Wlar4JXTg1#Th1Hbr0*vP(-n7 z3@#&?R$lo*vsg_WwSlPjp{w|y6Kt(v5UswVbB+ED&)V%@Ehu!{NvO#_$aeF7N@-Bv zl;LF^^~WJ#aWRPQKsH2_HJhuJ(KUiKeXTmIqZl5>$BG(nsYHfjoq1~xEW?wFX%Xme zThX8VP_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XbxRz8E|=jWT6pgvt?DG#(eGQ$moZ>^*x4FXQYg| z>>Cx*HvoX{9ycW^I0i2e0#M*rFszUiBlF&m$DlHKbU@RSL~-nRxlVsjy@8^UI3u|I zlU%I<@%Z^vBU^n*Tis>te8pujjy+rPaG6w6I#%=NDq1;p&4_D6pN-rq*D?UqH_$Iq3t5CPx>ztRbb{-q;nKH4`2CY|r;4vsra0YoiKHv(Hk@yDE zy0avbD8PuBbBiC-KB5SEu~l`Znf!2=Dy7Yc#Ol)XFV56-x0mnl^EeL|fuo2e_kdS$#WF zDT3;OK8}I$K9sk7!i4B{K3JfevDd=M=tBXy>2to@RtNxszPVj*?0WFIM_P62)EYXKB01qxPaL;O6tzzNZ%@fq@YD-3YDv-DZiqpN9OYn6g>|TSp4+PJ zGdMoxWQP{LI_dP@l13-nZcLZNDI;!E`y?AVl!vK0kE0XMRaJ}7L!pOUN zYvo zo&0l-t`VO@#$SSV&dU{ml|)gdl-xRw*KfnM!|e1O_zh7E4d;1}&GrF+UUJgPQk4>> G-~I=*^1jdj literal 0 HcmV?d00001 diff --git a/extensions/homebrew/screenshots/apps.png b/extensions/homebrew/screenshots/apps.png new file mode 100644 index 0000000000000000000000000000000000000000..356d6e156ebcc1631dab2a268036a4bb35beca31 GIT binary patch literal 6539 zcmeHM_dnYY(Er#}jndj0qeg4hj1{q|U2SP8F-pzY)TU-@wzYRrI*3h)RikPPMTHct z86;nlP+~luzvB7j`Q={s!@cfaclW-#*WJCcFf(Af!gB=x0H%9}x|RSyp?S&wM^AZ4 z&&}_s0|2+>JzcGbFN*ds(QbU!FU9`DuX(JH1Z5s2QQHaVVCx0F`3zII%*G4)Auqmp zN3a&ICF{|48YPa3GnmwjgI-NUQ}3O=dB^_Pmi<>H`wsy+CByUnN+!>$(Ui;Muw#`#CA)y2o0XQO7PyLdWB^lTl>nlX~x6-Kh3m5DmtH(-5J zpfCVEl4eEqPgiC^k2F|OI@8a_0CtGJeCgP~?w)a@gX7aRx_4cRV63(pn2+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ktr|Lyg+O(taQNd?sBD-ZA_1`5bPL~J5H%8YV#l@sywbk~ z5&*%k5qpwq%J)k5m5(4qma{V`aug>1B>91F*R9*MQNL>KZ*@8yZ4-)FZ-$hb2}OE~ z7gLZR#6ARgGv|bRj_!co->QI$iVqWBd{BhK-wrv3!gn`aI6}DrJEjOAV#lE*PJ0NJKIELqF#n@B;zP;ZhU~Yoh(^2cfxP-KJFou^Lpym^4dKhuP$a$T6>U z2?0^;gTPlTLALgfsd@z84+9c4QN}_mDk|>Avzu^QTjsKD0z7iY0lgB#c&~5{IRhTM zF3U*dMNjaV01$D%LM=wlIp^pPK_R*tnMIKkOjx5l&272*J<#HUUDxHFfd@8rY%pBA z4g{b87nuW<7!tHFw2e|%yrl6dr|-eL`{SgmYS72ctjrgL?QX1w^M$=1&94%JQTZbirk7m5P+PM z>v;~M8sI^2uj_Yt54Ydn-R-|CDk`>lz^uE@%lcMu$Y*9YIWhn=`Gu+YU@S&S#sUBr zJw$dTJF-y_AMw7^^MF$hp2N<>iH<^KchgGn=o(%3fu0000 Date: Fri, 27 Nov 2026 20:54:11 +0000 Subject: [PATCH 10/20] docs: link the eApp SDK in the core repository The SDK that builds Homebrew packages lives in eapp-sdk/ of the RepriseOS repository with RepriseOS/repriseos#108 and later; the Revola repository it came from is private. --- extensions/homebrew/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/homebrew/README.md b/extensions/homebrew/README.md index 8ac2d81..acad91b 100644 --- a/extensions/homebrew/README.md +++ b/extensions/homebrew/README.md @@ -2,7 +2,7 @@ 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/paviro/revola-eapp-sdk). +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 | |---|---| From 4ab29188cfc6853b191938ec0b3a4480e50c39fb Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 11:18:13 +0000 Subject: [PATCH 11/20] feat: share the sunrise schedule between extensions schedule.c and sun.c move from Night Shift to extensions/shared, compiled into each extension that reads the time zone's sunset and sunrise. The icon renderer learns to mirror a glyph. --- Makefile | 2 +- extensions/night-shift/Makefile | 3 ++- extensions/night-shift/test.c | 4 ++-- extensions/{night-shift => shared}/schedule.c | 1 - extensions/{night-shift => shared}/schedule.h | 5 +++-- extensions/shared/settings_icon.py | 6 ++++-- extensions/{night-shift => shared}/sun.c | 0 extensions/{night-shift => shared}/sun.h | 0 8 files changed, 12 insertions(+), 9 deletions(-) rename extensions/{night-shift => shared}/schedule.c (99%) rename extensions/{night-shift => shared}/schedule.h (84%) rename extensions/{night-shift => shared}/sun.c (100%) rename extensions/{night-shift => shared}/sun.h (100%) diff --git a/Makefile b/Makefile index fa9d5ae..737c342 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,7 @@ check: $(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" + $(CC) $(TEST_FLAGS) -Iextensions/shared extensions/night-shift/test.c -o "$(OUT)/test-night-shift" "$(OUT)/test-night-shift" $(CC) $(TEST_FLAGS) extensions/playback-log/test.c -o "$(OUT)/test-playback-log" "$(OUT)/test-playback-log" diff --git a/extensions/night-shift/Makefile b/extensions/night-shift/Makefile index 246d199..9be7f51 100644 --- a/extensions/night-shift/Makefile +++ b/extensions/night-shift/Makefile @@ -1,3 +1,4 @@ # SPDX-License-Identifier: GPL-3.0-only -main_SOURCES := main.c night_shift.c schedule.c sun.c +main_SOURCES := main.c night_shift.c ../shared/schedule.c ../shared/sun.c +EXTRA_CFLAGS := -I../shared include $(SDK)/rv.mk diff --git a/extensions/night-shift/test.c b/extensions/night-shift/test.c index 1f0b6d9..9f828c8 100644 --- a/extensions/night-shift/test.c +++ b/extensions/night-shift/test.c @@ -41,8 +41,8 @@ static uint8_t host_preferences[PreferencesFile_time_zone_id + 4]; static uint8_t host_browser[MediaBrowser_preferences + sizeof(void *)]; static uint8_t host_app[App_browser + sizeof(void *)]; void *App = host_app; -#include "sun.c" -#include "schedule.c" +#include "../shared/sun.c" +#include "../shared/schedule.c" #include "night_shift.c" static int allocations; diff --git a/extensions/night-shift/schedule.c b/extensions/shared/schedule.c similarity index 99% rename from extensions/night-shift/schedule.c rename to extensions/shared/schedule.c index f9c0963..1d96045 100644 --- a/extensions/night-shift/schedule.c +++ b/extensions/shared/schedule.c @@ -1,7 +1,6 @@ /* SPDX-License-Identifier: GPL-3.0-only */ #include "schedule.h" -#include "ext.h" #include "osos-2.0.5.h" #include "sun.h" #include diff --git a/extensions/night-shift/schedule.h b/extensions/shared/schedule.h similarity index 84% rename from extensions/night-shift/schedule.h rename to extensions/shared/schedule.h index 07b25b2..c82931d 100644 --- a/extensions/night-shift/schedule.h +++ b/extensions/shared/schedule.h @@ -5,8 +5,9 @@ /* The Auto schedule Dark Mode and Night Shift follow: sunset to sunrise in * the city of the time zone set under Settings > Date & Time, by the iPod's - * clock. Reading it is a few integer multiplies; the main module reads it - * once a minute while a row is on Auto. */ + * clock. Reading it is a few integer multiplies; an extension reads it once a + * minute while its row is on Auto. Compiled into each extension that uses it + * with sun.c. */ enum { SCHEDULE_NO_ZONE, /* the time zone is unset or not one of Apple's: day */ SCHEDULE_RISES, /* the sun rises and sets today */ diff --git a/extensions/shared/settings_icon.py b/extensions/shared/settings_icon.py index 659db8a..3214a80 100644 --- a/extensions/shared/settings_icon.py +++ b/extensions/shared/settings_icon.py @@ -62,9 +62,10 @@ def supersampled(work, shapes): return [mask] -def glyph(work, font, code, reach): +def glyph(work, font, code, reach, mirror=False): """magick arguments for a mask of the font's glyph at `code`, fitted into a - square of side `reach` centred on the art box.""" + square of side `reach` centred on the art box, flipped left to right when + `mirror` is set.""" path = work / f"{code:x}.png" magick( "-background", @@ -78,6 +79,7 @@ def glyph(work, font, code, reach): f"label:{chr(code)}", "-trim", "+repage", + *(["-flop"] if mirror else []), "-resize", f"{reach}x{reach}", path, diff --git a/extensions/night-shift/sun.c b/extensions/shared/sun.c similarity index 100% rename from extensions/night-shift/sun.c rename to extensions/shared/sun.c diff --git a/extensions/night-shift/sun.h b/extensions/shared/sun.h similarity index 100% rename from extensions/night-shift/sun.h rename to extensions/shared/sun.h From 944e1198e30deaca090ca521b7c683d16b4576c1 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 11:25:59 +0000 Subject: [PATCH 12/20] feat: host the Night Shift row in Appearance after Dark Mode The row opens a choice of Auto, On and Off with its own icon, and sits in the Appearance menu after Dark Mode while that extension runs, after Brightness otherwise. On Auto a read that finds no time zone at load is retried a second later, so the first screen already follows the schedule. --- extensions/night-shift/listing.toml | 2 +- extensions/night-shift/main.c | 98 +++++++++++++++++++--------- extensions/night-shift/manifest.toml | 2 +- 3 files changed, 70 insertions(+), 32 deletions(-) diff --git a/extensions/night-shift/listing.toml b/extensions/night-shift/listing.toml index f04edb1..bff6573 100644 --- a/extensions/night-shift/listing.toml +++ b/extensions/night-shift/listing.toml @@ -1,4 +1,4 @@ -details = "Press Select on Night Shift in Settings to cycle through Auto, On and Off. Auto follows sunset and sunrise in the iPod’s time zone." +details = "Night Shift in Settings opens a choice of Auto, On and Off; while the Appearance extension runs the row sits in its menu after Dark Mode. Auto follows sunset and sunrise in the iPod’s time zone." [[screenshots]] file = "screenshots/settings.png" diff --git a/extensions/night-shift/main.c b/extensions/night-shift/main.c index 9e8ca82..d33fa3c 100644 --- a/extensions/night-shift/main.c +++ b/extensions/night-shift/main.c @@ -1,79 +1,117 @@ /* SPDX-License-Identifier: GPL-3.0-only */ + +/* Night Shift: a Settings row, Auto, On or Off, in the Appearance menu after + * Dark Mode while that extension runs, after Brightness otherwise. While it is + * on Auto a minute timer reads the schedule and the warmth follows it. */ + #include "../shared/legacy.h" #include "ext.h" #include "night_shift.h" -#include "schedule.h" +#include "rv_api.h" #include "rv_menus.h" #include "rv_sites.h" #include "rv_ui.h" +#include "schedule.h" +#include const struct rv_api *api; rv_extension_handle self; enum { MODE = 1 }; -static struct rv_timer *timer; -static int has_zone; -static void tick(void *unused) +static const struct rv_setting settings[] = { + RV_SETTING_CHOICE(MODE, "Night Shift", NIGHT_SHIFT_OFF, night_shift_labels), +}; + +static struct rv_timer *timer; /* the minute tick while on Auto */ +static int zone_known; +static int first_load = 1; + +static void tick(void *arg) { - (void)unused; + (void)arg; struct schedule s; schedule_read(&s); night_shift_follow(&s); - int known = s.state != SCHEDULE_NO_ZONE; - if (known != has_zone) { - has_zone = known; + if (zone_known != (s.state != SCHEDULE_NO_ZONE)) { + zone_known = !zone_known; api->ui_pane_refresh(self); } } -static int first_load = 1; +/* The minute timer while on Auto. At load the extension runs inside Apple's + * preferences load, before the browser holds the preferences object that + * names the time zone: a read that finds no zone is tried again from the + * event loop a second later, so the first screen already follows Auto. */ +static void watch(int on) +{ + struct schedule s; + if (on && !timer) { + timer = api->timer_start(self, 60 * 1000, 1, tick, NULL); + schedule_read(&s); + zone_known = s.state != SCHEDULE_NO_ZONE; + if (!zone_known) + api->timer_start(self, 1000, 0, tick, NULL); + } + if (!on) + rv_timer_cancel(api, self, &timer); +} -static void changed(uint16_t key) +static void setting_changed(uint16_t key) { if (key == RV_SETTING_KEY_ALL) { int import = first_load; first_load = 0; migrate_switch(api, self, import, MODE, 0x5448474e, 0x31544e53, NIGHT_SHIFT_ON, NIGHT_SHIFT_OFF, RV_SETTING_TYPE_INT); + } else if (key != MODE) { + return; } int mode = api->setting_get_int(self, MODE); night_shift_set(mode); - if (mode != NIGHT_SHIFT_AUTO) { - rv_timer_cancel(api, self, &timer); - } else if (!timer) { - timer = api->timer_start(self, 60000, 1, tick, NULL); - /* The time zone service can become available after preferences load. */ - api->timer_start(self, 1000, 0, tick, NULL); - } + watch(mode == NIGHT_SHIFT_AUTO); } -static const char *caption(const struct rv_context *ctx) +static const char *pane_caption(const struct rv_context *ctx) { (void)ctx; return night_shift_caption(); } -static const struct rv_setting settings[] = { - RV_SETTING_LABELLED(MODE, "Night Shift", NIGHT_SHIFT_OFF, night_shift_labels), -}; -static const struct rv_menu_entry entries[] = { - RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_BRIGHTNESS, - RV_ROW_SETTING("Night Shift", MODE), .caption_setting = MODE, - .pane = RV_PANE(.caption_text = caption, - .bitmap = RV_BITMAP("settings-night-shift"))), -}; static const struct rv_hook hooks[] = { RV_HOOK_FILTER(RV_SITE_DisplayPipe_Init_SetGammaTables_call, night_shift_init_gamma), }; + +/* Declared for its pane icon; the screen the core makes from the setting has none. */ +static const struct rv_screen screens[] = { + RV_SCREEN_CHOICE("night-shift", "Night Shift", MODE, night_shift_labels, + .bitmap = RV_BITMAP("settings-night-shift")), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY( + RV_MENU_SETTINGS, RV_SETTINGS_BRIGHTNESS, RV_ROW_SETTING("Night Shift", MODE), + .pane = RV_PANE(.caption_text = pane_caption, + .bitmap = RV_BITMAP("settings-night-shift")), + .host = "appearance", .host_screen = "appearance", .host_after = "dark-mode"), +}; + +/* The core stops the timer itself as the module unloads. */ +static void unload(void) +{ + timer = NULL; + night_shift_stop(); +} + static const struct rv_descriptor extension = { .size = sizeof extension, + RV_HOOKS(hooks), RV_SETTINGS(settings), + .unload = unload, + .setting_changed = setting_changed, + RV_SCREENS(screens), RV_ENTRIES(entries), - RV_HOOKS(hooks), - .setting_changed = changed, - .unload = night_shift_stop, }; const struct rv_descriptor *rv_module_entry(const struct rv_api *core, diff --git a/extensions/night-shift/manifest.toml b/extensions/night-shift/manifest.toml index f6f6e5b..938f7d6 100644 --- a/extensions/night-shift/manifest.toml +++ b/extensions/night-shift/manifest.toml @@ -1,7 +1,7 @@ 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.3" +version = "0.1.4" author = "RepriseOS and RevolaOS contributors" license = "GPL-3.0-only" api = "1.89" From c1e733eec09f655eb934f57709a6384a9c9f0c97 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 12:19:27 +0000 Subject: [PATCH 13/20] feat: add the rvt theme compiler and the Classic theme rvt compiles a theme.toml folder into one .rvt file for the Appearance extension: colour roles, accents and options, replacement art, and derivation rules the iPod applies to the stock bitmaps at switch time (recolour, alias, invert, relight). Classic's dark appearance is 109 bitmaps, 108 of them derived on the device and one hand-made background, so no Apple pixels are in the repository; the catalog records names, sizes, offsets and checksums only. The core's own bitmaps are owned by the id reprise; the extension asset catalog lists the core's settings-info and every first-party extension's. Tests compare the encoder and lz copies with the SDK checkout and the extension asset catalog with the build that the next commit's Makefile writes; CI runs ruff and the tests. Adapted from RevolaOS themes 6d0ea430642b. --- .github/workflows/extensions.yml | 3 + .gitignore | 3 + extensions/crossfeed/tests/run.py | 2 +- pyproject.toml | 22 + themes/NOTICE | 18 + themes/README.md | 28 + themes/docs/README.md | 10 + themes/docs/authoring.md | 251 + themes/docs/bitmaps.md | 717 ++ themes/docs/catalog.md | 87 + themes/docs/extension-bitmaps.md | 28 + themes/docs/format.md | 111 + themes/docs/toolchain.md | 84 + themes/rvt/__init__.py | 2 + themes/rvt/__main__.py | 4 + themes/rvt/assets.py | 474 + themes/rvt/bitmaps.py | 407 + themes/rvt/catalog.py | 148 + themes/rvt/cli.py | 319 + themes/rvt/compiler.py | 422 + themes/rvt/data/__init__.py | 0 themes/rvt/data/bitmap.py | 190 + themes/rvt/data/extensions.json | 13 + themes/rvt/data/osos-2.0.5.json | 9598 +++++++++++++++++ themes/rvt/data/rvt.h | 188 + themes/rvt/derive.py | 658 ++ themes/rvt/errors.py | 7 + themes/rvt/firmware.py | 186 + themes/rvt/inspector.py | 205 + themes/rvt/lz.py | 127 + themes/rvt/rvtfile.py | 399 + themes/rvt/style.py | 189 + themes/rvt/theme.py | 396 + themes/tests/fixtures.py | 201 + themes/tests/test_assets.py | 921 ++ themes/tests/test_bitmaps.py | 278 + themes/tests/test_catalog.py | 95 + themes/tests/test_cli.py | 159 + themes/tests/test_compile.py | 467 + themes/tests/test_derive.py | 507 + themes/tests/test_format.py | 209 + themes/tests/test_style.py | 135 + themes/tests/test_theme.py | 305 + .../AddressViewer_NoContactPict_Image.toml | 1 + .../AddressViewer_NoGroupPict_Image.toml | 1 + .../dark/apple/Background_LightBlue_Image.png | Bin 0 -> 51869 bytes .../dark/apple/Calendar_Active_Cell.toml | 123 + .../dark/apple/Calendar_Inactive_Cell.toml | 43 + .../CapacityView_Detailed_Edge_Image.toml | 5 + ...pacityView_Detailed_EmptyCenter_Image.toml | 29 + ...CapacityView_Detailed_EmptyLeft_Image.toml | 78 + ...apacityView_Detailed_EmptyRight_Image.toml | 78 + .../apple/CoverFlow_Backside_Top_Image.toml | 72 + .../dark/apple/CoverFlow_Proxy_Image.toml | 112 + .../apple/CoverFlow_Proxy_Image_iTunesU.toml | 113 + .../DiskModeImage_Progress_Empty_Fill.toml | 7 + .../DiskModeImage_Progress_Empty_LeftCap.toml | 41 + ...DiskModeImage_Progress_Empty_RightCap.toml | 51 + .../classic/dark/apple/Games_Proxy_Image.toml | 1 + .../dark/apple/Genius_Slider_Image.toml | 120 + .../dark/apple/Lozenge_Left_White_Image.toml | 184 + .../apple/Lozenge_Middle_White_Image.toml | 100 + .../dark/apple/Lozenge_Right_White_Image.toml | 179 + .../dark/apple/Media_AlbumsProxy_Image.toml | 1 + .../dark/apple/Media_ArtistsProxy_Image.toml | 1 + .../apple/Media_AudioBooksProxy_Image.toml | 1 + .../dark/apple/Media_AudioProxy_Image.toml | 1 + .../apple/Media_DocumentsProxy_Image.toml | 1 + .../dark/apple/Media_Genius_Normal_Image.toml | 168 + .../apple/Media_Genius_Refresh_Image.toml | 92 + .../apple/Media_MusicVideosProxy_Image.toml | 1 + .../dark/apple/Media_OTGPlaylist_Image.toml | 106 + .../dark/apple/Media_PhotosProxy_Image.toml | 1 + .../apple/Media_PlaylistsProxy_Image.toml | 1 + .../dark/apple/Media_PodcastsProxy_Image.toml | 1 + .../dark/apple/Media_SearchProxy_Image.toml | 1 + .../dark/apple/Media_TVShowsProxy_Image.toml | 1 + .../apple/Media_VideoStatusIcon_Image.toml | 6 + .../dark/apple/Media_VideosProxy_Image.toml | 1 + .../apple/No_Content_iTunesU_Small_Image.toml | 48 + .../NowPlaying_Classic_Repeat_Image.toml | 27 + .../NowPlaying_Classic_Repeat_Once_Image.toml | 61 + .../NowPlaying_Classic_Shuffle_Image.toml | 70 + .../dark/apple/NowPlaying_Dot_Image.toml | 17 + .../apple/NowPlaying_Large_Shuffle_Image.toml | 94 + ...g_ProgressBar_Active_Background_Image.toml | 38 + .../dark/apple/NowPlaying_White_FF_Image.toml | 113 + .../apple/NowPlaying_White_Rew_Image.toml | 113 + .../NowPlaying_White_Volume_High_Image.toml | 54 + .../NowPlaying_White_Volume_Low_Image.toml | 28 + ...tionBar_NowPlaying_Thumb_Center_Image.toml | 28 + ...ionBar_NowPlaying_Thumb_LeftCap_Image.toml | 50 + ...onBar_NowPlaying_Thumb_RightCap_Image.toml | 50 + ...ptionBar_NowPlaying_Well_Center_Image.toml | 27 + ...tionBar_NowPlaying_Well_LeftCap_Image.toml | 72 + ...ionBar_NowPlaying_Well_RightCap_Image.toml | 72 + .../OptionBar_White_Well_Center_Image.toml | 30 + .../OptionBar_White_Well_LeftCap_Image.toml | 146 + .../OptionBar_White_Well_RightCap_Image.toml | 146 + .../dark/apple/Playlist_Genius_Icon.toml | 257 + .../dark/apple/Podcasts_video_solo_Image.toml | 6 + .../dark/apple/Settings_About_Band_Image.toml | 515 + ...ettings_About_Bubble_Deselected_Image.toml | 7 + .../Settings_About_Capacity_Fill_Image.toml | 29 + ...Settings_About_Capacity_LeftCap_Image.toml | 78 + ...ettings_About_Capacity_RightCap_Image.toml | 78 + .../Settings_DateTime_Calendar_Image.toml | 185 + ...ettings_MainMenu_CheckmarkBlack_Image.toml | 6 + .../StatusBarWhite_Background_Image.toml | 23 + .../apple/StatusBarWhite_Battery_Image_0.toml | 59 + .../apple/StatusBarWhite_Battery_Image_1.toml | 71 + .../StatusBarWhite_Battery_Image_10.toml | 64 + .../StatusBarWhite_Battery_Image_11.toml | 58 + .../StatusBarWhite_Battery_Image_12.toml | 61 + .../StatusBarWhite_Battery_Image_13.toml | 58 + .../StatusBarWhite_Battery_Image_14.toml | 57 + .../StatusBarWhite_Battery_Image_15.toml | 55 + .../StatusBarWhite_Battery_Image_16.toml | 56 + .../StatusBarWhite_Battery_Image_17.toml | 57 + .../StatusBarWhite_Battery_Image_18.toml | 50 + .../StatusBarWhite_Battery_Image_19.toml | 50 + .../apple/StatusBarWhite_Battery_Image_2.toml | 68 + .../StatusBarWhite_Battery_Image_20.toml | 47 + .../StatusBarWhite_Battery_Image_21.toml | 37 + .../StatusBarWhite_Battery_Image_22.toml | 27 + .../apple/StatusBarWhite_Battery_Image_3.toml | 67 + .../apple/StatusBarWhite_Battery_Image_4.toml | 67 + .../apple/StatusBarWhite_Battery_Image_5.toml | 69 + .../apple/StatusBarWhite_Battery_Image_6.toml | 65 + .../apple/StatusBarWhite_Battery_Image_7.toml | 65 + .../apple/StatusBarWhite_Battery_Image_8.toml | 61 + .../apple/StatusBarWhite_Battery_Image_9.toml | 62 + .../StatusBarWhite_Battery_Image_Charge.toml | 57 + .../StatusBarWhite_Battery_Image_Plug.toml | 46 + .../dark/apple/StatusBarWhite_Lock_Image.toml | 44 + .../apple/System_Input_Field_Left_Image.toml | 51 + .../System_Input_Field_Middle_Image.toml | 17 + .../apple/System_Input_Field_Right_Image.toml | 53 + .../apple/System_ScrollbarBottom_Image.toml | 10 + .../apple/System_ScrollbarCenter_Image.toml | 5 + .../dark/apple/System_ScrollbarTop_Image.toml | 10 + .../dark/apple/WorldClock_Graybar_Image.toml | 70 + themes/themes/classic/fit.py | 74 + themes/themes/classic/recolor.py | 169 + themes/themes/classic/theme.toml | 14 + themes/tools/bitmaps_doc.py | 105 + themes/tools/extension_bitmaps_doc.py | 63 + themes/tools/extensions_catalog.py | 49 + 148 files changed, 24930 insertions(+), 1 deletion(-) create mode 100644 pyproject.toml create mode 100644 themes/NOTICE create mode 100644 themes/README.md create mode 100644 themes/docs/README.md create mode 100644 themes/docs/authoring.md create mode 100644 themes/docs/bitmaps.md create mode 100644 themes/docs/catalog.md create mode 100644 themes/docs/extension-bitmaps.md create mode 100644 themes/docs/format.md create mode 100644 themes/docs/toolchain.md create mode 100644 themes/rvt/__init__.py create mode 100644 themes/rvt/__main__.py create mode 100644 themes/rvt/assets.py create mode 100644 themes/rvt/bitmaps.py create mode 100644 themes/rvt/catalog.py create mode 100644 themes/rvt/cli.py create mode 100644 themes/rvt/compiler.py create mode 100644 themes/rvt/data/__init__.py create mode 100644 themes/rvt/data/bitmap.py create mode 100644 themes/rvt/data/extensions.json create mode 100644 themes/rvt/data/osos-2.0.5.json create mode 100644 themes/rvt/data/rvt.h create mode 100644 themes/rvt/derive.py create mode 100644 themes/rvt/errors.py create mode 100644 themes/rvt/firmware.py create mode 100644 themes/rvt/inspector.py create mode 100644 themes/rvt/lz.py create mode 100644 themes/rvt/rvtfile.py create mode 100644 themes/rvt/style.py create mode 100644 themes/rvt/theme.py create mode 100644 themes/tests/fixtures.py create mode 100644 themes/tests/test_assets.py create mode 100644 themes/tests/test_bitmaps.py create mode 100644 themes/tests/test_catalog.py create mode 100644 themes/tests/test_cli.py create mode 100644 themes/tests/test_compile.py create mode 100644 themes/tests/test_derive.py create mode 100644 themes/tests/test_format.py create mode 100644 themes/tests/test_style.py create mode 100644 themes/tests/test_theme.py create mode 100644 themes/themes/classic/dark/apple/AddressViewer_NoContactPict_Image.toml create mode 100644 themes/themes/classic/dark/apple/AddressViewer_NoGroupPict_Image.toml create mode 100644 themes/themes/classic/dark/apple/Background_LightBlue_Image.png create mode 100644 themes/themes/classic/dark/apple/Calendar_Active_Cell.toml create mode 100644 themes/themes/classic/dark/apple/Calendar_Inactive_Cell.toml create mode 100644 themes/themes/classic/dark/apple/CapacityView_Detailed_Edge_Image.toml create mode 100644 themes/themes/classic/dark/apple/CapacityView_Detailed_EmptyCenter_Image.toml create mode 100644 themes/themes/classic/dark/apple/CapacityView_Detailed_EmptyLeft_Image.toml create mode 100644 themes/themes/classic/dark/apple/CapacityView_Detailed_EmptyRight_Image.toml create mode 100644 themes/themes/classic/dark/apple/CoverFlow_Backside_Top_Image.toml create mode 100644 themes/themes/classic/dark/apple/CoverFlow_Proxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/CoverFlow_Proxy_Image_iTunesU.toml create mode 100644 themes/themes/classic/dark/apple/DiskModeImage_Progress_Empty_Fill.toml create mode 100644 themes/themes/classic/dark/apple/DiskModeImage_Progress_Empty_LeftCap.toml create mode 100644 themes/themes/classic/dark/apple/DiskModeImage_Progress_Empty_RightCap.toml create mode 100644 themes/themes/classic/dark/apple/Games_Proxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Genius_Slider_Image.toml create mode 100644 themes/themes/classic/dark/apple/Lozenge_Left_White_Image.toml create mode 100644 themes/themes/classic/dark/apple/Lozenge_Middle_White_Image.toml create mode 100644 themes/themes/classic/dark/apple/Lozenge_Right_White_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_AlbumsProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_ArtistsProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_AudioBooksProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_AudioProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_DocumentsProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_Genius_Normal_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_Genius_Refresh_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_MusicVideosProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_OTGPlaylist_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_PhotosProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_PlaylistsProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_PodcastsProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_SearchProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_TVShowsProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_VideoStatusIcon_Image.toml create mode 100644 themes/themes/classic/dark/apple/Media_VideosProxy_Image.toml create mode 100644 themes/themes/classic/dark/apple/No_Content_iTunesU_Small_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_Classic_Repeat_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_Classic_Repeat_Once_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_Classic_Shuffle_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_Dot_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_Large_Shuffle_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_ProgressBar_Active_Background_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_White_FF_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_White_Rew_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_White_Volume_High_Image.toml create mode 100644 themes/themes/classic/dark/apple/NowPlaying_White_Volume_Low_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_NowPlaying_Thumb_Center_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_NowPlaying_Thumb_LeftCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_NowPlaying_Thumb_RightCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_NowPlaying_Well_Center_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_NowPlaying_Well_LeftCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_NowPlaying_Well_RightCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_White_Well_Center_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_White_Well_LeftCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/OptionBar_White_Well_RightCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/Playlist_Genius_Icon.toml create mode 100644 themes/themes/classic/dark/apple/Podcasts_video_solo_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_About_Band_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_About_Bubble_Deselected_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_About_Capacity_Fill_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_About_Capacity_LeftCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_About_Capacity_RightCap_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_DateTime_Calendar_Image.toml create mode 100644 themes/themes/classic/dark/apple/Settings_MainMenu_CheckmarkBlack_Image.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Background_Image.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_0.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_1.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_10.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_11.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_12.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_13.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_14.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_15.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_16.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_17.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_18.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_19.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_2.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_20.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_21.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_22.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_3.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_4.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_5.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_6.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_7.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_8.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_9.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_Charge.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Battery_Image_Plug.toml create mode 100644 themes/themes/classic/dark/apple/StatusBarWhite_Lock_Image.toml create mode 100644 themes/themes/classic/dark/apple/System_Input_Field_Left_Image.toml create mode 100644 themes/themes/classic/dark/apple/System_Input_Field_Middle_Image.toml create mode 100644 themes/themes/classic/dark/apple/System_Input_Field_Right_Image.toml create mode 100644 themes/themes/classic/dark/apple/System_ScrollbarBottom_Image.toml create mode 100644 themes/themes/classic/dark/apple/System_ScrollbarCenter_Image.toml create mode 100644 themes/themes/classic/dark/apple/System_ScrollbarTop_Image.toml create mode 100644 themes/themes/classic/dark/apple/WorldClock_Graybar_Image.toml create mode 100644 themes/themes/classic/fit.py create mode 100644 themes/themes/classic/recolor.py create mode 100644 themes/themes/classic/theme.toml create mode 100644 themes/tools/bitmaps_doc.py create mode 100644 themes/tools/extension_bitmaps_doc.py create mode 100644 themes/tools/extensions_catalog.py diff --git a/.github/workflows/extensions.yml b/.github/workflows/extensions.yml index a9141bf..eb73062 100644 --- a/.github/workflows/extensions.yml +++ b/.github/workflows/extensions.yml @@ -48,10 +48,13 @@ jobs: env: CROSS_COMPILE: ${{ github.workspace }}/toolchains/rockbox-arm/bin/arm-elf-eabi- run: | + pipx run ruff==0.12.12 check . + pipx run ruff==0.12.12 format --check themes tools tests make -j8 make check python3 tools/catalog.py preview python3 -m unittest discover -s tests + python3 -m unittest discover -s themes/tests - name: Select tagged package if: github.ref_type == 'tag' shell: bash diff --git a/.gitignore b/.gitignore index 048042b..fb4414a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ build/ __pycache__/ +.ruff_cache/ .DS_Store +themes/dist/ +*.rvt diff --git a/extensions/crossfeed/tests/run.py b/extensions/crossfeed/tests/run.py index 00bc001..b586883 100644 --- a/extensions/crossfeed/tests/run.py +++ b/extensions/crossfeed/tests/run.py @@ -275,7 +275,7 @@ def simple_response(hz): h = simple_response(hz) for amplitude, expected in ( (max(abs(r) for _, r in out), abs(h)), - (max(abs(l) for l, _ in out), abs(1 - h)), + (max(abs(left) for left, _ in out), abs(1 - h)), ): got = 20 * math.log10(amplitude / 20000) assert abs(got - 20 * math.log10(expected)) < 0.1, (hz, got, expected) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b1448e6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: GPL-3.0-only + +[tool.ruff] +required-version = "==0.12.12" +target-version = "py311" +line-length = 88 +extend-exclude = ["build", ".sdk", ".rockbox", "toolchains"] + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I"] + +[tool.ruff.lint.isort] +known-first-party = ["fixtures", "rvt"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" + +[tool.ruff.lint.per-file-ignores] +# Scripts that put another directory on sys.path before importing from it. +"extensions/*/assets/render.py" = ["E402"] +"tools/catalog.py" = ["E402"] diff --git a/themes/NOTICE b/themes/NOTICE new file mode 100644 index 0000000..40a568a --- /dev/null +++ b/themes/NOTICE @@ -0,0 +1,18 @@ +RepriseOS themes +Copyright (C) lgreitis and RepriseOS contributors. GPL-3.0-only. + +The rvt compiler and the Classic theme are adapted from the RevolaOS themes +repository, revision 6d0ea430642b, copyright 2026 The RevolaOS Authors. +GPL-3.0-only. + +Third-party work included: + +- The Classic theme's dark background, + themes/classic/dark/apple/Background_LightBlue_Image.png, is the RepriseOS + core's former themes/dark/background-dark-image.png by lgreitis (5ec8799). + Its dark palette comes from the core's former payload/dark_mode.c (01c89f6) + by lgreitis and Alex Ball (alexballvideos-netizen). GPL-3.0-only. + +No Apple firmware or artwork ships in this directory. The catalog records the +names, sizes, offsets and checksums of Apple's bitmaps, and Classic's recolour +rules list the colour values they change; neither holds any pixels. diff --git a/themes/README.md b/themes/README.md new file mode 100644 index 0000000..86a413e --- /dev/null +++ b/themes/README.md @@ -0,0 +1,28 @@ +# themes + +First-party themes for RepriseOS and the compiler that builds a theme folder into one `/Reprise/Themes/.rvt` file for the Appearance extension. A theme sets colours, accents and rendering options, and replaces or derives Apple's bitmaps. Authoring needs only Python. + +| Directory | Theme | What it looks like | Appearances | +|---|---|---|---| +| `themes/classic` | Classic | The stock art relit, recoloured and inverted on the iPod. Ships inside the Appearance extension | dark | + +## Build + +From the `themes/` directory: + +```sh +python3 -m rvt compile themes/classic --allow-reserved # into dist/classic/classic.rvt +python3 -m rvt inspect dist/classic/classic.rvt +``` + +Copy `.rvt` to `/Reprise/Themes/`. Classic's recolour rule files are generated by `themes/classic/recolor.py --firmware osos.bin` from a decrypted 2.0.5 firmware. `--check` confirms the committed files match. The other commands, the tests and the package layout are in [The compiler](docs/toolchain.md). + +## Documentation + +| Page | Contents | +|---|---| +| [docs/](docs/README.md) | Authoring, the compiler, the file format, the catalogs, the bitmaps | + +## License + +GPL-3.0-only. See COPYING at the repository root and NOTICE in this directory. diff --git a/themes/docs/README.md b/themes/docs/README.md new file mode 100644 index 0000000..bf4752e --- /dev/null +++ b/themes/docs/README.md @@ -0,0 +1,10 @@ +# Themes documentation + +| Page | Contents | +|---|---| +| [Authoring](authoring.md) | The theme folder, `theme.toml`, colour roles, art, tints, derived art, limits | +| [The compiler](toolchain.md) | The `rvt` commands, warnings, `report.json`, the package layout, tests | +| [File format](format.md) | The `.rvt` layout | +| [Catalog](catalog.md) | Apple's bitmaps and the extension asset catalog, the fingerprint, regenerating | +| [Bitmaps](bitmaps.md) | Every Apple bitmap a theme can replace | +| [Extension bitmaps](extension-bitmaps.md) | The first-party extension bitmaps a theme can replace | diff --git a/themes/docs/authoring.md b/themes/docs/authoring.md new file mode 100644 index 0000000..ea515c6 --- /dev/null +++ b/themes/docs/authoring.md @@ -0,0 +1,251 @@ +# Authoring a theme + +A theme is a folder compiled into one `.rvt` file. It sets colours, a palette per accent and a few rendering options, and replaces Apple's bitmaps with same-size art or with rules that derive them. Keys in `theme.toml` and the rule files use American spelling (`colors`, `recolor`). + +## Quickstart + +1. `python3 -m rvt new mytheme` writes `mytheme/theme.toml` with every role and option commented out, and empty `light/` and `dark/` folders, each with `apple/`, `reprise/` and `extensions/`. Run `python3 -m rvt` from the `themes/` directory. +2. Edit `theme.toml`. Put art in `light/apple/` and `dark/apple/`, named after the [bitmaps](bitmaps.md) it replaces, and [extension bitmaps](#extension-bitmaps) in `light/extensions//` and `dark/extensions//`. +3. `python3 -m rvt check mytheme` prints what each rule matched, the warnings and a size table. It writes nothing. +4. `python3 -m rvt compile mytheme` writes `dist/mytheme/mytheme.rvt` and `report.json`. `--strict` turns warnings into errors. +5. Copy `mytheme.rvt` to `/Reprise/Themes/` on the iPod. It appears under Settings > Appearance > Theme. + +The iPod derives the theme's art from `/osos-cfw.bin`, so that file must be the build that is running; a mismatch leaves the look unchanged and the Theme row reports it. + +``` +mytheme/ + theme.toml + light/ + apple/ art for the light appearance: a PNG per replaced Apple bitmap, a TOML per derived one + extensions/ one folder per extension id, with a PNG per bitmap asset it replaces + reprise/ a PNG per bitmap of the core it replaces; `reprise` is the reserved owner id of the core's own bitmaps + dark/ the same for dark +``` + +A file directly under `light/` or `dark/` is an error. + +## theme.toml + +```toml +schema = 1 +id = "mytheme" # the file's stem; "classic" is the built-in theme +name = "My Theme" # shown in Settings +author = "..." # optional, report only +version = "1.0" # optional, report only + +[light] +menu_covers_default = true # the Menu Covers setting until the listener chooses one + +[light.colors] # any subset of the roles below, "#rrggbb" +accent_fill = "#0071e3" +icon_tint = "#0071e3" # left out, it follows accent_text + +[light.accents] # one colour per accent, or a table; see Accents +blue = "#007aff" +yellow = { accent = "#ffcc00", on_accent = "#000000" } + +[light.rendering] +flat_selection = false +flat_now_playing = false + +[light.tint] # role = [catalog names, globs or id/asset]; see Tint +icon_tint = ["Settings_EQ_*_Image", "Media_*Proxy_Image"] +text = ["StatusBar*_Battery_Image_[3-9]", "StatusBar*_Battery_Image_[12][0-9]"] +darkness_coverage = ["NowPlaying_Blue_Dot_Image"] +solid_coverage = ["Settings_AppleLogo_Image"] + +[light.derive] # rules for derived art; see Derived art +"Settings_Brightness_Image" = { kind = "invert" } + +[dark] # the same tables; an empty table is Classic dark colours and no art +``` + +Declare `[light]`, `[dark]` or both. For a missing appearance the iPod keeps Classic, and turning Dark Mode on with a light-only theme says the theme has no dark appearance. Unknown keys are rejected. `fonts`, `layouts`, `metrics`, `animations`, `sounds`, `strings` and `wallpapers` are rejected as unsupported. + +### Colour roles + +Roles left out keep their Classic value, except `icon_tint`, which follows `accent_text`. + +| Role | Light | Dark | What it colours | +|---|---|---|---| +| `background` | `#ffffff` | `#181818` | Native surfaces; labels on light art | +| `text` | `#202020` | `#e8e8e8` | Native text; labels on dark art | +| `accent_fill` | `#236cc5` | `#00a1ff` | Native accent fills; stock progress, dot, star and playback art the theme leaves stock | +| `accent_text` | `#3185d0` | `#00a1ff` | Native accent text, the Search caret | +| `on_accent` | `#ffffff` | `#ffffff` | Selected-row text and tinted icons on the selection bar, the highlighted Search key, the selected calendar day | +| `selection` | `#236cc5` | `#00a1ff` | The list selection bar; stock selection and focus art the theme leaves stock | +| `cover_border` | `#7e8183` | `#383838` | Cover Flow border | +| `icon_tint` | `#3185d0` | `#00a1ff` | Tinted icons: the Settings icons of extensions and the bitmaps `[tint]` lists under it | + +Keep `on_accent` readable on both `accent_fill` and `selection`. `report.json` lists the contrast of each text and background pair for Theme Default and every accent, and `rvt check` warns about pairs the theme colours that fall below 4.5:1. + +Labels Apple draws in a fixed colour over art take `text` or `background`, whichever differs more in brightness from the centre pixel of the art behind them: + +| Label | Art | +|---|---| +| Stopwatch and Charging header title | `NowPlaying_StatusBar_Image` | +| Screen Lock and Volume Limit combination digits | `LockScreen_TumblerBgnd_Image` | +| Date and time picker values | `DateTimePicker_Well` | +| Cover Flow album title and artist (track list) | `CoverFlow_Backside_Top_Image` | +| Calendar days of the shown month | `Calendar_Active_Cell` | + +Keep `LockScreen_TumblerFocus_Image` and `DateTimePicker_Selection` about as light or dark as the art above. The focused digit and selected value use the same colour as the rest. + +Calendar days of neighbouring months follow the rule against `Calendar_Inactive_Cell`, mixed halfway toward the cell. Weekday names follow it against `background`, as does a cell with a transparent centre. The selected day and its tinted markers use `on_accent` on `Calendar_Hilite_Cell`. + +The Search letter strip and option bars (such as the Clock's Add/Edit bar) follow the rule against the well art (`OptionBar_*_Well_Center_Image`). The highlighted letter uses `on_accent` on the thumb, so keep it readable there. The shuffle selector on Now Playing follows the same rule against its own well under a theme and in Classic's dark appearance, whose art repaints that well. Its thumb does not follow the accent, so in Classic the highlighted label keeps its stock colour. Text typed into the Search box follows the rule against `System_Input_Field_Middle_Image`, and its caret uses `accent_text`. + +Apart from that, Classic keeps the stock colours of all these labels. + +### Accents + +The accents are `blue`, `purple`, `pink`, `red`, `orange`, `green`, `teal`, `yellow` and `graphite`. Each has a built-in fill (`accent_fill`, `selection`) and text colour (`accent_text`, `icon_tint`) per appearance, and uses the appearance's `on_accent`. Blue is Classic's. In `[light.accents]` an accent takes one of these forms: + +| Form | Sets | +|---|---| +| `blue = "#007aff"` | `accent_fill`, `accent_text`, `selection` and `icon_tint` to that colour | +| `yellow = { accent = "#ffcc00", on_accent = "#000000" }` | the same four, and `on_accent` | +| `teal = { accent_fill = "...", accent_text = "...", selection = "...", on_accent = "...", icon_tint = "..." }` | any subset of the five palette slots, each named after the role it replaces | + +Accents left out keep the built-in colours. `report.json` lists them under `accents_builtin`. + +### Menu Covers + +`menu_covers_default`, directly in `[light]` or `[dark]`, sets whether the Main and Music menus show the highlighted row's cover until the listener changes Menu Covers. The default is `true`. + +### Rendering + +| Key | Default | `true` / `false` | +|---|---|---| +| `flat_selection` | `false` | `true`: `selection` throughout the bar. `false`: a gradient ending at `selection`, starting at `selection` lightened 25 % toward white, with a top line lightened 55 % | +| `flat_now_playing` | `false` | `true`: the cover face-on, no reflection; Cover Flow is unchanged. `false`: the tilted cover with its reflection. The flag holds until the listener changes Now Playing Cover | +| `flat_icons` | `false` | `true`: the Settings icons of [extensions](#extension-bitmaps) the theme does not replace are drawn without their reflection. `false`: they keep it | + +Stock blue art for selection, focus and progress that the theme leaves stock is recoloured with `selection` or `accent_fill`, keeping its shading. This covers option bar thumbs, the active button, picker and calendar highlights, the Settings checkmark, the progress and Genius sliders, new-item dots, rating stars and playback glyphs. Replaced art is not recoloured. + +Screens RepriseOS draws itself mix their greys from `background` toward `text`, draw the highlighted row or the cell being edited on the lists' selection bar with `on_accent` text, tint the selected cell from `background` toward `accent_text`, and use `accent_text` for accent text. + +## Art + +A file in `light/apple/` or `dark/apple/` is named after a catalog bitmap. `Settings_About_Band_Image.png` replaces its pixels; `Settings_About_Band_Image.toml` [derives](#derived-art) them from the stock bitmap. A name the catalog lists more than once is given as its hex id, such as `light/apple/0x0DAD012A.png`. Every file must match a catalog bitmap, once per appearance. + +Art must be the bitmap's exact native size. The compiler converts it to the native format: + +| Format | Art | +|---|---| +| Masks (4 and 8) | Opaque grayscale; 4-bit masks round to 16 levels | +| Paletted (0x64, 0x65) | Any RGBA; extra colours are reduced to fit the native palette, with a warning (`palette_reduced` in `report.json`) | +| RGB565 | Opaque | +| BGRA8888 (0x1888) | Any RGBA | + +### Tint + +`[light.tint]` draws bitmaps in a colour role, following the picked accent. Each key is a role listing catalog names, hex ids, case-sensitive globs (`*`, `?`, `[...]`) or extension bitmaps as `/` ([below](#extension-bitmaps)). A glob that matches nothing is a warning; an unknown name is an error. A bitmap may appear under one role only. + +Coverage comes from the PNG if there is one (its alpha, else its gray level; coloured opaque art is rejected), otherwise from the stock bitmap. Tinted art with more coverage levels than the palette holds is reduced on coverage alone. + +| Format | Needs art | How it is tinted | +|---|---|---| +| Masks | No | At draw time | +| Paletted | No | Palette entries rewritten, alpha kept | +| BGRA8888 | No | Pixels rewritten, alpha kept | +| RGB565 | Cannot be tinted | | + +`darkness_coverage` lists tinted bitmaps whose coverage is their darkness instead of their alpha, for stock glyphs drawn black on transparent. `solid_coverage` lists tinted bitmaps drawn flat: coverage levels from 150 of 255 up become full and lower levels stay, for stock masks with gloss in their levels, such as the Apple logo. A bitmap can be in only one of the two, and both apply to stock bitmaps only, not to a PNG. A tinted bitmap cannot also be derived. + +### Derived art + +A rule describes a bitmap as a change to the stock bitmap, which the iPod computes from its firmware when the theme is applied. A rule is either an entry of `[dark.derive]`, keyed by catalog name, hex id or glob, or a file `dark/apple/.toml` with the same table. The file suits a long recolour map. A `[derive]` rule must match at least one bitmap, none with a PNG or `.toml`, and no bitmap matched by another rule. A rule has a `kind` and that kind's keys: + +| `kind` | Keys | Formats | Result | +|---|---|---|---| +| `recolor` | `[map]`: `"#rrggbbaa" = "#rrggbbaa"`, a stock colour and its replacement; keys must be quoted | paletted, BGRA8888, RGB565 | Each palette entry, pixel or RGB565 word equal to a stock colour in the map takes its replacement; the rest stay | +| `alias` | `source`: a catalog name or hex id | any but masks, the same size | The pixels of `source` (the theme's version if it has one, else stock), re-encoded when the layouts differ; a paletted target must have room for the source's colours | +| `invert` | | any but masks | RGB inverted, alpha kept | +| `relight` | the rule's values, all optional, below | paletted | A light icon on a light square redrawn as grays on a dark one | + +Any kind may add `from_other = true` to start from the theme's PNG for that bitmap in the other appearance instead of the stock bitmap. The compiler computes and stores the result. That PNG must exist and must not be tinted. An alias with `from_other` takes the other appearance's PNG of `source`, or of the bitmap itself when `source` is left out. + +```toml +# theme.toml +[dark.derive] +"Clock_*_Image_*" = { kind = "alias", from_other = true } # every digit reuses its light art +"Settings_Brightness_Image" = { kind = "invert", from_other = true } +"NowPlaying_White_Pause_Image" = { kind = "alias", source = "NowPlaying_Black_Pause_Image" } +"Media_*Proxy_Image" = { kind = "relight" } + +# dark/apple/System_ScrollbarCenter_Image.toml +kind = "recolor" +[map] +"#ffffff26" = "#91919126" +"#00000073" = "#7e7e7e73" +``` + +On RGB565 both recolour colours are opaque, with `r` and `b` multiples of 8 and `g` a multiple of 4. An alias may not point at another alias or a tinted bitmap. Aliases with `from_other` do not count against the alias [limit](#limits). + +#### Relight keys + +The keys are `t_zero` and `t_full` (the offsets from the row's background at which a pixel counts as no icon and as all icon), `bg_base`, `bg_ref`, `bg_slope`, `bg_lo`, `bg_hi`, `icon_base`, `icon_luma`, `icon_row`, `icon_lo` and `icon_hi`. [File format](format.md#relight) gives the arithmetic. The defaults are Classic's: `t_zero = 3`, `t_full = 14`, `bg_base = 25`, `bg_ref = 216`, `bg_slope = 0.357` (stored as 91/256), `bg_lo = 24`, `bg_hi = 35`, `icon_base = 394.6`, `icon_luma = -1.170`, `icon_row = -1.769`, `icon_lo = 40`, `icon_hi = 160`. + +Values are rounded to 1/256 and must satisfy `0 <= t_zero < t_full <= 255`, `0 <= bg_lo <= bg_hi <= icon_lo <= icon_hi <= 255`, `bg_base` and `icon_base` within ±1024, `bg_ref`, `icon_luma` and `icon_row` within ±255 and `bg_slope` within ±16. The bitmap must have at most 3,840 pixels and a palette of at least `icon_hi - bg_lo + 1` entries. + +#### Recolour rule from a PNG + +With a decrypted firmware: + +```sh +python3 -m rvt recolor mytheme/dark/apple/Foo.png --firmware osos.bin +``` + +writes `dark/apple/Foo.toml` when the PNG is a pure recolour of the stock bitmap, ignoring small dithering and stray pixels. Otherwise it lists the stock colours painted in more than one colour. Delete the PNG to use the rule. + +#### Previewing derived art + +```sh +python3 -m rvt preview mytheme --firmware osos.bin +``` + +renders every derived bitmap to `dist/mytheme/derived//.png`, writes `derived.json` with the address, size and CRC-32 of each, and warns about map colours that match nothing. + +## Extension bitmaps + +Extensions ship bitmaps as assets: the 78 x 121 Settings icon of their row and any pictures their screens draw. `light/extensions//.png` replaces asset `` of extension `` in light, `dark/extensions/` in dark. The core's id is `reprise`, the reserved owner id of the core's own bitmaps in the theme format, and its bitmaps go in `light/reprise/` and `dark/reprise/`. The extension asset [catalog](catalog.md#extension-asset-catalog) lists which bitmaps exist: + +```sh +python3 -m rvt catalog list --extensions # id, asset, size, format, palette, menu +python3 -m rvt catalog list --extensions --group appearance +python3 -m rvt catalog show appearance/settings-moon +``` + +[Extension bitmaps](extension-bitmaps.md) is the same list as a page. For an extension outside the built-in catalog, pass its `assets.json` to `check`, `compile` and `inspect` with `--extension` (repeatable). Its author makes the file with `python3 /assets.py manifest.toml file.rvx > assets.json`. The compiler encodes the art as the extension's build would: + +| Bitmap | Art | Stored as | +|---|---|---| +| Settings icon (`menu` in the catalog) | Exactly 78 x 121; coverage is the alpha if any pixel is translucent, else the gray level; coloured opaque art is rejected | A Mask8 coverage mask drawn in the icon tint | +| Any other bitmap | Exactly the catalog's width and height, any RGBA | Indexed8 with a palette when the art has at most 256 colours, else BGRA8888; at most 65,536 bytes with its header | + +A `[tint]` role can list a picture as `/` (`reprise/` for the core). `icon_tint = ["homebrew/apps"]` reads `extensions/homebrew/apps.png` as coverage, like a Settings icon, and draws it in that role. The PNG is needed in every appearance that lists it, `darkness_coverage` and `solid_coverage` do not apply, and Settings icons cannot be listed because they are already drawn in the icon tint. + +An unknown (id, asset) compiles only as a Settings icon, from a 78 x 121 coverage PNG, with a warning. Any other size is an error asking for `--extension`. The iPod ignores bitmaps no installed extension uses. + +A Settings icon's art box is rows 12..62, centred on column 39. Stock icons hold their reflection from row 79 down. With `flat_icons` ([Rendering](#rendering)) off, an icon with nothing below row 78 is a warning, because the icons the theme leaves stock keep their reflection. Icons are coverage in both appearances, so one shape goes into both folders. + +## Limits + +| What | Limit | +|---|---| +| `id` | `[a-z0-9][a-z0-9_-]{0,30}`; `classic` is reserved | +| `name` | at most 47 UTF-8 bytes, no control characters | +| Art size | the bitmap's native width and height, nothing else; Settings icons 78 x 121, other extension bitmaps the catalog's size | +| Extension bitmaps | at most 64 per appearance, each at most 65,536 bytes encoded; ids `[a-z][a-z0-9_-]{0,31}`, assets `[a-z0-9_-]{1,31}`, no two with equal hashes; a tinted one is a picture, not a Settings icon | +| Art files | non-interlaced PNG with 8-bit channels or a palette, at most 16 MiB; plain file names inside the folder, no symlinks that leave it | +| `theme.toml`, rule files | at most 256 KiB each | +| Palette per bitmap | the native palette's entries (see [Bitmaps](bitmaps.md)); more colours are reduced with a warning | +| Recolour map | at most 512 pairs, and no more than the bitmap has palette entries or pixels | +| Aliases of stock art | at most 16 per appearance; an alias between differing layouts is re-encoded on the iPod and allowed for bitmaps of at most 3,840 pixels | +| Relight | bitmaps of at most 3,840 pixels; the bounds above | +| Colours | opaque `#rrggbb`; translucent roles are not supported | + +## Unsupported + +Fonts, layouts, metrics, animations, sounds, strings, wallpapers, new bitmaps, bitmaps of another size, translucent colours and appearances other than light and dark. diff --git a/themes/docs/bitmaps.md b/themes/docs/bitmaps.md new file mode 100644 index 0000000..e45da03 --- /dev/null +++ b/themes/docs/bitmaps.md @@ -0,0 +1,717 @@ +# Bitmaps + +Every bitmap of Apple's 2.0.5 firmware a theme can replace, from the +[catalog](catalog.md), grouped by name prefix. Size is width x height in +pixels. Palette is the number of native palette entries. Tintable says whether +`[.tint]` may name it. Appears is filled in by hand. + +Regenerate with `python3 tools/bitmaps_doc.py`; the Appears column survives. + +## Calendar + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Calendar_Active_Cell` | 41x30 | indexed8 | 120 | yes | Calendar, days of the shown month | +| `Calendar_Alarm` | 18x18 | bgra8888 | - | yes | Calendar | +| `Calendar_Flag` | 11x12 | indexed8 | 19 | yes | Calendar | +| `Calendar_Hilite_Cell` | 41x30 | bgra8888 | - | yes | Calendar, the selected day | +| `Calendar_Inactive_Cell` | 41x30 | indexed8 | 40 | yes | Calendar, days of the neighbouring months | +| `Calendar_Small_Alarm` | 11x11 | bgra8888 | - | yes | Calendar | + +## CapacityView + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `CapacityView_Detailed_AudioCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_AudioLeft_Image` | 16x30 | indexed8 | 95 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_AudioRight_Image` | 16x30 | indexed8 | 104 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_Edge_Image` | 2x30 | indexed8 | 3 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_EmptyCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_EmptyLeft_Image` | 16x30 | indexed8 | 76 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_EmptyRight_Image` | 16x30 | indexed8 | 76 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_OtherCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_OtherLeft_Image` | 16x30 | indexed8 | 101 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_OtherRight_Image` | 16x30 | indexed8 | 97 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_PhotosCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_PhotosLeft_Image` | 16x30 | indexed8 | 92 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_PhotosRight_Image` | 16x30 | indexed8 | 107 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_VideoCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_VideoLeft_Image` | 16x30 | indexed8 | 92 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_VideoRight_Image` | 16x30 | indexed8 | 97 | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_EmptyCenter_Image` | 1x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_EmptyLeft_Image` | 9x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_EmptyRight_Image` | 9x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_FillCenter_Image` | 1x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_FillLeft_Image` | 7x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_FillRight_Image` | 7x13 | bgra8888 | - | yes | Settings > About, the capacity bars | + +## Caption + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Caption_LeftEndcapBottom_Image` | 9x9 | mask4 | - | yes | Pane captions | +| `Caption_LeftEndcapTop_Image` | 9x9 | mask4 | - | yes | Pane captions | +| `Caption_RightEndcapBottom_Image` | 9x9 | mask4 | - | yes | Pane captions | +| `Caption_RightEndcapTop_Image` | 9x9 | mask4 | - | yes | Pane captions | + +## ChargingMode + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `ChargingMode_Image_Critical` | 205x163 | indexed16 | 5552 | yes | Charging screen | +| `ChargingMode_Image_Empty_CapLeft` | 38x142 | indexed16 | 1243 | yes | Charging screen | +| `ChargingMode_Image_Empty_CapRight` | 45x142 | indexed16 | 1497 | yes | Charging screen | +| `ChargingMode_Image_Empty_Middle` | 8x142 | indexed8 | 225 | yes | Charging screen | +| `ChargingMode_Image_Green_CapLeft` | 38x142 | indexed16 | 1380 | yes | Charging screen | +| `ChargingMode_Image_Green_CapRight` | 45x142 | indexed16 | 1619 | yes | Charging screen | +| `ChargingMode_Image_Green_Middle` | 8x142 | bgra8888 | - | yes | Charging screen | +| `ChargingMode_Image_Green_Middle_Cap` | 8x142 | bgra8888 | - | yes | Charging screen | +| `ChargingMode_Image_ToggleCharged` | 47x29 | mask4 | - | yes | Charging screen | +| `ChargingMode_Image_ToggleCharging` | 23x57 | mask4 | - | yes | Charging screen | + +## Clock + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Clock_CenterCap_Image` | 73x73 | indexed8 | 9 | yes | Clock faces | +| `Clock_Hours_Image_0` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_1` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_2` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_3` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_4` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_5` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_6` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_7` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_8` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_9` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_10` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_11` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_12` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_13` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_14` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_15` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_16` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_17` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_18` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_19` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_20` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_21` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_22` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_23` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_24` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_25` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_26` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_27` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_28` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_29` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Large_Image` | 132x145 | indexed16 | 1781 | yes | Clock faces | +| `Clock_Mins_Image_0` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_1` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_2` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_3` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_4` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_5` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_6` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_7` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_8` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_9` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_10` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_11` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_12` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_13` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_14` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_15` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_0` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_1` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_2` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_3` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_4` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_5` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_6` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_7` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_8` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_9` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_10` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_11` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_12` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_13` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_14` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_15` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Shadow_Image` | 8x26 | indexed8 | 27 | yes | Clock faces | +| `Clock_Small_Image` | 73x73 | indexed16 | 533 | yes | Clock faces | +| `Clock_Small_Night_Image` | 73x73 | indexed16 | 369 | yes | Clock faces | + +## DiskModeImage + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `DiskModeImage_ConnectedIcon` | 113x113 | indexed8 | 64 | yes | Disk Mode | +| `DiskModeImage_DisconnectIcon` | 112x112 | indexed8 | 95 | yes | Disk Mode | +| `DiskModeImage_Progress_Empty_Fill` | 1x12 | indexed8 | 4 | yes | Disk Mode | +| `DiskModeImage_Progress_Empty_LeftCap` | 8x12 | indexed8 | 38 | yes | Disk Mode | +| `DiskModeImage_Progress_Empty_RightCap` | 8x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_Progress_Full_Fill` | 1x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_Progress_Full_LeftCap` | 7x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_Progress_Full_RightCap` | 7x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow1` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow3` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow5` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow7` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow9` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow11` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow13` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow15` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow17` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow19` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow21` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow23` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow25` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow27` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow29` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow31` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow33` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow35` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncIcon` | 112x112 | indexed16 | 1708 | yes | Disk Mode | + +## Genius + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Genius_Slider_Endcap_Image` | 6x34 | bgra8888 | - | yes | Genius | +| `Genius_Slider_Fill_Image` | 1x34 | bgra8888 | - | yes | Genius | +| `Genius_Slider_Icon_Image` | 18x21 | indexed8 | 137 | yes | Genius | +| `Genius_Slider_Image` | 75x34 | indexed8 | 118 | yes | Genius | + +## Media + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Media_AlbumsProxy_Image` | 55x55 | indexed8 | 202 | yes | Music lists, the proxy icons | +| `Media_AllAlbumsProxy_Image` | 55x55 | indexed16 | 576 | yes | Music lists, the proxy icons | +| `Media_ArtistsProxy_Image` | 55x55 | indexed8 | 203 | yes | Music lists, the proxy icons | +| `Media_AudioBooksProxy_Image` | 55x55 | indexed8 | 230 | yes | Music lists, the proxy icons | +| `Media_AudioProxy_Image` | 55x55 | indexed8 | 240 | yes | Music lists, the proxy icons | +| `Media_DocumentsProxy_Image` | 55x55 | indexed16 | 295 | yes | Music lists, the proxy icons | +| `Media_Genius_Large_Image` | 114x114 | indexed16 | 4069 | yes | Music lists, the proxy icons | +| `Media_Genius_Normal_Image` | 18x18 | bgra8888 | - | yes | Music lists, the proxy icons | +| `Media_Genius_Refresh_Hi_Image` | 15x18 | indexed8 | 90 | yes | Music lists, the proxy icons | +| `Media_Genius_Refresh_Image` | 15x18 | indexed8 | 90 | yes | Music lists, the proxy icons | +| `Media_Genius_Selected_Image` | 18x18 | bgra8888 | - | yes | Music lists, the proxy icons | +| `Media_MusicVideosProxy_Image` | 55x55 | indexed8 | 234 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_Black_Image` | 24x14 | indexed8 | 65 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_Playlist_Black_Image` | 17x14 | indexed8 | 65 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_Playlist_White_Image` | 17x16 | indexed8 | 64 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_White_Image` | 24x16 | indexed8 | 64 | yes | Music lists, the proxy icons | +| `Media_OTGPlaylist_Image` | 46x57 | indexed8 | 103 | yes | Music lists, the proxy icons | +| `Media_PhotosProxy_Image` | 55x55 | indexed16 | 309 | yes | Music lists, the proxy icons | +| `Media_PlaylistsProxy_Image` | 55x55 | indexed8 | 197 | yes | Music lists, the proxy icons | +| `Media_PodcastsProxy_Image` | 55x55 | indexed8 | 231 | yes | Music lists, the proxy icons | +| `Media_SearchProxy_Image` | 55x55 | indexed8 | 185 | yes | Music lists, the proxy icons | +| `Media_TVShowsProxy_Image` | 55x55 | indexed8 | 169 | yes | Music lists, the proxy icons | +| `Media_VideoStatusIcon_Image` | 23x29 | indexed8 | 4 | yes | Music lists, the proxy icons | +| `Media_VideoStatusIcon_White_Image` | 23x29 | indexed8 | 3 | yes | Music lists, the proxy icons | +| `Media_VideosProxy_Image` | 55x55 | indexed8 | 186 | yes | Music lists, the proxy icons | + +## No_Content + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `No_Content_Albums_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_AudioBooks_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_Audiobooks_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Contacts_Preview_Image` | 200x145 | mask4 | - | yes | Empty lists | +| `No_Content_Movies_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_MusicVideos_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_Music_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Music_Video_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Notes_Preview_Image` | 161x145 | mask4 | - | yes | Empty lists | +| `No_Content_Photo_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Playlist_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Podcast_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Podcasts_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_TVShow_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_TVShows_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_Videos_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_iTunesU_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_iTunesU_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | + +## NowPlaying + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `NowPlaying_Black_FF_Image` | 14x16 | indexed8 | 12 | yes | Now Playing | +| `NowPlaying_Black_Pause_Image` | 14x16 | indexed8 | 3 | yes | Now Playing | +| `NowPlaying_Black_Play_Image` | 14x16 | indexed8 | 18 | yes | Now Playing | +| `NowPlaying_Black_Record_Image` | 13x13 | indexed8 | 73 | yes | Now Playing | +| `NowPlaying_Black_Rew_Image` | 14x16 | indexed8 | 12 | yes | Now Playing | +| `NowPlaying_Black_Volume_Locked_Image` | 19x17 | indexed8 | 10 | yes | Now Playing | +| `NowPlaying_Blue_Dot_Image` | 16x17 | indexed8 | 14 | yes | Now Playing | +| `NowPlaying_Blue_Star_Image` | 16x17 | indexed8 | 92 | yes | Now Playing | +| `NowPlaying_Chaptermark_Image` | 1x14 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Classic_Repeat_Image` | 19x15 | indexed8 | 25 | yes | Now Playing | +| `NowPlaying_Classic_Repeat_Once_Image` | 19x15 | indexed8 | 59 | yes | Now Playing | +| `NowPlaying_Classic_Shuffle_Image` | 18x14 | indexed8 | 68 | yes | Now Playing | +| `NowPlaying_Dot_Image` | 22x26 | indexed8 | 15 | yes | Now Playing | +| `NowPlaying_Genius_Icon` | 28x28 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Idle_Battery_0_Image` | 72x40 | indexed8 | 4 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_1_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_2_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_3_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_4_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_5_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_6_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_7_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Colon_Image` | 15x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_0_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_1_Image` | 27x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_2_Image` | 39x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_3_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_4_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_5_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_6_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_7_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_8_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_9_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Lock_Image` | 25x38 | indexed8 | 6 | yes | Now Playing | +| `NowPlaying_Idle_Play_Image` | 41x43 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Radio_Image` | 67x40 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Large_Blue_Star_Image` | 22x26 | indexed8 | 226 | yes | Now Playing | +| `NowPlaying_Large_Shuffle_Image` | 25x19 | indexed8 | 91 | yes | Now Playing | +| `NowPlaying_Overlay_Image` | 8x37 | indexed8 | 38 | yes | Now Playing | +| `NowPlaying_Paused_Image` | 72x71 | indexed16 | 914 | yes | Now Playing | +| `NowPlaying_ProgressBar_Active_Background_Image` | 8x28 | indexed8 | 36 | yes | Now Playing | +| `NowPlaying_ProgressBar_Active_Fill_Image` | 8x28 | indexed8 | 29 | yes | Now Playing | +| `NowPlaying_ProgressBar_Active_Fill_Orange_Image` | 8x28 | indexed8 | 34 | yes | Now Playing | +| `NowPlaying_ProgressBar_Growth_Image` | 5x7 | indexed8 | 9 | yes | Now Playing | +| `NowPlaying_ProgressBar_Inactive_Background_Image` | 8x24 | indexed8 | 33 | yes | Now Playing | +| `NowPlaying_ProgressBar_Inactive_Fill_Image` | 8x24 | indexed8 | 37 | yes | Now Playing | +| `NowPlaying_ProgressBar_LeftEndcap_Image` | 12x7 | indexed8 | 35 | yes | Now Playing | +| `NowPlaying_ProgressBar_RightEndcap_Image` | 12x7 | indexed8 | 35 | yes | Now Playing | +| `NowPlaying_ProgressBar_Scrub_Image` | 13x28 | indexed8 | 129 | yes | Now Playing | +| `NowPlaying_ProgressFill_Growth_Image` | 2x7 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_ProgressFill_LeftEndcap_Image` | 3x7 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_ProgressFill_RightEndcap_Image` | 4x7 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Rental_Warning_Overlay_Fill` | 1x104 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Rental_Warning_Overlay_Left` | 9x104 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Rental_Warning_Overlay_Right` | 9x104 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Repeat_Image` | 20x14 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_Repeat_Once_Image` | 24x16 | indexed8 | 93 | yes | Now Playing | +| `NowPlaying_Scrub_Image` | 14x9 | indexed8 | 25 | yes | Now Playing | +| `NowPlaying_Shuffle_Image` | 18x16 | indexed8 | 68 | yes | Now Playing | +| `NowPlaying_Small_Grey_Star_Image` | 13x13 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_Small_White_Star_Image` | 13x13 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_Star_Image` | 13x13 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_StatusBar_Image` | 320x24 | indexed8 | 41 | yes | Stopwatch and Charging header | +| `NowPlaying_White_FF_Image` | 15x16 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_White_Pause_Image` | 14x16 | indexed8 | 72 | yes | Now Playing | +| `NowPlaying_White_Play_Image` | 14x16 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_White_Rew_Image` | 15x16 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_White_Volume_High_Image` | 19x17 | indexed8 | 51 | yes | Now Playing | +| `NowPlaying_White_Volume_Locked_Image` | 19x17 | indexed8 | 11 | yes | Now Playing | +| `NowPlaying_White_Volume_Low_Image` | 9x17 | indexed8 | 25 | yes | Now Playing | + +## OptionBar + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `OptionBar_Black_Thumb_Center_Image` | 1x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Thumb_LeftCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Thumb_RightCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Well_Center_Image` | 1x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Well_LeftCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Well_RightCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Thumb_Center_Image` | 1x27 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Thumb_LeftCap_Image` | 8x27 | indexed8 | 48 | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Thumb_RightCap_Image` | 8x27 | indexed8 | 48 | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Well_Center_Image` | 1x27 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Well_LeftCap_Image` | 8x27 | indexed8 | 70 | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Well_RightCap_Image` | 8x27 | indexed8 | 70 | yes | Search letter strip and option bars | +| `OptionBar_White_Thumb_Center_Image` | 1x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Thumb_LeftCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Thumb_RightCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Well_Center_Image` | 1x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Well_LeftCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Well_RightCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | + +## Playlist + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Playlist_Folder_Icon` | 23x24 | bgra8888 | - | yes | Playlists | +| `Playlist_Genius_Icon` | 23x25 | bgra8888 | - | yes | Playlists | +| `Playlist_Genius_Icon_Hi` | 23x25 | bgra8888 | - | yes | Playlists | +| `Playlist_Regular_Icon` | 23x24 | bgra8888 | - | yes | Playlists | +| `Playlist_Saved_Genius_Icon` | 23x24 | bgra8888 | - | yes | Playlists | +| `Playlist_Smart_Icon` | 23x24 | bgra8888 | - | yes | Playlists | + +## Podcasts + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Podcasts_new_item_Image` | 13x29 | indexed8 | 46 | yes | Podcasts | +| `Podcasts_new_item_video_Image` | 13x29 | indexed8 | 47 | yes | Podcasts | +| `Podcasts_new_item_video_white_Image` | 13x29 | indexed8 | 32 | yes | Podcasts | +| `Podcasts_new_item_white_Image` | 13x29 | indexed8 | 31 | yes | Podcasts | +| `Podcasts_spacer_Image` | 13x29 | indexed8 | 1 | yes | Podcasts | +| `Podcasts_video_solo_Image` | 13x29 | indexed8 | 4 | yes | Podcasts | +| `Podcasts_video_white_solo_Image` | 13x29 | indexed8 | 3 | yes | Podcasts | + +## Radio + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Radio_Bottom_Background_Image` | 8x36 | indexed8 | 118 | yes | Radio | +| `Radio_Bottom_Bar_Image` | 320x5 | indexed8 | 150 | yes | Radio | +| `Radio_Current_Image` | 2x36 | bgra8888 | - | yes | Radio | +| `Radio_Digit_0_Image` | 42x98 | indexed8 | 90 | yes | Radio | +| `Radio_Digit_1_Image` | 32x98 | indexed8 | 70 | yes | Radio | +| `Radio_Digit_2_Image` | 39x98 | indexed8 | 83 | yes | Radio | +| `Radio_Digit_3_Image` | 39x98 | indexed8 | 93 | yes | Radio | +| `Radio_Digit_4_Image` | 39x98 | indexed8 | 79 | yes | Radio | +| `Radio_Digit_5_Image` | 39x98 | indexed8 | 92 | yes | Radio | +| `Radio_Digit_6_Image` | 39x98 | indexed8 | 93 | yes | Radio | +| `Radio_Digit_7_Image` | 39x98 | indexed8 | 79 | yes | Radio | +| `Radio_Digit_8_Image` | 39x98 | indexed8 | 90 | yes | Radio | +| `Radio_Digit_9_Image` | 39x98 | indexed8 | 88 | yes | Radio | +| `Radio_Digit_Period_Image` | 18x98 | indexed8 | 44 | yes | Radio | +| `Radio_Icon_Image` | 146x110 | indexed16 | 4401 | yes | Radio | +| `Radio_MHz_Image` | 63x44 | indexed8 | 84 | yes | Radio | +| `Radio_Preset_Image` | 11x11 | indexed8 | 19 | yes | Radio | +| `Radio_Scanning_1_Image` | 19x15 | indexed8 | 6 | yes | Radio | +| `Radio_Scanning_2_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_3_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_4_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_5_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_6_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_7_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Signal_Indicator_Dark_Image` | 20x16 | indexed8 | 35 | yes | Radio | +| `Radio_Signal_Indicator_Light_Image` | 20x16 | indexed8 | 101 | yes | Radio | +| `Radio_Ticks_Image` | 320x36 | mask4 | - | yes | Radio | +| `Radio_Ticks_Japan_Image` | 320x36 | mask4 | - | yes | Radio | + +## Settings + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Settings_About_Band_Image` | 320x39 | indexed16 | 512 | yes | Settings pane previews | +| `Settings_About_Bubble_Deselected_Image` | 6x6 | indexed8 | 4 | yes | Settings pane previews | +| `Settings_About_Bubble_Selected_Image` | 6x6 | indexed8 | 4 | yes | Settings pane previews | +| `Settings_About_Capacity_AudioLegend_Image` | 12x12 | indexed8 | 36 | yes | Settings pane previews | +| `Settings_About_Capacity_Fill_Image` | 1x30 | bgra8888 | - | yes | Settings pane previews | +| `Settings_About_Capacity_LeftCap_Image` | 16x30 | indexed8 | 76 | yes | Settings pane previews | +| `Settings_About_Capacity_OtherLegend_Image` | 12x12 | indexed8 | 34 | yes | Settings pane previews | +| `Settings_About_Capacity_PhotosLegend_Image` | 12x12 | indexed8 | 26 | yes | Settings pane previews | +| `Settings_About_Capacity_RightCap_Image` | 16x30 | indexed8 | 76 | yes | Settings pane previews | +| `Settings_About_Capacity_VideoLegend_Image` | 12x12 | indexed8 | 34 | yes | Settings pane previews | +| `Settings_About_Logo_Image` | 64x72 | indexed16 | 906 | yes | Settings pane previews | +| `Settings_Accessory_TitleBand_Image` | 296x20 | indexed8 | 5 | yes | Settings pane previews | +| `Settings_AppleLogoPreview_Image` | 77x80 | mask8 | - | yes | Settings pane previews | +| `Settings_AppleLogo_Image` | 119x119 | mask8 | - | yes | Settings pane previews | +| `Settings_Audiobooks_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_Backlight_2s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_5s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_10s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_20s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_30s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_Image` | 78x122 | mask4 | - | yes | Settings > Backlight | +| `Settings_Backlight_off_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_on_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_BasePanelWide_Image` | 130x105 | indexed16 | 409 | yes | Settings pane previews | +| `Settings_BasePanel_Image` | 78x121 | indexed16 | 546 | yes | Settings pane previews | +| `Settings_Brightness_Image` | 78x121 | mask8 | - | yes | Settings > Brightness | +| `Settings_ClickerOff_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_ClickerOn_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_DateTime_Calendar_Image` | 130x128 | indexed16 | 298 | yes | Settings pane previews | +| `Settings_DateTime_Capsule_Hilite` | 40x37 | indexed8 | 141 | yes | Settings pane previews | +| `Settings_DateTime_Capsule_Image` | 167x57 | indexed16 | 540 | yes | Settings pane previews | +| `Settings_DateTime_TimeZonePin_Image` | 19x24 | indexed8 | 171 | yes | Settings pane previews | +| `Settings_EQ_Acoustic_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_BassBooster_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_BassReducer_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Classical_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Dance_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Deep_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Electronic_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Flat_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_HipHop_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Jazz_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Latin_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Loudness_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Lounge_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Piano_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Pop_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_RandB_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Rock_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_SmallSpeakers_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_SpokenWord_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_TrebleBooster_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_TrebleReducer_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_VocalBooster_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_Language_Image` | 159x240 | indexed8 | 30 | yes | Settings pane previews | +| `Settings_Legal_Image` | 20x25 | indexed8 | 17 | yes | Settings pane previews | +| `Settings_MainMenu_CheckmarkBlack_Image` | 14x12 | indexed8 | 4 | yes | Settings pane previews | +| `Settings_MainMenu_CheckmarkWhite_Image` | 14x12 | indexed8 | 22 | yes | Settings pane previews | +| `Settings_MainMenu_Image` | 78x121 | mask4 | - | yes | Settings pane previews | +| `Settings_Radio_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_RepeatAll_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_RepeatOff_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_RepeatOne_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_Reset_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_ShuffleOff_Image` | 78x121 | mask4 | - | yes | Settings pane previews | +| `Settings_ShuffleSongs_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_SortBy_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_SoundCheckOff_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_SoundCheckOn_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_VolumeLimitArrow_Image` | 9x5 | indexed8 | 6 | yes | Settings pane previews | +| `Settings_VolumeLimit_Image` | 78x121 | mask8 | - | yes | Settings pane previews | + +## StatusBarBlack + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `StatusBarBlack_Background_Image` | 320x24 | indexed8 | 79 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_0` | 26x13 | indexed8 | 27 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_1` | 26x13 | indexed8 | 27 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_2` | 26x13 | indexed8 | 27 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_3` | 26x13 | indexed8 | 5 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_4` | 26x13 | indexed8 | 6 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_5` | 26x13 | indexed8 | 5 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_6` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_7` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_8` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_9` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_10` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_11` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_12` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_13` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_14` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_15` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_16` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_17` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_18` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_19` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_20` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_21` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_22` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_Charge` | 26x13 | indexed8 | 41 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_Plug` | 26x13 | indexed8 | 34 | yes | Status bar on dark screens | +| `StatusBarBlack_Lock_Image` | 11x16 | indexed8 | 14 | yes | Status bar on dark screens | + +## StatusBarWhite + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `StatusBarWhite_Background_Image` | 320x20 | indexed8 | 20 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_0` | 26x13 | indexed8 | 62 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_1` | 26x13 | indexed8 | 84 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_2` | 26x13 | indexed8 | 85 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_3` | 26x13 | indexed8 | 87 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_4` | 26x13 | indexed8 | 88 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_5` | 26x13 | indexed8 | 91 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_6` | 26x13 | indexed8 | 90 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_7` | 26x13 | indexed8 | 92 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_8` | 26x13 | indexed8 | 89 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_9` | 26x13 | indexed8 | 92 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_10` | 26x13 | indexed8 | 95 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_11` | 26x13 | indexed8 | 89 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_12` | 26x13 | indexed8 | 93 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_13` | 26x13 | indexed8 | 91 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_14` | 26x13 | indexed8 | 90 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_15` | 26x13 | indexed8 | 88 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_16` | 26x13 | indexed8 | 89 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_17` | 26x13 | indexed8 | 90 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_18` | 26x13 | indexed8 | 85 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_19` | 26x13 | indexed8 | 87 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_20` | 26x13 | indexed8 | 88 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_21` | 26x13 | indexed8 | 78 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_22` | 26x13 | indexed8 | 68 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_Charge` | 26x13 | indexed8 | 55 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_Plug` | 26x13 | indexed8 | 45 | yes | Status bar on light screens | +| `StatusBarWhite_Lock_Image` | 13x16 | indexed8 | 41 | yes | Status bar on light screens | +| `StatusBarWhite_PlayStatus_Image` | 14x16 | bgra8888 | - | yes | Status bar on light screens | + +## Stopwatch + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Stopwatch_Caps_Image` | 123x123 | indexed8 | 42 | yes | Stopwatch | +| `Stopwatch_Clock_Image` | 145x181 | indexed16 | 2895 | yes | Stopwatch | +| `Stopwatch_Mins_Image_0` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_1` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_2` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_3` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_4` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_5` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_6` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_7` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_8` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_9` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_10` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_11` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_12` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_13` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_14` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_15` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_16` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_17` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_18` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_19` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_20` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_21` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_22` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_23` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_24` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_25` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_26` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_27` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_28` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_29` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_PlayPause_Image` | 104x76 | indexed16 | 897 | yes | Stopwatch | +| `Stopwatch_Secs_Image_0` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_1` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_2` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_3` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_4` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_5` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_6` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_7` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_8` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_9` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_10` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_11` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_12` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_13` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_14` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_15` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_16` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_17` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_18` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_19` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_20` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_21` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_22` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_23` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_24` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_25` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_26` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_27` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_28` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_29` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_SmallPause_Image` | 23x17 | indexed8 | 5 | yes | Stopwatch | +| `Stopwatch_SmallPlay_Image` | 23x17 | indexed8 | 22 | yes | Stopwatch | + +## System + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `System_ActiveButtonFill_Image` | 1x22 | bgra8888 | - | yes | | +| `System_ActiveButtonLeftCap_Image` | 5x22 | bgra8888 | - | yes | | +| `System_ActiveButtonRightCap_Image` | 5x22 | bgra8888 | - | yes | | +| `System_Input_Field_Left_Image` | 10x26 | indexed8 | 49 | yes | | +| `System_Input_Field_Middle_Image` | 10x26 | indexed8 | 14 | yes | Search, the text typed into the box | +| `System_Input_Field_Right_Image` | 10x26 | indexed8 | 52 | yes | | +| `System_NormalButtonFill_Image` | 1x26 | bgra8888 | - | yes | | +| `System_NormalButtonLeftCap_Image` | 6x26 | bgra8888 | - | yes | | +| `System_NormalButtonRightCap_Image` | 6x26 | bgra8888 | - | yes | | +| `System_Overlay_BrightnessLess_Image` | 12x13 | indexed8 | 20 | yes | | +| `System_Overlay_BrightnessMore_Image` | 17x17 | indexed8 | 14 | yes | | +| `System_Overlay_Left_Image` | 8x80 | indexed8 | 188 | yes | | +| `System_Overlay_Middle_Image` | 9x80 | indexed8 | 41 | yes | | +| `System_Overlay_Right_Image` | 8x80 | indexed8 | 188 | yes | | +| `System_Overlay_VolumeLeft_Image` | 15x13 | indexed8 | 32 | yes | | +| `System_Overlay_VolumeRight_Image` | 19x17 | indexed8 | 63 | yes | | +| `System_QuickScroll_123_Image` | 74x70 | mask4 | - | yes | | +| `System_QuickScroll_Image` | 74x70 | indexed8 | 168 | yes | | +| `System_ScrollbarBottom_Image` | 6x9 | indexed8 | 7 | yes | | +| `System_ScrollbarCenter_Image` | 6x8 | indexed8 | 2 | yes | | +| `System_ScrollbarTop_Image` | 6x10 | indexed8 | 7 | yes | | +| `System_Submenu_Image` | 10x15 | indexed8 | 34 | yes | | + +## TVOut + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `TVOut_30_Pin_Connector_Image` | 86x98 | indexed16 | 295 | yes | TV Out | +| `TVOut_Background_LeftCap_Image` | 24x48 | indexed8 | 181 | yes | TV Out | +| `TVOut_Background_Middle_Image` | 1x48 | indexed8 | 10 | yes | TV Out | +| `TVOut_Background_RightCap_Image` | 24x48 | indexed8 | 176 | yes | TV Out | +| `TVOut_Charge_Image_Clear_Middle` | 4x50 | indexed8 | 12 | yes | TV Out | +| `TVOut_Charge_Image_Left` | 20x50 | indexed8 | 132 | yes | TV Out | +| `TVOut_Charge_Image_Right` | 20x50 | indexed8 | 135 | yes | TV Out | +| `TVOut_Charge_Image_Set_Middle` | 4x50 | indexed8 | 12 | yes | TV Out | +| `TVOut_Duration_Center_Image` | 1x22 | indexed8 | 3 | yes | TV Out | +| `TVOut_Duration_RightCap_Image` | 10x22 | indexed8 | 52 | yes | TV Out | +| `TVOut_Duration_Scrub_Image` | 20x22 | indexed8 | 9 | yes | TV Out | +| `TVOut_Duration_White_Center_Image` | 1x22 | indexed8 | 4 | yes | TV Out | +| `TVOut_Duration_White_LeftCap_Image` | 10x22 | indexed8 | 67 | yes | TV Out | +| `TVOut_Duration_White_RightCap_Image` | 10x22 | indexed8 | 16 | yes | TV Out | +| `TVOut_FF_Image` | 70x50 | indexed16 | 363 | yes | TV Out | +| `TVOut_Pause_Image` | 70x50 | indexed16 | 303 | yes | TV Out | +| `TVOut_Rew_Image` | 70x50 | indexed16 | 373 | yes | TV Out | +| `TVOut_Volume_Full_Image` | 40x39 | indexed8 | 129 | yes | TV Out | +| `TVOut_Volume_Off_Image` | 42x39 | indexed8 | 70 | yes | TV Out | + +## VoiceMemosImage + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `VoiceMemosImage_Colon` | 7x33 | indexed8 | 28 | yes | Voice Memos | +| `VoiceMemosImage_Meter` | 127x167 | indexed16 | 4454 | yes | Voice Memos | +| `VoiceMemosImage_Microphone` | 110x190 | indexed16 | 2852 | yes | Voice Memos | +| `VoiceMemosImage_Pause` | 86x145 | indexed16 | 796 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_0` | 20x50 | indexed8 | 73 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_1` | 20x50 | indexed8 | 56 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_2` | 20x50 | indexed8 | 66 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_3` | 20x50 | indexed8 | 77 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_4` | 20x50 | indexed8 | 62 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_5` | 20x50 | indexed8 | 70 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_6` | 20x50 | indexed8 | 72 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_7` | 20x50 | indexed8 | 61 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_8` | 20x50 | indexed8 | 74 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_9` | 20x50 | indexed8 | 73 | yes | Voice Memos | + +## Other + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `AddressViewer_NoContactPict_Image` | 55x55 | indexed8 | 216 | yes | Contacts | +| `AddressViewer_NoGroupPict_Image` | 55x55 | indexed16 | 274 | yes | Contacts | +| `AddressViewer_Preview_Image` | 130x146 | indexed16 | 4177 | yes | Contacts | +| `Alarms_Clock_Static_Image` | 127x135 | indexed16 | 5199 | yes | Clock > Alarms | +| `Alarms_Timer_Time_Panel` | 163x53 | indexed16 | 485 | yes | Clock > Alarms | +| `Alarms_Timer_Time_Panel_Focus` | 40x37 | indexed8 | 141 | yes | Clock > Alarms | +| `Background_LightBlue_Image` | 320x240 | indexed16 | 1530 | yes | Background behind the Settings previews | +| `BigDaisyPetal0` | 3x12 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal1` | 9x13 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal2` | 12x9 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal3` | 12x3 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal4` | 12x9 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal5` | 9x13 | mask4 | - | yes | Activity spinner | +| `CoverFlow_Backside_Top_Image` | 8x43 | indexed8 | 69 | yes | Cover Flow, the track list behind a cover | +| `CoverFlow_Proxy_Image` | 128x128 | rgb565 | - | no | Cover Flow | +| `CoverFlow_Proxy_Image_iTunesU` | 128x128 | rgb565 | - | no | Cover Flow | +| `DateTimePicker_Bar` | 167x57 | indexed16 | 361 | yes | Date and time picker | +| `DateTimePicker_Selection` | 40x37 | indexed8 | 141 | yes | Date and time picker, the selected value | +| `DateTimePicker_Well` | 40x41 | indexed8 | 211 | yes | Date and time picker, the values | +| `DemoMode_Icon` | 97x97 | indexed16 | 869 | yes | | +| `Extras_Games_Preview_Image` | 142x87 | indexed16 | 5662 | yes | | +| `Games_Proxy_Image` | 55x55 | indexed16 | 519 | yes | | +| `GeniusMixes_Background_Image` | 8x240 | indexed8 | 47 | yes | Genius | +| `LockScreen_Padlock_Image` | 116x165 | indexed16 | 3250 | yes | Screen Lock | +| `LockScreen_TumblerBgnd_Image` | 182x57 | indexed16 | 372 | yes | Screen Lock and Volume Limit, the combination digits | +| `LockScreen_TumblerFocus_Image` | 26x54 | indexed8 | 174 | yes | Screen Lock and Volume Limit, the focused digit | +| `Lozenge_Left_White_Image` | 15x58 | indexed8 | 182 | yes | Lozenges | +| `Lozenge_Middle_White_Image` | 16x58 | indexed8 | 97 | yes | Lozenges | +| `Lozenge_Right_White_Image` | 15x58 | indexed8 | 177 | yes | Lozenges | +| `MainMenu_Backlight_Image` | 119x119 | mask8 | - | yes | Main menu | +| `MainMenu_Shuffle_Image` | 119x119 | mask8 | - | yes | Main menu | +| `MainMenu_Sleep_Image` | 98x146 | mask8 | - | yes | Main menu | +| `Notes_Preview_Image` | 120x146 | indexed16 | 5841 | yes | | +| `Page_White_Active_Image` | 8x8 | indexed8 | 5 | yes | Page indicators | +| `Page_White_Inactive_Image` | 8x8 | indexed8 | 8 | yes | Page indicators | +| `Photos_Slideshow_Top_Strip` | 1x88 | indexed8 | 4 | yes | | +| `PreviewArea_Shadow_Image` | 26x240 | indexed8 | 40 | yes | | +| `RemoteUI_Icon_Apple` | 113x113 | indexed8 | 184 | yes | | +| `Speakers_Icon_Image` | 159x240 | indexed16 | 3155 | yes | | +| `WorldClock_Graybar_Image` | 5x80 | indexed8 | 67 | yes | Clock, world clocks | +| `WorldClock_Map_Image` | 320x240 | mask4 | - | yes | Clock, world clocks | diff --git a/themes/docs/catalog.md b/themes/docs/catalog.md new file mode 100644 index 0000000..77be994 --- /dev/null +++ b/themes/docs/catalog.md @@ -0,0 +1,87 @@ +# Catalog + +The compiler ships two catalogs: Apple's bitmaps in `rvt/data/osos-2.0.5.json` and the first-party extension bitmaps in `rvt/data/extensions.json`. + +## Apple's bitmaps + +`rvt/data/osos-2.0.5.json` lists every `BMap` bitmap of Apple's 2.0.5 firmware a theme can replace. Records and tint bytes refer to bitmaps by their index in this list. The fingerprint in the `.rvt` header makes the Appearance extension refuse a file built against a different list. + +### Fields + +| Field | Contents | +|---|---| +| `schema` | 1 | +| `firmware` | File name, version, byte count and SHA-256 of the decrypted `osos.bin` the offsets refer to | +| `runtime_base`, `runtime_file_offset` | How a file offset becomes an address, below | +| `fingerprint` | The fingerprint of `bitmaps`, below | +| `bitmaps` | The entries, in firmware order | + +Each entry: + +| Key | Contents | +|---|---| +| `id` | Resource id | +| `name` | Resource name, what `theme.toml` and the art files use | +| `offset` | File offset of the bitmap header in `osos.bin` | +| `address` | Where the bitmap lives at run time | +| `bytes` | Bitmap size including its header | +| `format`, `depth` | Native pixel format and bits per pixel: 4 and 8 are masks, 0x64 and 0x65 are paletted, 0x565 is RGB565, 0x1888 is BGRA8888 | +| `width`, `height`, `stride` | Pixel size and row bytes | +| `data_offset` | Where a theme record starts: after the header and, for paletted formats, the colour count | +| `pixels_offset` | Where the rows start, after any palette | +| `palette_colors` | Palette entries, 0 for formats without one | +| `crc32` | CRC-32 of the whole bitmap, for checking the firmware the theme is applied to | + +### Addresses + +Apple loads `osos.bin` at `0x08000000` with the file's first `0xb798` bytes stripped (`OSOS_RUNTIME_FILE_OFFSET` in the core), so + +``` +address = runtime_base + offset - runtime_file_offset +``` + +### Fingerprint + +The first 8 bytes of the SHA-256 of the entry list, serialised as JSON with sorted keys and no whitespace. `rvt.catalog.fingerprint` computes it. + +### Browsing + +`rvt catalog list` prints one line per bitmap, filtered by name prefix with `--group` or by format with `--format`. `rvt catalog show ` prints every field of one bitmap. [Bitmaps](bitmaps.md) is the same list as a page. + +### Provenance + +`rvt/data/osos-2.0.5.json` was produced once from the core repository's former `firmware/bitmaps.json`, the bitmap table its old theme compiler read out of the 2.0.5 resource index (core commit 41ac06e, before both were removed). RepriseOS supports only that firmware, so no regeneration is expected; a catalog for another image would need a walker over its resource index. The fingerprint ties every theme to this catalog, and the Appearance extension compiles the same file into its own table, so a changed catalog means recompiling every theme and the extension. + +## Extension asset catalog + +`rvt/data/extensions.json` lists every bitmap of the first-party extensions and the core, one JSON object per line, sorted by id then asset. The compiler uses it to check art sizes, tell Settings icons from pictures and name bitmaps in `rvt inspect`. A bitmap not in it compiles only as a 78 x 121 Settings icon, with a warning. `--extension assets.json` on `compile`, `check`, `inspect` and `catalog` adds another extension's bitmaps. Its author generates the file from the built package: + +```sh +python3 /assets.py manifest.toml build/.rvx > assets.json +``` + +A later record for the same id and asset replaces an earlier one. + +| Key | Contents | +|---|---| +| `id` | The extension's id; `reprise` is the reserved owner id of the core's own bitmaps | +| `asset` | The asset's name in the manifest | +| `menu` | `true` for a Settings icon (`menu = true` in the manifest): a 78 x 121 coverage mask | +| `format`, `depth` | The BMap format word and bits per pixel as the extension ships it: 8 Mask8, 0x64 Indexed8, 0x1888 BGRA8888 | +| `width`, `height`, `stride` | Pixel size and row bytes | +| `palette_colors` | Palette entries, 0 without one | +| `bytes` | The decoded BMap, header included | +| `preload` | `always`, `optional` or `never`: whether the core loads it with the extension's main module (`preload` in the manifest) | + +`rvt catalog list --extensions [--group ]` prints one line per bitmap, and `rvt catalog show /` prints every field and the two hashes. [Extension bitmaps](extension-bitmaps.md) is the same list as a page. + +### Regenerating + +`make` at the repository root writes `build/assets.json` with the core's and every built extension's bitmaps. Then, from the `themes/` directory: + +```sh +python3 tools/extensions_catalog.py # rvt/data/extensions.json, by id then asset +python3 tools/extension_bitmaps_doc.py # docs/extension-bitmaps.md +``` + +Regenerate when an extension adds, removes or resizes a bitmap asset. `tests/test_assets.py` checks that the committed catalog matches the build and the committed page matches the generator. diff --git a/themes/docs/extension-bitmaps.md b/themes/docs/extension-bitmaps.md new file mode 100644 index 0000000..554ea58 --- /dev/null +++ b/themes/docs/extension-bitmaps.md @@ -0,0 +1,28 @@ +# Extension bitmaps + +The first-party extension bitmaps a theme can replace with +`/extensions//.png`, or `/reprise/.png` +for the core's (id `reprise`). See [Authoring](authoring.md#extension-bitmaps). +Size is width x height in pixels, which the art must match. Menu marks a +Settings icon, a 78 x 121 coverage mask drawn in the icon tint. + +The catalog and how to regenerate it are in +[Catalog](catalog.md#extension-asset-catalog). + +Regenerate this page with `python3 tools/extension_bitmaps_doc.py`. + +| Id | Asset | Size | Format | Palette | Menu | +|---|---|---|---|---|---| +| `appearance` | `settings-accent` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-appearance` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-cover` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-covers` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-moon` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-theme` | 78x121 | mask8 | - | yes | +| `balance` | `settings-balance` | 78x121 | mask8 | - | yes | +| `crossfeed` | `settings-crossfeed` | 78x121 | mask8 | - | yes | +| `equalizer` | `settings-eq` | 78x121 | mask8 | - | yes | +| `homebrew` | `apps` | 142x87 | bgra8888 | - | no | +| `night-shift` | `settings-night-shift` | 78x121 | mask8 | - | yes | +| `playback-log` | `settings-playback-log` | 78x121 | mask8 | - | yes | +| `reprise` | `settings-info` | 78x121 | mask8 | - | yes | diff --git a/themes/docs/format.md b/themes/docs/format.md new file mode 100644 index 0000000..e724eb1 --- /dev/null +++ b/themes/docs/format.md @@ -0,0 +1,111 @@ +# File format + +A theme is one file, `/Reprise/Themes/.rvt`: a header, then optional light and dark appearance packs. [`rvt/data/rvt.h`](../rvt/data/rvt.h) is the contract. The Appearance extension vendors it byte for byte, and `rvt/rvtfile.py` parses every `RVT_*` value from it. Integers are little-endian. + +## Header + +The offsets are the `RVT_HEADER_*` defines. + +| Offset | Size | Field | +|---|---|---| +| 0 | 4 | `"RVT0"` | +| 4 | u16 | Version, `RVT_VERSION` (3); a reader accepts exactly this value | +| 6 | u16 | Header bytes, where the packs begin | +| 8 | 8 | Catalog fingerprint, see [Catalog](catalog.md) | +| 16 | u32 | Appearances present: `RVT_APPEARANCE_LIGHT`, `RVT_APPEARANCE_DARK` | +| 20 | u32 x 4 | Light offset and bytes, dark offset and bytes; 0 when absent | +| 36 | u32 | CRC-32 of the first `RVT_HEADER_BYTES` (128) bytes with this word as zero | +| 40 | 32 | Id, `[a-z0-9][a-z0-9_-]{0,30}`, NUL-padded; the file's stem | +| 72 | 48 | Name, UTF-8, NUL-padded | +| 120 | 8 | Zero, up to `RVT_HEADER_BYTES`; a reader does not check them | + +The light pack starts at the header bytes, and the dark pack follows it, 4-byte aligned. A pack's bytes include its header. A reader places the packs by the header bytes field, not the constant, and skips fields it does not know in a longer header. The CRC always covers the first 128 bytes only. + +## Pack + +The offsets are the `RVT_PACK_*` defines. + +| Offset | Size | Field | +|---|---|---| +| 0 | u32 | Body bytes, at least `RVT_STYLE_BYTES` | +| 4 | u32 | Record count | +| 8 | u32 | CRC-32 of the body | +| 12 | u32 | Extension bitmap count, at most `RVT_EXTENSION_BITMAPS_MAX` (64) | +| 16 | | Body: the style prefix, the records, then the extension bitmaps | + +A pack is at least `RVT_PACK_HEADER_BYTES` (16) plus `RVT_STYLE_BYTES` long. + +## Style prefix + +`RVT_STYLE_BYTES` (856), at the `RVT_STYLE_*` offsets. Every colour is R, G, B, A with A = 255. + +| Offset | Size | Field | +|---|---|---| +| 0 | 8 x 4 | Colour roles in `enum rvt_role` order: background, text, accent fill, accent text, on accent, selection, cover border, icon tint | +| 32 | u32 | Rendering flags: `RVT_FLAG_FLAT_SELECTION`, `RVT_FLAG_MENU_COVERS_OFF`, `RVT_FLAG_FLAT_NOW_PLAYING`, `RVT_FLAG_FLAT_ICONS` | +| 36 | 9 x 5 x 4 | One palette per accent in `enum rvt_accent` order, each in `enum rvt_accent_slot` order: accent fill, accent text, selection, on accent, icon tint; a slot replaces the role of its name while that accent is picked | +| 216 | `RVT_CATALOG_MAX` | One tint byte per catalog index: `RVT_TINT_NONE`, or `RVT_TINT_ROLE` plus an `rvt_role`, or-ed with `RVT_TINT_DARKNESS` when the coverage comes from darkness or with `RVT_TINT_SOLID` when every level from `RVT_SOLID_FLOOR` up is full, never both. A reader packs the roles two per byte, so `RVT_TINT_ROLE + RVT_ROLES` stays at most 16 | + +## Records + +Records follow in ascending catalog index, each index at most once: + +| Size | Field | +|---|---| +| u32 | Catalog index | +| u32 | Kind, `enum rvt_kind` | +| u32 | Payload bytes | +| bytes | Payload, zero-padded to 4 | + +| Kind | Payload | The iPod writes | +|---|---|---| +| `pixels` | The native bytes from `data_offset` to the end: palette and rows | them in place | +| `pixels_lz` | The same bytes as an lz stream; the payload bytes are the stream's size | them in place while decoding | +| `recolor` | u32 count, then count × (`from` RGBA, `to` RGBA), strictly ascending by `from` as a little-endian u32, no `from` equal to its `to`; count 1..`RVT_RECOLOR_MAX` | each palette entry, BGRA8888 pixel or RGB565 word equal to a `from` as its `to` | +| `alias` | u32 source catalog index | the source's bytes after its header when the layouts are equal, else its pixels re-encoded in this bitmap's format; after every other record of the pack | +| `invert` | none | RGB inverted, alpha kept | +| `relight` | `RVT_RELIGHT_WORDS` × i32, 8.8 fixed point, `enum rvt_relight` order | grays per [Relight](#relight) below, a palette of the distinct grays in ascending order with zeros after it, and the rows re-indexed | + +The pixel kinds replace the stock bytes. The other kinds are computed from them, so the iPod restores a bitmap from its firmware before deriving it. The compiler writes `pixels_lz` when the stream is smaller than the raw bytes. + +**lz stream.** The layout is the core's (`rvx-sdk/rvx.h`, summarised in `rvt.h`). Each group is a flag byte and up to 8 items, bit 0 first. A clear bit is a literal byte. A set bit is a two-byte match `LLLLDDDD DDDDDDDD` copying L + 3 bytes from D + 1 bytes back in the output; when L = 15, following bytes are added to the length while they are 255, plus the first that is not. Matches copy from the output itself. The stream has no length field: a decoder stops after the bitmap's bytes (catalog size minus `data_offset`), and the stream must end exactly at the record's end. A stream that ends early, overruns the output or copies from before its start makes the record invalid. The palette-index check and the pack CRC apply to the stored bytes. + +**Tint bytes.** On a paletted or BGRA8888 bitmap without a record, a tint byte tints the stock bitmap with the coverage its `RVT_TINT_DARKNESS` or `RVT_TINT_SOLID` bit names. With a pixel record, the coverage is the record's alpha. A tint byte on a derived bitmap is invalid. On a mask, a tint byte needs no record and keeps the stock levels unless it carries `RVT_TINT_SOLID`, which rewrites them (a 4-bit level counts as level x 17). RGB565 bitmaps take no tint. + +**Derived records.** `recolor` on RGB565 uses opaque, 5-6-5-exact colours. `invert` and `alias` are not for masks. `relight` needs a paletted bitmap of at most `RVT_SCRATCH_PIXELS` pixels with a palette of at least `icon_hi − bg_lo + 1` entries. A pack has at most `RVT_ALIASES_MAX` aliases, and an alias source is neither an alias nor tinted. An alias between equal layouts is a byte copy. Between differing layouts the iPod re-encodes the source's pixels, for bitmaps of at most `RVT_SCRATCH_PIXELS` pixels. If the source has more colours than a paletted target holds, the alias fails and the stock bitmap stays. + +## Relight + +Every word is 8.8 fixed point; `luma = (77 r + 150 g + 29 b) >> 8`. The iPod rejects the record unless `0 <= t_zero < t_full <= 255`, `0 <= bg_lo <= bg_hi <= icon_lo <= icon_hi <= 255`, `|bg_base|` and `|icon_base|` are at most 1024, `|bg_ref|`, `|icon_luma|` and `|icon_row|` at most 255, and `|bg_slope|` at most 16, in pixel units before scaling. + +For each row, the stock pixel in column 0 is the background `bg`. A pixel's offset `o` is its largest channel difference from `bg`, and `t = clamp((o - t_zero) / (t_full - t_zero), 0, 1)` is how much of it is icon. A pixel with `0 < t < 1` and no 8-neighbour at `t = 1` is a drop shadow and takes `t = 0`. Then: + +- `bg_dark = clamp(bg_base + (luma(bg) - bg_ref) * bg_slope, bg_lo, bg_hi)` +- `icon_dark = clamp(icon_base + icon_luma * luma(c) + icon_row * y, icon_lo, icon_hi)` +- the pixel is `bg_dark + (icon_dark - bg_dark) * t`, rounded, opaque. + +The palette becomes the distinct grays in ascending order with zeros after them, and the rows are re-indexed. `rvt.derive` is the reference; the iPod's division must match it byte for byte. + +`from_other` art ([Authoring](authoring.md#derived-art)) is computed by the compiler and stored as a pixel record. One pack never refers into the other. + +## Extension bitmaps + +The extension bitmaps ([Authoring](authoring.md#extension-bitmaps)) follow the last record, ascending by owner then asset, each pair once, at most `RVT_EXTENSION_BITMAPS_MAX` (64) per pack. Each has a `RVT_EXTENSION_BITMAP_BYTES` (24) header: + +| Size | Field | +|---|---| +| u32 | Owner: FNV-1a of the extension id; the core's own bitmaps are owned by the hash of `reprise`, the reserved owner id of the core in the theme format | +| u32 | Asset: FNV-1a of the asset name | +| u32 | Kind, `enum rvt_extension_kind`: `RVT_EXTENSION_BITMAP` (1) the bitmap raw, `RVT_EXTENSION_BITMAP_LZ` (2) the bitmap as one lz stream | +| u32 | Stored bytes: the payload's length | +| u32 | Decoded bytes: the bitmap's length | +| u32 | Tint: `RVT_TINT_NONE` (0), or `RVT_TINT_ROLE` plus an `rvt_role` without coverage bits for a picture the reader paints in that role | +| bytes | Payload, zero-padded to 4 | + +A bitmap is the whole BMap as the iPod decodes it: the `RVT_BMAP_HEADER_BYTES` (28) header (format, reserved, stride, depth, bounds top, left, bottom, right, payload bytes), then the palette and rows. The payload is the bitmap raw (stored equals decoded) or one lz stream that decodes to exactly the decoded bytes and is at most those plus one flag byte per 8. The lz stream is the same as in `pixels_lz`, and the compiler uses it when it is smaller. + +The decoded bytes are at most `RVT_EXTENSION_BITMAP_MAX_BYTES` (65,536) and equal the header plus its payload bytes. A reader checks the header as the core does and rejects the bitmap unless the bounds are in order and within 16 bits, the depth is at most 32, a row fits the stride, and an Indexed8 palette of at most 256 entries and the rows fit the payload. + +A Settings icon has the menu header: Mask8 (8), stride 80, depth 8, bounds 0, 0, 121, 78, 9,680 payload bytes. A tinted bitmap is an Indexed8 or BGRA8888 picture, never a Settings icon. Its palette entries or pixels carry the coverage in their alpha with a placeholder colour, which the reader replaces with the role's colour at each decode. + +The hashes are the core's FNV-1a of the extension id and asset name (`rvx-sdk/rvx.py`, `fnv1a`). The pack CRC covers the extension bitmaps with the records. diff --git a/themes/docs/toolchain.md b/themes/docs/toolchain.md new file mode 100644 index 0000000..093f627 --- /dev/null +++ b/themes/docs/toolchain.md @@ -0,0 +1,84 @@ +# The compiler + +`rvt` is a Python 3.11+ package without dependencies. Run it from the `themes/` directory as `python3 -m rvt`. Only `preview` and `recolor` need a firmware. + +## Commands + +| Command | Does | +|---|---| +| `rvt new [--name NAME]` | Writes `/theme.toml` with every role and option as a comment, and the empty `apple/`, `reprise/` and `extensions/` folders of `/light/` and `/dark/`; `reprise` is the reserved owner id of the core's own bitmaps in the theme format | +| `rvt check ` | Compiles without writing; prints what each derive rule matched, the warnings and a size table per appearance | +| `rvt compile [--out DIR]` | The same, then writes `//.rvt` and `report.json`; `--out` defaults to `dist` | +| `rvt inspect [--json]` | Validates an `.rvt` against the catalog and describes it; extension bitmaps are named from the extension asset catalog, by their hashes when it does not know them | +| `rvt catalog list [--group PREFIX] [--format FMT]` | One line per Apple bitmap: name, size, format, palette entries, tintable | +| `rvt catalog list --extensions [--group ID] [--format FMT]` | One line per extension bitmap: id, asset, size, format, palette entries, menu or bitmap | +| `rvt catalog show ` | Every catalog field of one Apple bitmap, by name or hex id | +| `rvt catalog show /` | Every catalog field of one extension bitmap, and its two hashes | +| `rvt preview --firmware FILE` | Renders every derived bitmap of a theme from a decrypted `osos.bin` or the booted `osos-cfw.bin` to `dist//derived/` | +| `rvt recolor --firmware FILE` | Turns `//apple/.png` into a `recolor` rule file when the PNG is a pure recolour of the stock bitmap | + +| Option | On | Does | +|---|---|---| +| `--strict` | `check`, `compile`, `preview` | Turns warnings into errors | +| `--catalog FILE` | all but `new` | Uses another Apple catalog | +| `--extension assets.json` | `check`, `compile`, `preview`, `inspect`, `catalog` | Adds an extension's bitmaps ([Catalog](catalog.md#extension-asset-catalog)); repeatable | +| `--allow-reserved` | `check`, `compile`, `preview` | Accepts the id `classic` | + +Warnings cover: + +- a PNG with more colours than its native palette (reduced to fit) +- a text and background pair the theme colours that falls below 4.5:1 +- a tint glob that matches nothing +- a Settings icon with nothing below its art box while `flat_icons` is off +- an extension bitmap not in the catalog (compiled as a Settings icon) + +`report.json` has the theme's id, name, author and version and, per appearance: + +| Key | Contents | +|---|---| +| `contrast` | Contrast of every text and background pair, for Theme Default and each accent | +| `accents_builtin` | Accents using the built-in colours | +| `records` | Record count per kind | +| `extension_bitmaps` | Extension bitmap count per kind | +| `extension_tinted` | Tinted extension bitmaps and their roles | +| `palette_reduced` | Palette reductions | + +It also has each appearance's size in bytes. The output is deterministic, with sorted keys. + +## Layout + +| Path | Contents | +|---|---| +| `rvt/rvtfile.py` | The `.rvt` header and packs; every constant parsed from `rvt/data/rvt.h` | +| `rvt/data/` | The vendored contracts: the format header, the two catalogs and the SDK's bitmap encoder | +| `rvt/data/rvt.h` | The file format; the Appearance extension compiles against this header | +| `rvt/data/osos-2.0.5.json` | The [catalog](catalog.md) of Apple's bitmaps | +| `rvt/data/extensions.json` | The [extension asset catalog](catalog.md#extension-asset-catalog): the bitmaps of the first-party extensions | +| `rvt/data/bitmap.py` | The SDK's bitmap encoder, a byte copy of the SDK's `bitmap.py` | +| `rvt/catalog.py` | Catalog loading, lookup, the fingerprint | +| `rvt/theme.py` | `theme.toml`: validation and the resolution of colours, accents, tints and rules | +| `rvt/bitmaps.py` | PNG reading, palette fitting, the native pixel formats | +| `rvt/style.py` | The colours, rendering, accent palettes and tint bytes of an appearance; the Classic colours and the built-in accents | +| `rvt/derive.py` | Derivation rules, record payloads and the reference arithmetic of the iPod's derivations | +| `rvt/lz.py` | The core's lz codec | +| `rvt/assets.py` | Extension bitmaps: the folders, encoding, the extension asset catalog, the hashes and the pack table | +| `rvt/errors.py` | `fail`, the one error every check raises | +| `rvt/compiler.py`, `rvt/inspector.py` | Folder to bytes, bytes to a checked description | +| `rvt/firmware.py` | Stock bitmaps from a local firmware for `preview` and `recolor` | +| `rvt/cli.py` | The commands | +| `tests/` | Host tests against a synthetic catalog; a few compare the encoder and lz copies with the SDK checkout `SDK` names, the accent table with the Appearance extension and the extension asset catalog with the build | +| `tools/bitmaps_doc.py` | Writes [Bitmaps](bitmaps.md) from the catalog | +| `tools/extensions_catalog.py` | Writes `rvt/data/extensions.json` from the build's `assets.json`, see [Catalog](catalog.md#extension-asset-catalog) | +| `tools/extension_bitmaps_doc.py` | Writes [Extension bitmaps](extension-bitmaps.md) from `rvt/data/extensions.json` | +| `themes/` | The first-party themes; `themes/classic/recolor.py` generates Classic's recolour rules (needs `--firmware`), `themes/classic/fit.py` snaps Classic's PNGs to their palettes | + +## Tests + +From the repository root, after `make` (the build writes `build/assets.json` and compiles Classic with `--strict`): + +```sh +SDK=../osos-lab/rvx-sdk python3 -m unittest discover -s themes/tests +ruff check . && ruff format --check themes tools tests +``` + +CI runs both on Python 3.12 with the pinned SDK checkout. diff --git a/themes/rvt/__init__.py b/themes/rvt/__init__.py new file mode 100644 index 0000000..9ee5f12 --- /dev/null +++ b/themes/rvt/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""RepriseOS theme compiler: theme.toml folders in, .rvt files out.""" diff --git a/themes/rvt/__main__.py b/themes/rvt/__main__.py new file mode 100644 index 0000000..aa16d39 --- /dev/null +++ b/themes/rvt/__main__.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-3.0-only +from rvt.cli import main + +main() diff --git a/themes/rvt/assets.py b/themes/rvt/assets.py new file mode 100644 index 0000000..c05d76a --- /dev/null +++ b/themes/rvt/assets.py @@ -0,0 +1,474 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Extension bitmaps: /extensions//.png and +/reprise/.png for the core's own. + +A theme replaces any bitmap asset of an extension, a Settings icon or a canvas +bitmap, with a whole BMap the iPod uses as it would the extension's own: the +28-byte header, then the palette and rows. The compiler encodes a PNG with the +SDK's own encoder, rvt/data/bitmap.py, vendored byte for byte from +rvx-sdk/bitmap.py: `encode_mask` for a pane icon (a 78 x 121 coverage +mask, Mask8, stride 80), `encode_bmap` for any other (Indexed8 with a palette +up to 256 colours, else BGRA8888, rows padded to 4 bytes). The pack stores the +header raw and the rows raw or as one lz stream, at most the rows plus one flag +byte per 8, keyed by the FNV-1a hashes of the extension id and the asset name, +as the core keys them. + +Which (id, asset) pairs exist and what size they are comes from the extension +asset catalog, rvt/data/extensions.json for the first-party extensions, plus +any `--extension assets.json` additions; docs/catalog.md. +""" + +import json +import re +import struct +from importlib.resources import files +from pathlib import Path + +from rvt import bitmaps, lz, rvtfile +from rvt.data import bitmap +from rvt.errors import fail + +HEADER = bitmap.HEADER +MASK8, INDEXED8, BGRA8888 = bitmap.MASK8, bitmap.INDEXED8, bitmap.BGRA8888 +MENU_WIDTH, MENU_HEIGHT = bitmap.ICON_SIZE +MENU_STRIDE = (MENU_WIDTH + 3) & ~3 +MENU_HEADER = HEADER.pack( + MASK8, 0, MENU_STRIDE, 8, 0, 0, MENU_HEIGHT, MENU_WIDTH, MENU_STRIDE * MENU_HEIGHT +) +FORMAT_NAMES = {MASK8: "mask8", INDEXED8: "indexed8", BGRA8888: "bgra8888"} +# The art box of a Settings icon; the rows below it hold the reflection. +ART_ROWS = 79 + +if HEADER.size != rvtfile.BMAP_HEADER_BYTES: + raise ValueError("rvt/data/rvt.h and rvt/data/bitmap.py disagree on the header") + +FOLDER = "extensions" +CORE_ID = "reprise" +# The core's own bitmaps, owned by the id reprise, have their own folder beside +# apple/ and extensions/. +CORE_FOLDER = CORE_ID +ID_PATTERN = re.compile(r"[a-z][a-z0-9_-]{0,31}") +ASSET_PATTERN = re.compile(r"[a-z0-9_-]{1,31}") +PNG_LIMIT = 16 * 1024 * 1024 +CATALOG = files("rvt") / "data" / "extensions.json" +RECORD_KEYS = ( + "id", + "asset", + "menu", + "format", + "width", + "height", + "stride", + "depth", + "palette_colors", + "bytes", + "preload", +) +PRELOAD = ("always", "optional", "never") + + +def owner_hash(identifier: str) -> int: + return rvtfile.fnv1a(identifier.encode()) + + +def asset_hash(asset: str) -> int: + return rvtfile.fnv1a(asset.encode()) + + +# The extension asset catalog + + +def check_record(record: dict, where: str) -> dict: + """A catalog record with exactly the known keys and plausible values.""" + if not isinstance(record, dict) or tuple(sorted(record)) != tuple( + sorted(RECORD_KEYS) + ): + fail(where, f"expected a record with the keys {', '.join(RECORD_KEYS)}") + if not isinstance(record["id"], str) or not ID_PATTERN.fullmatch(record["id"]): + fail(where, f"id must match {ID_PATTERN.pattern}") + if not isinstance(record["asset"], str) or not ASSET_PATTERN.fullmatch( + record["asset"] + ): + fail(where, f"asset must match {ASSET_PATTERN.pattern}") + if not isinstance(record["menu"], bool): + fail(where, "menu is true or false") + if record["preload"] not in PRELOAD: + fail(where, f"preload is one of {', '.join(PRELOAD)}") + for key in ( + "format", + "width", + "height", + "stride", + "depth", + "palette_colors", + "bytes", + ): + value = record[key] + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + fail(where, f"{key} is a non-negative integer") + if not record["width"] or not record["height"]: + fail(where, "width and height are at least 1") + if record["menu"] and (record["width"], record["height"]) != ( + MENU_WIDTH, + MENU_HEIGHT, + ): + fail(where, f"a menu bitmap is {MENU_WIDTH}x{MENU_HEIGHT}") + return record + + +def read_json(path: Path) -> list[dict]: + """The records of an assets.json, one JSON object per line.""" + records = [] + for number, line in enumerate(path.read_text().splitlines(), 1): + if not line.strip(): + continue + try: + record = json.loads(line) + except ValueError as error: + fail(f"{path}:{number}", str(error)) + records.append(check_record(record, f"{path}:{number}")) + return records + + +def load_catalog(extensions: list[Path] = ()) -> dict[tuple[str, str], dict]: + """(id, asset) -> record: the vendored first-party catalog, then every + `--extension assets.json` in order, a later record for a pair replacing an + earlier one.""" + records = {} + sources = [Path(str(CATALOG)), *(Path(p) for p in extensions)] + for number, path in enumerate(sources): + if number and path.suffix != ".json": + fail("--extension", f"{path}: expected an assets.json") + if number and not path.is_file(): + fail("--extension", f"{path} does not exist") + for record in read_json(path): + records[record["id"], record["asset"]] = record + return records + + +def known_names(records: dict[tuple[str, str], dict]) -> dict[tuple[int, int], str]: + """(owner hash, asset hash) -> "id/asset" for the catalog's records.""" + return { + (owner_hash(identifier), asset_hash(asset)): f"{identifier}/{asset}" + for identifier, asset in records + } + + +def label(asset: dict, names: dict[tuple[int, int], str]) -> str: + return names.get( + (asset["owner"], asset["asset"]), + f"{asset['owner']:#010x}/{asset['asset']:#010x}", + ) + + +# The theme folder + + +def find_sources(folder: Path, appearance: str) -> dict[tuple[str, str], Path]: + """(id, asset) -> PNG path: /extensions//.png and + the core's /reprise/.png.""" + root = Path(folder).resolve() + found = {} + + def add(owner: str, directory: Path, where: str) -> None: + for path in sorted(directory.iterdir()): + at = f"{where}/{path.name}" + if path.name.startswith("."): + continue + if path.suffix != ".png" or not ASSET_PATTERN.fullmatch(path.stem): + fail( + at, + f"expected .png with the asset matching {ASSET_PATTERN.pattern}", + ) + found[owner, path.stem] = source_file(path, root, at, PNG_LIMIT) + + core = root / appearance / CORE_FOLDER + if core.is_dir(): + add(CORE_ID, core, f"{appearance}/{CORE_FOLDER}") + directory = root / appearance / FOLDER + if not directory.is_dir(): + return found + for owner in sorted(directory.iterdir()): + where = f"{appearance}/{FOLDER}/{owner.name}" + if owner.name.startswith("."): + continue + if not owner.is_dir(): + fail( + where, + f"expected a folder named after an extension id ({ID_PATTERN.pattern})", + ) + if owner.name == CORE_ID: + fail( + where, + f"{CORE_ID} is the core's id; its bitmaps go in " + f"{appearance}/{CORE_FOLDER}/", + ) + if not ID_PATTERN.fullmatch(owner.name): + fail(where, f"expected an extension id matching {ID_PATTERN.pattern}") + add(owner.name, owner, where) + return found + + +def source_file(path: Path, root: Path, where: str, limit: int) -> Path: + """The resolved path of an art or rule file: a plain file inside the theme + folder of at most `limit` bytes.""" + try: + resolved = path.resolve(strict=True) + except OSError: + fail(where, "does not exist") + if not resolved.is_relative_to(root) or not resolved.is_file(): + fail(where, "must be a file inside the theme folder") + if resolved.stat().st_size > limit: + fail(where, f"exceeds {limit:,} bytes") + return resolved + + +def source_path(appearance: str, identifier: str, asset: str) -> str: + """Where the PNG of (id, asset) sits in the theme, for messages; without + an appearance, the path below it.""" + folder = CORE_FOLDER if identifier == CORE_ID else f"{FOLDER}/{identifier}" + return "/".join(part for part in (appearance, folder, f"{asset}.png") if part) + + +# Encoding + + +def encode( + path: Path, where: str, record: dict | None, tint: str | None = None +) -> bytes: + """The whole BMap of a PNG: the SDK's menu rule for a catalog record with + `menu`, else its picture rule at the record's size. Without a record a + 78 x 121 coverage PNG is a menu bitmap; anything else needs the catalog. + A picture tinted on the iPod is read as coverage and stored in the + placeholder colour `tint`, which the iPod rewrites with the role's.""" + try: + width, height, rgba = bitmaps.read_png(path.read_bytes()) + except ValueError as error: + fail(where, str(error)) + if record is None and (width, height) != (MENU_WIDTH, MENU_HEIGHT): + fail( + where, + f"{width}x{height} is not a menu bitmap and the asset is not in the " + "extension asset catalog; pass --extension assets.json of the extension", + ) + menu = record is None or record["menu"] + if not menu and (width, height) != (record["width"], record["height"]): + fail( + where, + f"expected {record['width']}x{record['height']}, got {width}x{height}", + ) + if tint is not None and menu: + fail(where, "a Settings icon is drawn in the icon tint already; no tint role") + try: + if tint is not None: + rgba = bitmaps.tinted_pixels(bitmaps.coverage(rgba), tint) + encoder = bitmap.encode_mask if menu else bitmap.encode_bmap + data = encoder(width, height, rgba) + except ValueError as error: + fail(where, str(error)) + if len(data) > rvtfile.EXTENSION_BITMAP_MAX_BYTES: + fail( + where, + f"{len(data):,} bytes exceed {rvtfile.EXTENSION_BITMAP_MAX_BYTES:,}", + ) + return data + + +def is_menu(bmap: bytes) -> bool: + """True when the header is the menu header the pane slot accepts.""" + return bmap[: HEADER.size] == MENU_HEADER + + +def has_reflection(bmap: bytes) -> bool: + """True when a menu bitmap's rows below the art box carry anything.""" + return any(bmap[HEADER.size + ART_ROWS * MENU_STRIDE :]) + + +def check_collisions(names: list[tuple[str, str]]) -> None: + """Two (id, asset) pairs of a theme whose hashes agree would stand for one + bitmap on the iPod.""" + seen: dict[tuple[int, int], tuple[str, str]] = {} + for identifier, asset in names: + key = (owner_hash(identifier), asset_hash(asset)) + other = seen.setdefault(key, (identifier, asset)) + if other != (identifier, asset): + fail( + source_path("", identifier, asset), + f"its hashes collide with {source_path('', *other)}; rename one", + ) + + +# The table in the pack + +KIND_NAMES = {value: name for name, value in rvtfile.EXTENSION_KINDS.items()} + + +def tint_byte(role: str) -> int: + """The tint word of a picture drawn in `role`: no coverage bits, the + coverage is the art's alpha.""" + return rvtfile.TINT_ROLE + rvtfile.ROLES.index(role) + + +def tint_role(word: int, where: str) -> str | None: + """The role a tint word names, None for RVT_TINT_NONE.""" + if word == rvtfile.TINT_NONE: + return None + if not rvtfile.TINT_ROLE <= word < rvtfile.TINT_ROLE + len(rvtfile.ROLES): + fail(where, f"unknown tint {word:#x}") + return rvtfile.ROLES[word - rvtfile.TINT_ROLE] + + +def tintable(bmap: bytes) -> bool: + """Whether the iPod can paint a bitmap in a role: an Indexed8 or BGRA8888 + picture, not a Settings icon, which the core draws in the icon tint.""" + fmt = HEADER.unpack_from(bmap)[0] + return fmt in (INDEXED8, BGRA8888) and not is_menu(bmap) + + +def encode_table( + bmaps: dict[tuple[str, str], bytes], + tints: dict[tuple[str, str], str] | None = None, +) -> tuple[bytes, int, dict[str, int]]: + """The extension bitmap table of (id, asset) -> whole BMap, ascending by + the hashes, each as one lz stream when that is smaller, with the tint byte + of the role `tints` gives it; its bytes, its count and the count per kind + name.""" + tints = tints or {} + if len(bmaps) > rvtfile.EXTENSION_BITMAPS_MAX: + fail( + FOLDER, + f"{len(bmaps)} extension bitmaps exceed {rvtfile.EXTENSION_BITMAPS_MAX}", + ) + table = bytearray() + counts: dict[str, int] = {} + ordered = sorted( + bmaps.items(), key=lambda item: (owner_hash(item[0][0]), asset_hash(item[0][1])) + ) + for (identifier, asset), bmap in ordered: + name, data = "bitmap", bmap + packed = lz.lz_encode(bmap) + if len(packed) < len(bmap): + name, data = "bitmap_lz", packed + counts[name] = counts.get(name, 0) + 1 + role = tints.get((identifier, asset)) + table += rvtfile.EXTENSION_BITMAP.pack( + owner_hash(identifier), + asset_hash(asset), + rvtfile.EXTENSION_KINDS[name], + len(data), + len(bmap), + rvtfile.TINT_NONE if role is None else tint_byte(role), + ) + table += data + table += bytes(-len(table) % 4) + return bytes(table), len(bmaps), counts + + +def header_sane(bmap: bytes) -> bool: + """core_bitmap_whole: bounds in order and within 16 bits, depth at most + 32, a row of pixels within the stride, the palette within the payload and + the rows within what is left.""" + fmt, _, stride, depth, top, left, bottom, right, payload = HEADER.unpack_from(bmap) + height, width = bottom - top, right - left + palette = 0 + if fmt == INDEXED8: + colors = ( + struct.unpack_from("= 4 else 0x10000 + ) + palette = 4 + 4 * colors if colors <= 256 else payload + 1 + return ( + bottom >= top + and right >= left + and height <= 0xFFFF + and width <= 0xFFFF + and depth <= 32 + and width * depth <= stride * 8 + and palette <= payload + and height * stride <= payload - palette + ) + + +def describe(bmap: bytes) -> dict: + """Size, format name and palette of a BMap, for inspection.""" + fmt, _, _, _, top, left, bottom, right, _ = HEADER.unpack_from(bmap) + palette = 0 + if fmt == INDEXED8: + palette = struct.unpack_from(" tuple[list[dict], int]: + """The `count` extension bitmaps starting at `at`, each checked: known + kind, ascending unique (owner, asset), a decoded size within the cap, a + payload of the whole BMap raw at that size or as an lz stream no longer + than it plus a flag byte per 8 that decodes to exactly it, a header that + describes exactly that many bytes, zero padding. Returns the bitmaps, each + with its decoded whole BMap as `bmap`, and the offset after the last.""" + if count > rvtfile.EXTENSION_BITMAPS_MAX: + fail(where, f"{count} extension bitmaps exceed {rvtfile.EXTENSION_BITMAPS_MAX}") + found = [] + previous = None + for _ in range(count): + if at + rvtfile.EXTENSION_BITMAP_BYTES > len(body): + fail(where, "truncated extension bitmap header") + owner, asset, kind, stored, decoded, tint = ( + rvtfile.EXTENSION_BITMAP.unpack_from(body, at) + ) + name = f"extension bitmap {owner:#010x}/{asset:#010x}" + role = tint_role(tint, f"{where}: {name}") + if previous is not None and (owner, asset) <= previous: + fail(where, "extension bitmaps must be sorted by unique owner and asset") + previous = (owner, asset) + if kind not in KIND_NAMES: + fail(where, f"{name} has unknown kind {kind:#x}") + at += rvtfile.EXTENSION_BITMAP_BYTES + if decoded <= HEADER.size: + fail(where, f"{name}: decoded size smaller than a header") + if decoded > rvtfile.EXTENSION_BITMAP_MAX_BYTES: + fail( + where, + f"{name}: {decoded:,} bytes exceed {rvtfile.EXTENSION_BITMAP_MAX_BYTES:,}", + ) + end = at + stored + if rvtfile.align(end) > len(body): + fail(where, f"{name}: truncated payload") + bmap = body[at:end] + if KIND_NAMES[kind] == "bitmap_lz": + if stored > decoded + (decoded + 7) // 8: + fail(where, f"{name}: lz stream longer than its bitmap allows") + try: + bmap = lz.lz_decode(bmap, decoded) + except ValueError as error: + fail(where, f"{name}: {error}") + elif stored != decoded: + fail(where, f"{name}: raw payload is not its decoded size") + if HEADER.size + HEADER.unpack_from(bmap)[8] != decoded or not header_sane( + bmap + ): + fail(where, f"{name}: bitmap header does not describe its bytes") + if any(body[end : rvtfile.align(end)]): + fail(where, f"{name}: padding must be zero") + if role is not None and not tintable(bmap): + fail(where, f"{name}: tinted, but not an Indexed8 or BGRA8888 picture") + found.append( + { + "owner": owner, + "asset": asset, + "kind": KIND_NAMES[kind], + "bytes": stored, + "decoded": decoded, + "tint": role, + "bmap": bmap, + **describe(bmap), + } + ) + at = rvtfile.align(end) + return found, at diff --git a/themes/rvt/bitmaps.py b/themes/rvt/bitmaps.py new file mode 100644 index 0000000..c8ead9f --- /dev/null +++ b/themes/rvt/bitmaps.py @@ -0,0 +1,407 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""PNG reading and the native BMap pixel formats a theme can replace. + +A BMap is a 28-byte header (format, stride, depth, bounds, payload bytes), for +paletted formats a 32-bit colour count and the palette as B, G, R, A, then the +rows, each padded to the stride. The 32-bit format stores B, G, R, A too. A theme record carries everything after the +header (and after the colour count, which never changes), so a replacement is +the same size as the original and the device copies it in place. + +Adapted from the RepriseOS core's themes/compiler.py and patching/bitmap.py (8fc840d) by +lgreitis. +""" + +import struct +import zlib +from collections import Counter + +MASK4, MASK8 = 4, 8 +INDEXED8, INDEXED16 = 0x64, 0x65 +RGB565 = 0x565 +BGRA8888 = 0x1888 +MASK_FORMATS = (MASK4, MASK8) +PALETTE_FORMATS = (INDEXED8, INDEXED16) +BGRA_FORMATS = (BGRA8888,) +DEPTHS = {MASK4: 4, MASK8: 8, INDEXED8: 8, INDEXED16: 16, RGB565: 16, BGRA8888: 32} + + +def paeth(a, b, c): + p = a + b - c + return min((a, b, c), key=lambda value: abs(p - value)) + + +def read_png(data: bytes) -> tuple[int, int, bytes]: + """Width, height and RGBA bytes of a PNG.""" + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError("not a PNG") + chunks = {} + offset = 8 + while offset < len(data): + if offset + 8 > len(data): + raise ValueError("truncated PNG") + size, kind = struct.unpack_from(">I4s", data, offset) + if offset + 12 + size > len(data): + raise ValueError("truncated PNG") + body = data[offset + 8 : offset + 8 + size] + crc = struct.unpack_from(">I", data, offset + 8 + size)[0] + if zlib.crc32(kind + body) != crc: + raise ValueError("PNG chunk checksum mismatch") + chunks.setdefault(kind, bytearray()).extend(body) + offset += size + 12 + if b"IEND" not in chunks or len(chunks.get(b"IHDR", b"")) != 13: + raise ValueError("truncated PNG") + width, height, depth, color, compression, filtering, interlace = struct.unpack( + ">IIBBBBB", chunks[b"IHDR"] + ) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color) + if ( + not width + or not height + or not (depth == 8 or color == 3 and depth in (1, 2, 4)) + or channels is None + or any((compression, filtering, interlace)) + ): + raise ValueError("export a non-interlaced PNG with 8-bit channels or a palette") + try: + raw = zlib.decompress(chunks.get(b"IDAT", b"")) + except zlib.error: + raise ValueError("truncated PNG") from None + stride = (width * channels * depth + 7) // 8 + filter_bytes = max(1, (channels * depth + 7) // 8) + if len(raw) != (stride + 1) * height: + raise ValueError("PNG pixel length does not match its dimensions") + palette = chunks.get(b"PLTE", b"") + alpha = chunks.get(b"tRNS", b"") + transparent = ( + tuple(struct.unpack(">" + "H" * channels, alpha)) + if alpha and color in (0, 2) + else None + ) + previous = bytearray(stride) + pixels = bytearray() + for y in range(height): + start = y * (stride + 1) + filter_type = raw[start] + if filter_type > 4: + raise ValueError("unknown PNG row filter") + row = bytearray(raw[start + 1 : start + 1 + stride]) + for x in range(stride): + a = row[x - filter_bytes] if x >= filter_bytes else 0 + b = previous[x] + c = previous[x - filter_bytes] if x >= filter_bytes else 0 + predictor = (0, a, b, (a + b) // 2, paeth(a, b, c))[filter_type] + row[x] = (row[x] + predictor) & 255 + for x in range(width): + p = tuple(row[x * channels : (x + 1) * channels]) + if color == 3: + bit = x * depth + index = (row[bit // 8] >> (8 - depth - bit % 8)) & ((1 << depth) - 1) + if index * 3 + 3 > len(palette): + raise ValueError("PNG pixel exceeds palette") + rgba = ( + *palette[index * 3 : index * 3 + 3], + alpha[index] if index < len(alpha) else 255, + ) + elif color in (0, 4): + rgba = ( + p[0], + p[0], + p[0], + p[1] if color == 4 else 0 if p == transparent else 255, + ) + else: + rgba = p if color == 6 else (*p, 0 if p == transparent else 255) + pixels.extend(rgba) + previous = row + return width, height, bytes(pixels) + + +def describe(resource_id: int, offset: int, data: bytes, name: str = "") -> dict: + """Catalog entry of a native BMap from its bytes.""" + if len(data) < 28: + raise ValueError(f"{resource_id:#x}: truncated bitmap") + fmt, _, stride, depth = struct.unpack_from("<4H", data) + height, width = struct.unpack_from(" 1 << depth) or stride < (width * depth + 7) // 8: + raise ValueError(f"{resource_id:#x}: invalid palette or stride") + if pixels + stride * height != len(data): + raise ValueError(f"{resource_id:#x}: invalid pixel storage") + return { + "id": resource_id, + "name": name, + "offset": offset, + "bytes": len(data), + "format": fmt, + "depth": depth, + "width": width, + "height": height, + "stride": stride, + "data_offset": start + (4 if colors else 0), + "pixels_offset": pixels, + "palette_colors": colors, + "crc32": zlib.crc32(data), + } + + +def tint_kind(fmt: int) -> str | None: + """How a format takes a tint: masks at draw time, palettes and BGRA8888 + pixels by rewriting their colours on the device; RGB565 has neither palette + nor alpha.""" + if fmt in MASK_FORMATS: + return "mask" + if fmt in PALETTE_FORMATS: + return "palette" + if fmt in BGRA_FORMATS: + return "bgra" + return None + + +def encode_pixels(info: dict, width: int, height: int, rgba: bytes) -> bytes: + """Record payload of a catalog bitmap from RGBA pixels of its native size. + 4-bit masks round to the 16 gray levels the format stores.""" + if (width, height) != (info["width"], info["height"]): + raise ValueError( + f"expected {info['width']}x{info['height']}, got {width}x{height}" + ) + colors = [rgba[i : i + 4] for i in range(0, len(rgba), 4)] + if len(colors) != width * height: + raise ValueError("invalid PNG pixel count") + result = bytearray(info["bytes"] - info["data_offset"]) + fmt, stride = info["format"], info["stride"] + start = info["pixels_offset"] - info["data_offset"] + capacity = info["palette_colors"] + if capacity: + unique = list(dict.fromkeys(colors)) + if len(unique) > capacity: + raise ValueError( + f"{len(unique)} colours exceed the {capacity} of its palette" + ) + lookup = {color: index for index, color in enumerate(unique)} + for index, (red, green, blue, alpha) in enumerate(unique): + result[index * 4 : index * 4 + 4] = bytes((blue, green, red, alpha)) + for y in range(height): + for x in range(width): + at = start + y * stride + x * (info["depth"] // 8) + index = lookup[colors[y * width + x]] + if fmt == INDEXED8: + result[at] = index + else: + struct.pack_into("> 3) << 11 | (green >> 2) << 5 | blue >> 3 + ) + else: + if red != green or green != blue or alpha != 255: + raise ValueError("native grayscale requires opaque gray levels") + if fmt == MASK8: + result[at] = red + else: + at = start + y * stride + x // 2 + shift = 4 if x % 2 == 0 else 0 + result[at] = (result[at] & ~(15 << shift)) | ( + round(red / 17) << shift + ) + return bytes(result) + + +def palette_indices_fit(info: dict, payload: bytes) -> bool: + """True when every pixel of a paletted record payload indexes its palette.""" + capacity = info["palette_colors"] + if not capacity: + return True + start = info["pixels_offset"] - info["data_offset"] + width = info["depth"] // 8 + for y in range(info["height"]): + for x in range(info["width"]): + at = start + y * info["stride"] + x * width + if int.from_bytes(payload[at : at + width], "little") >= capacity: + return False + return True + + +def decode_pixels(info: dict, payload: bytes) -> bytes: + """RGBA pixels of a catalog bitmap from its record payload, the inverse of + encode_pixels. RGB565 channels expand with zero low bits.""" + fmt, stride = info["format"], info["stride"] + width, height = info["width"], info["height"] + start = info["pixels_offset"] - info["data_offset"] + palette = [] + for i in range(info["palette_colors"]): + blue, green, red, alpha = payload[i * 4 : i * 4 + 4] + palette.append(bytes((red, green, blue, alpha))) + out = bytearray() + for y in range(height): + row = start + y * stride + for x in range(width): + if fmt == INDEXED8: + out += palette[payload[row + x]] + elif fmt == INDEXED16: + out += palette[struct.unpack_from("> (4 if x % 2 == 0 else 0) & 15 + out += bytes((nibble * 17,) * 3) + b"\xff" + return bytes(out) + + +def write_png(width: int, height: int, rgba: bytes) -> bytes: + """An RGBA PNG with unfiltered rows.""" + rows = b"".join( + b"\0" + rgba[y * width * 4 : (y + 1) * width * 4] for y in range(height) + ) + + def chunk(kind, body): + return ( + struct.pack(">I", len(body)) + + kind + + body + + struct.pack(">I", zlib.crc32(kind + body)) + ) + + 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(rows)) + + chunk(b"IEND", b"") + ) + + +def pack_565(red, green, blue): + return (red >> 3) << 11 | (green >> 2) << 5 | blue >> 3 + + +def unpack_565(word): + return (word >> 11) << 3, (word >> 5 & 63) << 2, (word & 31) << 3 + + +def is_565(rgba): + """True for an opaque colour RGB565 stores exactly.""" + red, green, blue, alpha = rgba + return alpha == 255 and not (red & 7 or green & 3 or blue & 7) + + +def coverage(rgba: bytes) -> bytes: + """Per-pixel coverage of tinted art: the alpha channel when the PNG uses one, + otherwise the gray level. Coloured, opaque art has no single coverage.""" + alpha = rgba[3::4] + if any(value != 255 for value in alpha): + return bytes(alpha) + if any( + rgba[i] != rgba[i + 1] or rgba[i + 1] != rgba[i + 2] + for i in range(0, len(rgba), 4) + ): + raise ValueError("tinted art must be grayscale or carry alpha coverage") + return bytes(rgba[::4]) + + +def gray_pixels(levels: bytes) -> bytes: + """Opaque gray pixels of a coverage, for a native mask.""" + return b"".join(bytes((value, value, value, 255)) for value in levels) + + +def distinct(rgba: bytes) -> int: + """Distinct colours of RGBA pixels.""" + return len({rgba[i : i + 4] for i in range(0, len(rgba), 4)}) + + +def fit_levels(levels: bytes, capacity: int) -> bytes: + """Coverage reduced to what a palette of `capacity` entries holds, so the + result does not depend on the colour it is painted in afterwards.""" + return fit_palette(b"".join(bytes((0, 0, 0, level)) for level in levels), capacity)[ + 3::4 + ] + + +def tinted_pixels(levels: bytes, tint: str) -> bytes: + """Placeholder-coloured pixels whose alpha carries the coverage; the device + rewrites the palette entries or BGRA8888 pixels with the live role colour.""" + color = bytes.fromhex(tint.removeprefix("#")) + return b"".join(color + bytes((level,)) if level else bytes(4) for level in levels) + + +def premultiplied(color): + return tuple(value * color[3] / 255 for value in color[:3]) + (color[3],) + + +def fit_palette(rgba: bytes, capacity: int) -> bytes: + """Weighted median cut in premultiplied RGBA, reserving transparent pixels.""" + pixels = [tuple(rgba[i : i + 4]) for i in range(0, len(rgba), 4)] + counts = Counter(pixels) + if len(counts) <= capacity: + return rgba + transparent = any(color[3] == 0 for color in counts) + palette = [(0, 0, 0, 0)] if transparent and capacity > 1 else [] + colors = [color for color in counts if color[3] or not palette] + points = {color: premultiplied(color) for color in colors} + boxes = [colors] if colors else [] + while len(boxes) + len(palette) < capacity: + candidates = [] + for i, box in enumerate(boxes): + if len(box) < 2: + continue + spans = [ + max(points[c][axis] for c in box) - min(points[c][axis] for c in box) + for axis in range(4) + ] + axis = max(range(4), key=spans.__getitem__) + candidates.append((spans[axis] ** 2 * sum(counts[c] for c in box), i, axis)) + if not candidates: + break + _, index, axis = max(candidates) + box = sorted(boxes.pop(index), key=lambda color: (points[color][axis], color)) + halfway = sum(counts[c] for c in box) / 2 + accumulated = 0 + split = 1 + for split, color in enumerate(box[:-1], 1): + accumulated += counts[color] + if accumulated >= halfway: + break + boxes.extend((box[:split], box[split:])) + for box in boxes: + total = sum(counts[c] for c in box) + palette.append( + tuple( + round(sum(c[axis] * counts[c] for c in box) / total) + for axis in range(4) + ) + ) + palette_points = [premultiplied(color) for color in palette] + mapping = {} + for color in counts: + point = premultiplied(color) + index = min( + range(len(palette)), + key=lambda i: sum((a - b) ** 2 for a, b in zip(point, palette_points[i])), + ) + mapping[color] = bytes(palette[index]) + return b"".join(mapping[color] for color in pixels) diff --git a/themes/rvt/catalog.py b/themes/rvt/catalog.py new file mode 100644 index 0000000..f888ee0 --- /dev/null +++ b/themes/rvt/catalog.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The bitmap catalog: every BMap of the pinned Apple firmware that a theme can +replace, by index. A pack's records and tint bytes index into this list, so a +theme is tied to the catalog it was compiled against by the fingerprint.""" + +import hashlib +import json +from importlib.resources import files +from pathlib import Path +from typing import TypedDict + +from rvt import bitmaps, rvtfile + +SCHEMA = 1 + + +class Entry(TypedDict): + """One catalog bitmap; docs/catalog.md describes the fields.""" + + id: int + name: str + offset: int + address: int + bytes: int + format: int + depth: int + width: int + height: int + stride: int + data_offset: int + pixels_offset: int + palette_colors: int + crc32: int + + +ENTRY_KEYS = tuple(Entry.__annotations__) +DEFAULT = files("rvt") / "data" / "osos-2.0.5.json" +FORMAT_NAMES = { + bitmaps.MASK4: "mask4", + bitmaps.MASK8: "mask8", + bitmaps.INDEXED8: "indexed8", + bitmaps.INDEXED16: "indexed16", + bitmaps.RGB565: "rgb565", + bitmaps.BGRA8888: "bgra8888", +} + + +def address(offset: int, runtime_base: int, runtime_file_offset: int) -> int: + """Where a bitmap at a file offset lives: Apple loads osos.bin at + runtime_base with the file's first runtime_file_offset bytes stripped.""" + return runtime_base + offset - runtime_file_offset + + +def canonical(entries: list[Entry]) -> bytes: + return json.dumps(entries, sort_keys=True, separators=(",", ":")).encode() + + +def fingerprint(entries: list[Entry]) -> bytes: + """The first FINGERPRINT_BYTES of the SHA-256 of the canonical entry list.""" + return hashlib.sha256(canonical(entries)).digest()[: rvtfile.FINGERPRINT_BYTES] + + +def is_hex_id(reference: str) -> bool: + return ( + reference[:2].lower() == "0x" + and 1 <= len(reference) - 2 <= 8 + and all(c in "0123456789abcdefABCDEF" for c in reference[2:]) + ) + + +class Catalog: + assets: list[Entry] + + def __init__(self, document: dict): + if not isinstance(document, dict) or document.get("schema") != SCHEMA: + raise ValueError(f"catalog: expected schema {SCHEMA}") + entries = document.get("bitmaps") + if not isinstance(entries, list) or not entries: + raise ValueError("catalog: expected a non-empty bitmap list") + if len(entries) > rvtfile.CATALOG_MAX: + raise ValueError(f"catalog: more than {rvtfile.CATALOG_MAX} bitmaps") + self.assets = entries + self.firmware = document.get("firmware", {}) + runtime = (document.get("runtime_base"), document.get("runtime_file_offset")) + if not all(isinstance(value, int) for value in runtime): + raise ValueError("catalog: expected runtime_base and runtime_file_offset") + self.runtime_base, self.runtime_file_offset = runtime + self.by_id: dict[int, int] = {} + self.by_name: dict[str, list[int]] = {} + for index, asset in enumerate(entries): + if tuple(sorted(asset)) != tuple(sorted(ENTRY_KEYS)): + raise ValueError(f"catalog: bitmap {index} has unexpected keys") + if asset["address"] != address(asset["offset"], *runtime): + raise ValueError(f"catalog: bitmap {asset['id']:#010x} address") + if asset["id"] in self.by_id: + raise ValueError(f"catalog: duplicate bitmap id {asset['id']:#010x}") + self.by_id[asset["id"]] = index + self.by_name.setdefault(asset["name"], []).append(index) + self.fingerprint = fingerprint(entries) + stored = document.get("fingerprint") + if stored is not None and stored != self.fingerprint.hex(): + raise ValueError("catalog: stored fingerprint does not match the bitmaps") + + def resolve(self, reference: str, where: str) -> int: + """Index of a bitmap named by catalog name or hex id.""" + if is_hex_id(reference): + value = int(reference, 16) + if value not in self.by_id: + raise ValueError(f"{where}: {value:#010x} is not a catalog bitmap") + return self.by_id[value] + matches = self.by_name.get(reference) + if not matches: + raise ValueError(f"{where}: {reference!r} is not a catalog bitmap name") + if len(matches) > 1: + ids = ", ".join(f"{self.assets[i]['id']:#010x}" for i in matches) + raise ValueError(f"{where}: {reference!r} is ambiguous; use one of {ids}") + return matches[0] + + def payload_bytes(self, index: int) -> int: + asset = self.assets[index] + return asset["bytes"] - asset["data_offset"] + + def max_body(self) -> int: + """Largest valid body: the style prefix plus one record per bitmap.""" + return rvtfile.STYLE_BYTES + sum( + rvtfile.RECORD_BYTES + payload_max(asset) for asset in self.assets + ) + + +def entries(info: Entry) -> int: + """Colour slots a recolour can touch: palette entries or pixels.""" + return info["palette_colors"] or info["width"] * info["height"] + + +def payload_max(info: Entry) -> int: + """The largest padded payload any record kind allows for a bitmap.""" + pixels = info["bytes"] - info["data_offset"] + pairs = min(rvtfile.RECOLOR_MAX, entries(info)) + return max( + rvtfile.align(pixels), + rvtfile.align(4 + pairs * rvtfile.PAIR.size), + rvtfile.RELIGHT_BYTES, + ) + + +def load(path: Path | None = None) -> Catalog: + source = DEFAULT if path is None else Path(path) + return Catalog(json.loads(source.read_text())) diff --git a/themes/rvt/cli.py b/themes/rvt/cli.py new file mode 100644 index 0000000..10ff99a --- /dev/null +++ b/themes/rvt/cli.py @@ -0,0 +1,319 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""rvt: compile and check theme folders, inspect .rvt files, start a theme, +browse the two catalogs, and with a local firmware preview derived art or +turn a PNG into a recolour rule.""" + +import argparse +import json +import struct +import sys +from pathlib import Path + +from rvt import assets, compiler, inspector, rvtfile, theme +from rvt import catalog as catalog_module +from rvt.bitmaps import tint_kind + + +def main(argv=None) -> int | None: + parser = argparse.ArgumentParser(prog="rvt", description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + + def catalog_option(command): + command.add_argument( + "--catalog", + type=Path, + default=None, + help="a catalog other than the built-in", + ) + + def extension_option(command): + command.add_argument( + "--extension", + type=Path, + action="append", + default=[], + metavar="assets.json", + help="the bitmaps of an extension outside the first-party catalog, as " + "the SDK's assets.py prints them; repeatable", + ) + + def theme_options(command): + command.add_argument("folder", type=Path, help="folder with theme.toml") + catalog_option(command) + extension_option(command) + command.add_argument( + "--allow-reserved", + action="store_true", + help="accept the reserved id of the built-in theme", + ) + command.add_argument( + "--strict", action="store_true", help="treat warnings as errors" + ) + + build = commands.add_parser("compile", help="theme folder -> .rvt") + theme_options(build) + build.add_argument("--out", type=Path, default=Path("dist")) + + check = commands.add_parser("check", help="compile without writing") + theme_options(check) + + show = commands.add_parser("inspect", help="validate and describe an .rvt") + show.add_argument("file", type=Path) + catalog_option(show) + extension_option(show) + show.add_argument("--json", action="store_true", help="print the full description") + + new = commands.add_parser("new", help="start a theme folder") + new.add_argument("id", help="the theme's id, also the folder's name") + new.add_argument("--name", help="the display name; defaults to the id") + + browse = commands.add_parser( + "catalog", help="list or show Apple's bitmaps and extension bitmaps" + ) + browse_commands = browse.add_subparsers(dest="catalog_command", required=True) + listing = browse_commands.add_parser("list", help="name, size, format, palette") + listing.add_argument( + "--extensions", + action="store_true", + help="extension bitmaps instead of Apple's bitmaps", + ) + listing.add_argument("--group", help="name prefix, or an extension id") + listing.add_argument( + "--format", dest="fmt", help=", ".join(catalog_module.FORMAT_NAMES.values()) + ) + catalog_option(listing) + extension_option(listing) + detail = browse_commands.add_parser( + "show", help="every field of one Apple bitmap or extension bitmap" + ) + detail.add_argument("name", help="catalog name, hex id or /") + catalog_option(detail) + extension_option(detail) + + preview = commands.add_parser( + "preview", help="render the art a theme derives, from a firmware" + ) + theme_options(preview) + preview.add_argument( + "--firmware", type=Path, required=True, help="osos.bin or osos-cfw.bin" + ) + preview.add_argument("--out", type=Path, default=Path("dist")) + + recolor = commands.add_parser( + "recolor", help="turn /apple/.png into a recolour rule file" + ) + recolor.add_argument("png", type=Path, help="//apple/.png") + recolor.add_argument( + "--firmware", type=Path, required=True, help="osos.bin or osos-cfw.bin" + ) + catalog_option(recolor) + + args = parser.parse_args(argv) + try: + if args.command == "new": + print(new_theme(args.id, args.name)) + return None + catalog = catalog_module.load(args.catalog) + extensions = assets.load_catalog(getattr(args, "extension", [])) + if args.command == "compile": + path, build = compiler.write( + catalog, + args.folder, + args.out, + args.allow_reserved, + args.strict, + extensions, + ) + report(build) + print(f"Wrote {path}") + elif args.command == "check": + build = compiler.compile_theme( + catalog, args.folder, args.allow_reserved, args.strict, extensions + ) + report(build) + elif args.command == "inspect": + result = inspector.inspect( + args.file.read_bytes(), catalog, assets.known_names(extensions) + ) + if args.json: + print(json.dumps(result, indent=2, default=lambda b: b.hex())) + else: + print(inspector.describe(result)) + elif args.command == "catalog": + if args.catalog_command == "list" and args.extensions: + for line in extension_list(extensions, args.group, args.fmt): + print(line) + elif args.catalog_command == "list": + for line in catalog_list(catalog, args.group, args.fmt): + print(line) + elif "/" in args.name: + print(extension_show(extensions, args.name)) + else: + print(catalog_show(catalog, args.name)) + elif args.command == "preview": + for line in render(catalog, extensions, args): + print(line) + else: + print(convert(catalog, args), end="") + except (OSError, ValueError, struct.error) as error: + parser.exit(1, f"{error}\n") + return None + + +def report(build: compiler.Build) -> None: + """Notes, warnings and the size table of a compiled theme.""" + for note in build.notes: + print(note) + for warning in build.warnings: + print(f"warning: {warning}", file=sys.stderr) + print(compiler.summary(build.inspection, len(build.data))) + + +def new_theme(identifier: str, name: str | None) -> str: + """Write /theme.toml with every option as a comment, and the apple/, + reprise/ and extensions/ folders of light/ and dark/.""" + rvtfile.check_id(identifier) + if identifier in theme.RESERVED_IDS: + raise ValueError(f"id: {identifier!r} is reserved for the built-in theme") + name = rvtfile.check_name(name or identifier) + folder = Path(identifier) + if folder.exists(): + raise ValueError(f"{folder} exists") + for appearance in rvtfile.APPEARANCES: + for sub in compiler.FOLDERS: + (folder / appearance / sub).mkdir(parents=True) + (folder / "theme.toml").write_text(theme.template(identifier, name)) + return f"Wrote {folder}/theme.toml and {{light,dark}}/{{{','.join(compiler.FOLDERS)}}}/" + + +def catalog_list(catalog, group: str | None, fmt: str | None) -> list[str]: + """name WxH format palette tintable, one line per bitmap.""" + names = catalog_module.FORMAT_NAMES + if fmt is not None and fmt not in names.values(): + raise ValueError(f"--format: expected one of {', '.join(names.values())}") + lines = [] + for asset in catalog.assets: + if group and not asset["name"].startswith(group): + continue + if fmt and names[asset["format"]] != fmt: + continue + lines.append( + f"{asset['name']} {asset['width']}x{asset['height']} " + f"{names[asset['format']]} {asset['palette_colors']} " + f"{'tintable' if tint_kind(asset['format']) else 'untintable'}" + ) + return lines + + +def extension_list(extensions: dict, group: str | None, fmt: str | None) -> list[str]: + """id asset WxH format palette menu, one line per extension bitmap.""" + names = assets.FORMAT_NAMES + if fmt is not None and fmt not in names.values(): + raise ValueError(f"--format: expected one of {', '.join(names.values())}") + lines = [] + for (identifier, asset), record in sorted(extensions.items()): + if group and identifier != group: + continue + name = names.get(record["format"], f"{record['format']:#x}") + if fmt and name != fmt: + continue + lines.append( + f"{identifier} {asset} {record['width']}x{record['height']} {name} " + f"{record['palette_colors']} {'menu' if record['menu'] else 'bitmap'}" + ) + return lines + + +def extension_show(extensions: dict, reference: str) -> str: + """Every field of one extension bitmap, named /.""" + identifier, _, asset = reference.partition("/") + record = extensions.get((identifier, asset)) + if record is None: + raise ValueError( + f"name: {reference!r} is not in the extension asset catalog; " + "--extension adds an extension's assets.json" + ) + lines = [] + for key in assets.RECORD_KEYS: + value = record[key] + if key == "format": + value = f"{value:#x}" + elif isinstance(value, bool): + value = str(value).lower() + lines.append(f"{key} {value}") + lines.append(f"format_name {assets.FORMAT_NAMES.get(record['format'], 'unknown')}") + lines.append(f"owner_hash {assets.owner_hash(identifier):#010x}") + lines.append(f"asset_hash {assets.asset_hash(asset):#010x}") + return "\n".join(lines) + + +def catalog_show(catalog, reference: str) -> str: + """Every field of one bitmap; a name listed twice shows both.""" + if catalog_module.is_hex_id(reference): + indices = [catalog.resolve(reference, "name")] + else: + indices = catalog.by_name.get(reference) + if not indices: + raise ValueError(f"name: {reference!r} is not a catalog bitmap name") + blocks = [] + for index in indices: + asset = catalog.assets[index] + lines = [f"index {index}"] + for key, value in asset.items(): + text = f"{value:#x}" if key in ("id", "address", "format") else value + lines.append(f"{key} {text}") + lines.append(f"format_name {catalog_module.FORMAT_NAMES[asset['format']]}") + blocks.append("\n".join(lines)) + return "\n\n".join(blocks) + + +def convert(catalog, args) -> str: + """Write /.toml beside the PNG and return a summary.""" + from rvt import firmware + + png = args.png.resolve() + appearance = png.parent.parent.name + if ( + png.parent.name != compiler.APPLE + or appearance not in rvtfile.APPEARANCES + or png.suffix != ".png" + ): + raise ValueError( + f"expected //{compiler.APPLE}/.png" + ) + index = catalog.resolve(png.stem, str(args.png)) + pairs, notes = firmware.to_recolor( + catalog, firmware.Firmware(args.firmware, catalog), index, png.read_bytes() + ) + target = png.with_suffix(".toml") + target.write_text(firmware.recolor_text(pairs)) + return "".join(f"{png.name}: {note}\n" for note in notes) + ( + f"Wrote {target} ({len(pairs)} colour pairs); delete {png.name} to use it\n" + ) + + +def render(catalog, extensions, args) -> list[str]: + """Previews of every derived bitmap under //derived/.""" + from rvt import firmware + + build = compiler.compile_theme( + catalog, args.folder, args.allow_reserved, args.strict, extensions + ) + result, warnings = firmware.render( + catalog, firmware.Firmware(args.firmware, catalog), build.data + ) + root = args.out / build.report["id"] / "derived" + listing = {} + for appearance, entries in result.items(): + (root / appearance).mkdir(parents=True, exist_ok=True) + listing[appearance] = {} + for name, entry in entries.items(): + (root / appearance / f"{name}.png").write_bytes(entry.pop("png")) + listing[appearance][name] = entry + (root / "derived.json").write_text(json.dumps(listing, indent=2) + "\n") + count = sum(len(entries) for entries in listing.values()) + return [*warnings, f"Wrote {count} previews and derived.json under {root}"] + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/rvt/compiler.py b/themes/rvt/compiler.py new file mode 100644 index 0000000..836d626 --- /dev/null +++ b/themes/rvt/compiler.py @@ -0,0 +1,422 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Compile a theme folder (theme.toml, light/, dark/) into .rvt. + +An appearance folder holds `apple/`, a PNG or TOML per catalog bitmap, +`extensions//.png`, the bitmap assets of extensions, and +`reprise/.png`, the core's own. + +Everything is checked and built in memory, the result is read back through the +inspector, and only then are .rvt and report.json written. +""" + +import json +import re +import struct +import zlib +from dataclasses import dataclass, field +from pathlib import Path + +from rvt import assets, bitmaps, derive, inspector, lz, rvtfile, style, theme +from rvt.catalog import Catalog, Entry +from rvt.derive import Rule +from rvt.errors import fail + +FILE_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._ -]{0,127}") +APPLE = "apple" +FOLDERS = (APPLE, assets.CORE_FOLDER, assets.FOLDER) + + +@dataclass +class Build: + """A compiled theme: the file, the report, the inspector's description of + the file, the warnings `rvt check` prints and `--strict` rejects, the + notes about rule matches, and the payloads the compiler derived from the + other appearance (appearance -> name -> bytes from the bitmap's data + offset).""" + + data: bytes + report: dict + inspection: dict + warnings: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + resolved: dict[str, dict[str, bytes]] = field(default_factory=dict) + + +def check_layout(folder: Path, appearance: str) -> None: + """An appearance folder holds only apple/, reprise/ and extensions/.""" + directory = Path(folder) / appearance + if not directory.is_dir(): + return + for path in sorted(directory.iterdir()): + if path.name.startswith(".") or (path.is_dir() and path.name in FOLDERS): + continue + fail( + f"{appearance}/{path.name}", + f"catalog art goes in {appearance}/{APPLE}/, extension bitmaps in " + f"{appearance}/{assets.FOLDER}//, the core's in " + f"{appearance}/{assets.CORE_FOLDER}/", + ) + + +def has_art(folder: Path, appearance: str) -> bool: + return any( + path.is_file() and not path.name.startswith(".") + for path in (Path(folder) / appearance).rglob("*") + ) + + +def find_sources(folder: Path, appearance: str, catalog: Catalog) -> dict: + """Catalog index -> ("png" | "toml", path) for every file in the + appearance's apple/ folder: a PNG replaces the bitmap, a TOML derives it.""" + root = Path(folder).resolve() + directory = root / appearance / APPLE + found = {} + if not directory.is_dir(): + return found + for path in sorted(directory.iterdir()): + where = f"{appearance}/{APPLE}/{path.name}" + if path.name.startswith("."): + continue + if path.suffix not in (".png", ".toml") or not FILE_NAME.fullmatch(path.name): + fail(where, "expected .png, .toml or 0x.png") + limit = assets.PNG_LIMIT if path.suffix == ".png" else theme.TOML_LIMIT + resolved = assets.source_file(path, root, where, limit) + index = catalog.resolve(path.stem, where) + if index in found: + fail(where, f"duplicate replacement for {catalog.assets[index]['name']}") + found[index] = (path.suffix[1:], resolved) + return found + + +def pixel_payload( + info: Entry, path: Path, where: str, tint: bool, icon: str +) -> tuple[bytes, int | None]: + """The native payload of a PNG replacement, and the number of distinct + colours (coverage levels for tinted art) when it exceeded the palette and + was reduced. Tinted art is stored in `icon`, the placeholder the iPod + rewrites.""" + kind = bitmaps.tint_kind(info["format"]) if tint else None + capacity = info["palette_colors"] + reduced = None + try: + width, height, rgba = bitmaps.read_png(path.read_bytes()) + if kind == "mask": + rgba = bitmaps.gray_pixels(bitmaps.coverage(rgba)) + elif kind: + levels = bitmaps.coverage(rgba) + if capacity and len(set(levels)) > capacity: + reduced = len(set(levels)) + levels = bitmaps.fit_levels(levels, capacity) + rgba = bitmaps.tinted_pixels(levels, icon) + elif capacity and bitmaps.distinct(rgba) > capacity: + reduced = bitmaps.distinct(rgba) + rgba = bitmaps.fit_palette(rgba, capacity) + payload = bitmaps.encode_pixels(info, width, height, rgba) + except (KeyError, ValueError, zlib.error, struct.error) as error: + fail(where, str(error) or type(error).__name__) + if len(payload) != info["bytes"] - info["data_offset"]: + fail(where, "native encoding changed the bitmap size") + return payload, reduced + + +class Plan: + """One appearance before its bytes: style, tints and records as + index -> Rule, each with the text naming its origin.""" + + def __init__( + self, + catalog: Catalog, + folder: Path, + appearance: str, + table: dict, + extensions: dict, + ): + self.catalog = catalog + self.appearance = appearance + self.warnings: list[str] = [] + self.notes: list[str] = [] + self.reduced: list[dict] = [] + self.resolved: dict[str, bytes] = {} + check_layout(folder, appearance) + sources = find_sources(folder, appearance, catalog) + self.origin = { + index: f"{appearance}/{APPLE}/{path.name}" + for index, (_, path) in sources.items() + } + (self.colors, self.flags, self.palettes), self.report, warnings = ( + theme.resolve_style(appearance, table) + ) + self.warnings += warnings + self.tinted, self.tinted_bitmaps, warnings = theme.resolve_tints( + table, appearance, catalog + ) + self.warnings += warnings + rules, owners, self.notes = theme.resolve_rules( + table, appearance, catalog, sources + ) + self.records: dict[int, Rule] = {} + for index, (source, path) in sorted(sources.items()): + info = catalog.assets[index] + where = self.origin[index] + if source == "png": + payload, reduced = pixel_payload( + info, path, where, index in self.tinted, self.colors["icon_tint"] + ) + if reduced is not None: + self.reduced.append( + { + "name": info["name"], + "colors": reduced, + "palette": info["palette_colors"], + } + ) + self.warnings.append( + f"{where}: {reduced} colours reduced to the " + f"{info['palette_colors']} of its palette" + ) + self.records[index] = Rule("pixels", payload) + else: + self.records[index] = derive.load(path, index, catalog, where) + for index, rule in rules.items(): + self.origin[index] = f"{appearance}.derive.{owners[index]!r}" + self.records[index] = rule + self.check_tints() + self.bitmaps: dict[tuple[str, str], bytes] = {} + sources = assets.find_sources(folder, appearance) + for key, role in self.tinted_bitmaps.items(): + if key not in sources: + fail( + f"{appearance}.tint.{role}", + f"{key[0]}/{key[1]} has no {assets.source_path(appearance, *key)}", + ) + for key, path in sources.items(): + where = assets.source_path(appearance, *key) + record = extensions.get(key) + tint = self.tinted_bitmaps.get(key) + self.bitmaps[key] = assets.encode( + path, where, record, self.colors["icon_tint"] if tint else None + ) + if record is None: + self.warnings.append( + f"{where}: not in the extension asset catalog, compiled as a " + "Settings icon; docs/extension-bitmaps.md lists the first-party " + "bitmaps, --extension adds others" + ) + if not self.flags & rvtfile.FLAGS["flat_icons"]: + for key, bmap in self.bitmaps.items(): + if assets.is_menu(bmap) and not assets.has_reflection(bmap): + self.warnings.append( + f"{assets.source_path(appearance, *key)}: no reflection " + "below the art; draw one or set " + f"flat_icons = true in [{appearance}.rendering]" + ) + + def name(self, index: int) -> str: + return self.catalog.assets[index]["name"] + + def check_tints(self) -> None: + """A tint needs stock art or a PNG, never a derivation; darkness + coverage needs the stock art.""" + for index, (_, coverage) in self.tinted.items(): + record = self.records.get(index) + if record is None: + continue + at = f"{self.appearance}.tint.{self.name(index)}" + if record.kind != "pixels": + fail( + at, + f"{self.name(index)} is derived by {self.origin[index]}; " + "a tint cannot be combined with a derivation", + ) + if coverage != "alpha": + fail( + f"{at}.coverage", + f"coverage needs stock art; remove {self.origin[index]}", + ) + + def resolve_from_other(self, other: "Plan | None") -> None: + """Records starting from the theme's own art in the other appearance + become pixels records computed here, as the iPod would compute them + from that art. The art must be a PNG the other appearance does not + tint, since a tinted PNG carries coverage, not colours.""" + for index, rule in sorted(self.records.items()): + if not rule.from_other: + continue + where = f"{self.origin[index]}.from_other" + if other is None: + fail(where, "the theme has one appearance") + target = rule.spec if rule.kind == "alias" else index + name = self.name(target) + base = other.records.get(target) + if base is None: + fail(where, f"{name} has no art in {other.appearance}/{APPLE}/") + if base.kind != "pixels" or base.from_other: + fail( + where, + f"{name} is derived in {other.appearance}/{APPLE}/; it must be a PNG", + ) + if target in other.tinted: + fail(where, f"{name} is tinted in {other.appearance}/{APPLE}/") + try: + result = derive.apply_record( + self.catalog, self.blank, index, rule.kind, rule.spec, {}, base.spec + ) + except ValueError as error: + fail(where, str(error)) + payload = result[self.catalog.assets[index]["data_offset"] :] + self.records[index] = Rule("pixels", payload) + self.resolved[self.name(index)] = payload + + def blank(self, index: int) -> bytes: + """A bitmap of the right size whose header is never read.""" + return bytes(self.catalog.assets[index]["bytes"]) + + def check_aliases(self) -> None: + aliases = { + index: rule.spec + for index, rule in self.records.items() + if rule.kind == "alias" + } + derive.check_aliases( + aliases, + self.tinted, + self.name, + lambda index: ( + self.appearance if index is None else f"{self.origin[index]}.source" + ), + ) + + def body(self) -> bytes: + """The pack body: style prefix, records and extension bitmaps, pixels + and bitmap rows compressed when that is smaller.""" + body = bytearray(style.encode(*self.style_tuple(), self.tinted)) + counts: dict[str, int] = {} + for index, rule in sorted(self.records.items()): + kind, payload = rule.kind, derive.encode(rule.kind, rule.spec) + if kind == "pixels": + packed = lz.lz_encode(payload) + if len(packed) < len(payload): + kind, payload = "pixels_lz", packed + counts[kind] = counts.get(kind, 0) + 1 + body += rvtfile.RECORD.pack(index, rvtfile.KINDS.index(kind), len(payload)) + body += payload + body += bytes(-len(body) % 4) + if len(body) > self.catalog.max_body(): + fail(self.appearance, "exceeds the largest size the catalog allows") + table, self.bitmap_count, bitmap_counts = assets.encode_table( + self.bitmaps, self.tinted_bitmaps + ) + body += table + self.report["records"] = dict(sorted(counts.items())) + self.report["extension_bitmaps"] = dict(sorted(bitmap_counts.items())) + self.report["extension_tinted"] = { + f"{identifier}/{asset}": role + for (identifier, asset), role in sorted(self.tinted_bitmaps.items()) + } + self.report["palette_reduced"] = self.reduced + self.report["bytes"] = len(body) + return bytes(body) + + def style_tuple(self) -> tuple: + return self.colors, self.flags, self.palettes + + +def compile_theme( + catalog: Catalog, + folder: Path, + allow_reserved: bool = False, + strict: bool = False, + extensions: dict | None = None, +) -> Build: + """The .rvt bytes, report, warnings and notes of a theme folder; with + strict, warnings are errors. `extensions` is the extension asset catalog + ((id, asset) -> record), the vendored one when None. The built-in theme's + packs carry art only: no rendering flags, no tints.""" + folder = Path(folder) + if extensions is None: + extensions = assets.load_catalog() + document = theme.load(folder) + reserved = document["id"] in theme.RESERVED_IDS + if reserved and not allow_reserved: + fail("id", f"{document['id']!r} is reserved for the built-in theme") + for appearance in rvtfile.APPEARANCES: + if appearance not in document and has_art(folder, appearance): + fail(appearance, f"has art but theme.toml declares no [{appearance}]") + plans = { + appearance: Plan(catalog, folder, appearance, document[appearance], extensions) + for appearance in rvtfile.APPEARANCES + if appearance in document + } + for appearance, plan in plans.items(): + if reserved and (plan.flags or plan.tinted or plan.tinted_bitmaps): + fail(appearance, "the built-in theme carries art only: no flags, no tints") + others = [p for a, p in plans.items() if a != appearance] + plan.resolve_from_other(others[0] if others else None) + for plan in plans.values(): + plan.check_aliases() + assets.check_collisions([key for plan in plans.values() for key in plan.bitmaps]) + packs = { + a: (plan.body(), len(plan.records), plan.bitmap_count) + for a, plan in plans.items() + } + report = { + key: document[key] + for key in ("id", "name", "author", "version") + if key in document + } + report["appearances"] = {a: plan.report for a, plan in plans.items()} + data = rvtfile.encode_file( + catalog.fingerprint, document["id"], document["name"], packs + ) + build = Build( + data, + report, + inspector.inspect(data, catalog, assets.known_names(extensions)), + [w for plan in plans.values() for w in plan.warnings], + [n for plan in plans.values() for n in plan.notes], + {a: plan.resolved for a, plan in plans.items()}, + ) + if strict and build.warnings: + fail( + "", + "\n".join( + [f"{len(build.warnings)} warnings with --strict:"] + build.warnings + ), + ) + return build + + +def write( + catalog: Catalog, + folder: Path, + out: Path, + allow_reserved: bool = False, + strict: bool = False, + extensions: dict | None = None, +) -> tuple[Path, Build]: + """Compile and write //.rvt and report.json.""" + build = compile_theme(catalog, folder, allow_reserved, strict, extensions) + directory = Path(out) / build.report["id"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / f"{build.report['id']}.rvt" + path.write_bytes(build.data) + (directory / "report.json").write_text( + json.dumps(build.report, indent=2, sort_keys=True) + "\n" + ) + return path, build + + +def summary(result: dict, size: int) -> str: + """One line per appearance for the console, from an inspect() result.""" + lines = [f"{result['id']}.rvt: {size:,} bytes"] + for appearance, pack in result["appearances"].items(): + counts = inspector.counts(pack["records"]) + pixels = sum(counts.get(kind, 0) for kind in rvtfile.PIXEL_KINDS) + derived = len(pack["records"]) - pixels + lines.append( + f" {appearance}: {len(pack['records'])} bitmaps " + f"({pixels} pixels, {derived} derived), " + f"{len(pack['extension_bitmaps'])} extension bitmaps, " + f"{pack['bytes']:,} bytes" + ) + return "\n".join(lines) diff --git a/themes/rvt/data/__init__.py b/themes/rvt/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/themes/rvt/data/bitmap.py b/themes/rvt/data/bitmap.py new file mode 100644 index 0000000..591e0aa --- /dev/null +++ b/themes/rvt/data/bitmap.py @@ -0,0 +1,190 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""PNG to the device's BMap bitmap format, for rvx-pack. + +A BMap is a 28-byte header (format, stride in bytes, depth, bounds as top, left, +bottom, right, payload bytes) and its payload; rows are padded to a word. + +- Picture, with at most 256 colours: indexed, a 32-bit palette count, the + palette as B, G, R, A, then one byte per pixel. Otherwise B, G, R, A per + pixel, not premultiplied. +- Pane picture (`pane = "picture"` in the manifest): a picture of one of the + sizes the menu panes show (PICTURE_SIZES), or the 20 x 16 badge beside a + pane's count line (`"badge"`). +- Pane icon (`"icon"`): what the stock Settings pane icons are, a 78 x 121 mask + of one coverage byte per pixel (0 clear, 255 full) that the device draws in + its own colour. Coverage is the alpha channel when any pixel is translucent, + else the gray level of an opaque grayscale PNG. + +Ships in the SDK beside rvx-pack, so it depends on nothing outside this file. + +Adapted from RepriseOS patching/bitmap.py (bf749b2) by lgreitis. +""" + +import struct +import zlib + +HEADER = struct.Struct("I4s", data, offset) + body = data[offset + 8 : offset + 8 + size] + crc = struct.unpack_from(">I", data, offset + 8 + size)[0] + if zlib.crc32(kind + body) != crc: + raise ValueError("PNG chunk checksum mismatch") + chunks.setdefault(kind, bytearray()).extend(body) + offset += size + 12 + width, height, depth, color, compression, filtering, interlace = struct.unpack( + ">IIBBBBB", chunks[b"IHDR"] + ) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color) + if ( + not width + or not height + or not (depth == 8 or color == 3 and depth in (1, 2, 4)) + or channels is None + or any((compression, filtering, interlace)) + ): + raise ValueError("export a non-interlaced PNG with 8-bit channels or a palette") + raw = zlib.decompress(chunks[b"IDAT"]) + stride = (width * channels * depth + 7) // 8 + filter_bytes = max(1, (channels * depth + 7) // 8) + if len(raw) != (stride + 1) * height: + raise ValueError("PNG pixel length does not match its dimensions") + palette = chunks.get(b"PLTE", b"") + alpha = chunks.get(b"tRNS", b"") + transparent = ( + tuple(struct.unpack(">" + "H" * channels, alpha)) + if alpha and color in (0, 2) + else None + ) + previous = bytearray(stride) + pixels = bytearray() + for y in range(height): + start = y * (stride + 1) + filter_type = raw[start] + if filter_type > 4: + raise ValueError("unknown PNG row filter") + row = bytearray(raw[start + 1 : start + 1 + stride]) + for x in range(stride): + a = row[x - filter_bytes] if x >= filter_bytes else 0 + b = previous[x] + c = previous[x - filter_bytes] if x >= filter_bytes else 0 + predictor = (0, a, b, (a + b) // 2, paeth(a, b, c))[filter_type] + row[x] = (row[x] + predictor) & 255 + for x in range(width): + p = tuple(row[x * channels : (x + 1) * channels]) + if color == 3: + bit = x * depth + index = (row[bit // 8] >> (8 - depth - bit % 8)) & ((1 << depth) - 1) + if index * 3 + 3 > len(palette): + raise ValueError("PNG pixel exceeds palette") + rgba = ( + *palette[index * 3 : index * 3 + 3], + alpha[index] if index < len(alpha) else 255, + ) + elif color in (0, 4): + rgba = ( + p[0], + p[0], + p[0], + p[1] if color == 4 else 0 if p == transparent else 255, + ) + else: + rgba = p if color == 6 else (*p, 0 if p == transparent else 255) + pixels.extend(rgba) + previous = row + return width, height, bytes(pixels) + + +def encode_bmap(width, height, rgba, sizes=()): + """BMap bytes for RGBA pixels: indexed with at most 256 colours, else BGRA; + `sizes` are the (width, height) the picture may have, any when empty.""" + if sizes and (width, height) not in sizes: + allowed = ", ".join(f"{w} x {h}" for w, h in sizes) + raise ValueError(f"the picture is {width} x {height}, not one of {allowed}") + if len(rgba) != width * height * 4: + raise ValueError("RGBA pixel length does not match its dimensions") + pixels = [rgba[i : i + 4] for i in range(0, len(rgba), 4)] + colors = list(dict.fromkeys(pixels)) + indexed = len(colors) <= 256 + depth = 8 if indexed else 32 + stride = (width * depth // 8 + 3) & ~3 + if not width or not height or stride > 0x7FFF: + raise ValueError("bitmap dimensions exceed the row stride") + padding = bytes(stride - width * depth // 8) + payload = bytearray() + if indexed: + payload += struct.pack(".rvt: a header, then one appearance pack + * for light and one for dark, either optional. The layout is documented in + * themes/docs/format.md; this header is its one source of numbers, + * vendored by the appearance extension byte for byte. All integers are + * little-endian. A reader accepts exactly RVT_VERSION and places the packs by + * the header's own header-bytes field, never by RVT_HEADER_BYTES. + * + * Invariants the defines cannot say: records are in ascending catalog index + * and padded to 4 bytes; a pixels record holds the bitmap from its data offset + * to its end (palette, then rows); an lz record decodes to exactly that length + * and the stream must end at the record's end; a recolour table is strictly + * ascending by `from` read as a little-endian u32; an alias names a catalog + * bitmap of the same size that is neither a mask nor tinted, and aliases are + * applied after the other records of the pack; every alpha byte in the style + * prefix is 255. The pack's extension bitmaps follow its last record, + * ascending by owner then asset (both FNV-1a hashes, as the extension package + * catalog keys them; the core's own assets are owned by the hash of "reprise"); + * a bitmap payload is the whole BMap as the iPod decodes it, its 28-byte header + * raw and its rows raw or as one lz stream decoding to the header's payload + * length, the stream at most the payload plus one flag byte per 8; a tinted + * extension bitmap is an Indexed8 or BGRA8888 picture, never a Settings icon, + * whose palette entries or pixels the reader paints in its role, keeping + * their alpha. The relight arithmetic and the bounds of its words are in + * docs/format.md under Relight. */ + +#ifndef RVT_H +#define RVT_H + +#define RVT_MAGIC 0x30545652u /* "RVT0" */ +#define RVT_VERSION 3 +#define RVT_HEADER_BYTES 128 +#define RVT_FINGERPRINT_BYTES 8 +#define RVT_ID_BYTES 32 +#define RVT_NAME_BYTES 48 + +/* Header field offsets. The CRC covers the first RVT_HEADER_BYTES with its own + * word as zero; the bytes after the name up to RVT_HEADER_BYTES are zero. */ +#define RVT_HEADER_MAGIC 0 /* u32 */ +#define RVT_HEADER_VERSION 4 /* u16 */ +#define RVT_HEADER_HEADER_BYTES 6 /* u16, where the packs begin */ +#define RVT_HEADER_FINGERPRINT 8 /* RVT_FINGERPRINT_BYTES */ +#define RVT_HEADER_APPEARANCES 16 /* u32, RVT_APPEARANCE_* bits */ +#define RVT_HEADER_LIGHT_OFFSET 20 /* u32, 0 when absent */ +#define RVT_HEADER_LIGHT_BYTES 24 /* u32 */ +#define RVT_HEADER_DARK_OFFSET 28 /* u32, 0 when absent */ +#define RVT_HEADER_DARK_BYTES 32 /* u32 */ +#define RVT_HEADER_CRC 36 /* u32 */ +#define RVT_HEADER_ID 40 /* RVT_ID_BYTES, NUL-padded ASCII */ +#define RVT_HEADER_NAME 72 /* RVT_NAME_BYTES, NUL-padded UTF-8 */ + +#define RVT_APPEARANCE_LIGHT 1 +#define RVT_APPEARANCE_DARK 2 + +/* Pack header field offsets; the body follows. */ +#define RVT_PACK_BODY_BYTES 0 /* u32, at least RVT_STYLE_BYTES */ +#define RVT_PACK_RECORDS 4 /* u32, record count */ +#define RVT_PACK_CRC 8 /* u32, CRC-32 of the body */ +#define RVT_PACK_EXTENSION_BITMAPS 12 /* u32, at most RVT_EXTENSION_BITMAPS_MAX */ +#define RVT_PACK_HEADER_BYTES 16 + +/* Colour roles, in prefix order. */ +enum rvt_role { + RVT_ROLE_BACKGROUND, + RVT_ROLE_TEXT, + RVT_ROLE_ACCENT_FILL, + RVT_ROLE_ACCENT_TEXT, + RVT_ROLE_ON_ACCENT, + RVT_ROLE_SELECTION, + RVT_ROLE_COVER_BORDER, + RVT_ROLE_ICON_TINT, + RVT_ROLES +}; + +/* Named accents a listener picks, in palette order. */ +enum rvt_accent { + RVT_ACCENT_BLUE, + RVT_ACCENT_PURPLE, + RVT_ACCENT_PINK, + RVT_ACCENT_RED, + RVT_ACCENT_ORANGE, + RVT_ACCENT_GREEN, + RVT_ACCENT_TEAL, + RVT_ACCENT_YELLOW, + RVT_ACCENT_GRAPHITE, + RVT_ACCENTS +}; + +/* The slots of an accent palette, each replacing the role of its name. */ +enum rvt_accent_slot { + RVT_SLOT_ACCENT_FILL, + RVT_SLOT_ACCENT_TEXT, + RVT_SLOT_SELECTION, + RVT_SLOT_ON_ACCENT, + RVT_SLOT_ICON_TINT, + RVT_ACCENT_SLOTS +}; + +#define RVT_FLAG_FLAT_SELECTION 1 +#define RVT_FLAG_MENU_COVERS_OFF 2 +#define RVT_FLAG_FLAT_NOW_PLAYING 4 +#define RVT_FLAG_FLAT_ICONS 8 /* extension menu icons without their reflection */ + +/* Tint bytes: RVT_TINT_ROLE plus an rvt_role. A reader packs them two per + * byte, so they stay below 16. One coverage bit may be or-ed into the byte. */ +#define RVT_TINT_NONE 0 +#define RVT_TINT_ROLE 1 +#define RVT_TINT_DARKNESS 0x80 /* coverage from darkness */ +#define RVT_TINT_SOLID 0x40 /* coverage at or above RVT_SOLID_FLOOR becomes full */ +#define RVT_SOLID_FLOOR 150 /* of 255; a 4-bit mask level at or above 150 x 15 / 255 */ + +/* Catalog bitmaps a pack can address: records and tint bytes index them. */ +#define RVT_CATALOG_MAX 640 + +/* Style prefix offsets. */ +#define RVT_STYLE_COLORS 0 /* RVT_ROLES x RGBA */ +#define RVT_STYLE_FLAGS (RVT_ROLES * 4) +#define RVT_STYLE_PALETTES (RVT_STYLE_FLAGS + 4) /* RVT_ACCENTS x RVT_ACCENT_SLOTS x RGBA */ +#define RVT_STYLE_TINTS (RVT_STYLE_PALETTES + RVT_ACCENTS * RVT_ACCENT_SLOTS * 4) +#define RVT_STYLE_BYTES (RVT_STYLE_TINTS + RVT_CATALOG_MAX) +#define RVT_RECORD_BYTES 12 + +/* Record kinds, the second record word. Every kind but the two pixel kinds is + * computed on the iPod from the bitmap's stock bytes. */ +enum rvt_kind { + RVT_KIND_PIXELS, /* the bitmap's bytes from its data offset to its end */ + RVT_KIND_RECOLOR, /* u32 count, count x {u8 from[4], u8 to[4]} RGBA */ + RVT_KIND_ALIAS, /* u32 source catalog index: its pixels as the pack leaves them */ + RVT_KIND_INVERT, /* no payload: RGB inverted, alpha kept */ + RVT_KIND_RELIGHT, /* RVT_RELIGHT_WORDS x i32 8.8, enum rvt_relight order */ + RVT_KIND_PIXELS_LZ, /* RVT_KIND_PIXELS compressed as RVT_LZ describes */ + RVT_KINDS +}; + +/* RVT_LZ: groups of a flag byte and up to 8 items, bit 0 first. A clear bit is + * a literal byte. A set bit is a match of two bytes, LLLLDDDD DDDDDDDD: it + * copies L + 3 bytes from D + 1 bytes back in the output; L = 15 adds the + * following bytes to the length while they are 255, and the first that is not. + * Matches copy from the output itself, so a decoder needs no window. */ +#define RVT_LZ_WINDOW 4096 +#define RVT_LZ_MIN_MATCH 3 + +/* Relight words, in payload order. */ +enum rvt_relight { + RVT_RELIGHT_T_ZERO, + RVT_RELIGHT_T_FULL, + RVT_RELIGHT_BG_BASE, + RVT_RELIGHT_BG_REF, + RVT_RELIGHT_BG_SLOPE, + RVT_RELIGHT_BG_LO, + RVT_RELIGHT_BG_HI, + RVT_RELIGHT_ICON_BASE, + RVT_RELIGHT_ICON_LUMA, + RVT_RELIGHT_ICON_ROW, + RVT_RELIGHT_ICON_LO, + RVT_RELIGHT_ICON_HI, + RVT_RELIGHT_WORDS +}; +#define RVT_RELIGHT_BYTES (RVT_RELIGHT_WORDS * 4) + +/* Limits the reader's one scratch block per switch imposes: a recolour table + * of RVT_RECOLOR_MAX pairs, or the per-pixel grays of a relight or a + * re-encoded alias plus a 256-byte gray map. */ +#define RVT_SCRATCH_BYTES 4096 +#define RVT_RECOLOR_MAX 512 +#define RVT_SCRATCH_PIXELS 3840 +/* Alias records are applied after the other records of a pack. */ +#define RVT_ALIASES_MAX 16 + +/* Extension bitmaps: {u32 owner, u32 asset, u32 kind, u32 stored, u32 decoded, + * u32 tint} then the payload, 4-byte padded: the whole BMap, header and rows, + * raw or as one lz stream of `stored` bytes that decodes to `decoded`. The + * tint word is RVT_TINT_NONE, or RVT_TINT_ROLE plus an rvt_role without + * coverage bits for a picture drawn in that role. */ +#define RVT_EXTENSION_BITMAP_BYTES 24 +#define RVT_BMAP_HEADER_BYTES 28 +enum rvt_extension_kind { + RVT_EXTENSION_BITMAP = 1, + RVT_EXTENSION_BITMAP_LZ, + RVT_EXTENSION_KINDS +}; +#define RVT_EXTENSION_BITMAPS_MAX 64 +#define RVT_EXTENSION_BITMAP_MAX_BYTES 65536 /* header and rows, decoded */ + +_Static_assert(RVT_TINT_ROLE + RVT_ROLES <= 16, "tint bytes are packed in nibbles"); + +#endif diff --git a/themes/rvt/derive.py b/themes/rvt/derive.py new file mode 100644 index 0000000..9b0c063 --- /dev/null +++ b/themes/rvt/derive.py @@ -0,0 +1,658 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Derived art: records the iPod computes from the stock bitmaps, so a theme +carries colours and rules instead of pixels. + +The authoring side is a rule with a `kind`: one TOML file per bitmap, or a +glob rule in theme.toml. This module parses rules, checks them against the +catalog, encodes and decodes the record payloads, and holds the reference +arithmetic the appearance extension mirrors, applied here to bitmap bytes for +rules the compiler resolves itself (`from_other`), for tests and for previews. +Nothing here reads the firmware; rvt.firmware supplies stock bytes when a +caller has them. +""" + +import re +import struct +import tomllib +from dataclasses import dataclass +from pathlib import Path + +from rvt import bitmaps, rvtfile +from rvt.catalog import Catalog, Entry, entries +from rvt.errors import fail + +RGBA = re.compile(r"#[0-9A-Fa-f]{8}") +KEYS = { + "recolor": {"kind", "from_other", "map"}, + "alias": {"kind", "from_other", "source"}, + "invert": {"kind", "from_other"}, + "relight": {"kind", "from_other", *rvtfile.RELIGHT_FIELDS}, +} +# Classic dark's relight, fitted to its hand-made proxies. +RELIGHT_DEFAULTS = dict( + zip( + rvtfile.RELIGHT_FIELDS, + (3, 14, 25, 216, 10 / 28, 24, 35, 394.6, -1.170, -1.769, 40, 160), + ) +) +ONE = 256 # 8.8 fixed point +FULL = 255 # coverage scale +# The bounds derive.c accepts, in 8.8 units, so the arithmetic cannot overflow. +LEVEL_MAX = 255 * ONE +assert LEVEL_MAX * FULL < 1 << 24 # the per-pixel products stay in 32 bits with room +BASE_MAX = 1024 * ONE +SLOPE_MAX = 16 * ONE +RELIGHT_BOUNDS = { + "bg_base": BASE_MAX, + "bg_ref": LEVEL_MAX, + "bg_slope": SLOPE_MAX, + "icon_base": BASE_MAX, + "icon_luma": LEVEL_MAX, + "icon_row": LEVEL_MAX, +} + + +@dataclass(frozen=True) +class Rule: + """A record before it is encoded: the kind, its spec (a pixels payload, + recolour pairs, an alias source index, None for invert, relight words) and + whether it starts from the theme's own art in the other appearance.""" + + kind: str + spec: object + from_other: bool = False + + +def to_fixed(value, where: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, float)): + fail(where, "expected a number") + fixed = round(value * ONE) + if not -(1 << 31) <= fixed < 1 << 31: + fail(where, "out of range") + return fixed + + +def rgba(value, where: str) -> bytes: + if not isinstance(value, str) or not RGBA.fullmatch(value): + fail(where, 'expected "#rrggbbaa"') + return bytes.fromhex(value[1:]) + + +def key(color: bytes) -> int: + """A colour as the little-endian u32 the records sort by.""" + return int.from_bytes(color, "little") + + +def is_mask(info: Entry) -> bool: + return info["format"] in bitmaps.MASK_FORMATS + + +def is_565(info: Entry) -> bool: + return info["format"] == bitmaps.RGB565 + + +def same_layout(first: Entry, second: Entry) -> bool: + return all( + first[k] == second[k] + for k in ( + "format", + "width", + "height", + "stride", + "bytes", + "data_offset", + "pixels_offset", + "palette_colors", + ) + ) + + +# Parsing and checks + + +def load(path: Path, index: int, catalog: Catalog, where: str) -> Rule: + """The rule of a derivation file, see `rule`.""" + try: + table = tomllib.loads(path.read_bytes().decode("utf-8")) + except UnicodeDecodeError: + fail(where, "expected UTF-8") + except tomllib.TOMLDecodeError as error: + fail(where, f"invalid TOML: {error}") + return rule(table, index, catalog, where) + + +def rule(table: dict, index: int, catalog: Catalog, where: str) -> Rule: + """The Rule of a rule table: recolor -> sorted colour pairs, alias -> + source index, invert -> None, relight -> fixed-point words. from_other + says the rule starts from the theme's own PNG in the other appearance + instead of the stock bitmap; an alias may then leave `source` out to + reuse its own art unchanged.""" + if not isinstance(table, dict): + fail(where, "expected a table") + kind = table.get("kind") + if kind not in KEYS: + fail(where, f"expected kind = {', '.join(repr(k) for k in KEYS)}") + for name in sorted(table): + if name not in KEYS[kind]: + fail(f"{where}.{name}", "unknown key") + from_other = table.get("from_other", False) + if not isinstance(from_other, bool): + fail(f"{where}.from_other", "expected true or false") + info = catalog.assets[index] + if kind == "recolor": + pairs = read_map(table.get("map"), f"{where}.map") + check_recolor(pairs, info, where) + return Rule(kind, pairs, from_other) + if kind == "alias": + source = table.get("source") + if source is None and from_other: + return Rule(kind, index, True) + if not isinstance(source, str): + fail(f"{where}.source", "expected a catalog name or hex id") + found = catalog.resolve(source, f"{where}.source") + if found != index or not from_other: + check_alias(info, catalog.assets[found], f"{where}.source", from_other) + return Rule(kind, found, from_other) + if kind == "invert": + check_invert(info, where) + return Rule(kind, None, from_other) + words = relight_words(table, where) + check_relight(words, info, where) + return Rule(kind, words, from_other) + + +def read_map(table, where: str) -> list[tuple[bytes, bytes]]: + if not isinstance(table, dict) or not table: + fail(where, 'expected a table of "#rrggbbaa" = "#rrggbbaa"') + pairs = {} + for source, target in table.items(): + at = f'{where}."{source}"' + source, target = rgba(source, at), rgba(target, at) + if source == target: + fail(at, "maps a colour to itself") + if source in pairs: + fail(at, "duplicate colour") + pairs[source] = target + return sorted(pairs.items(), key=lambda pair: key(pair[0])) + + +def check_recolor(pairs: list, info: Entry, where: str) -> None: + if is_mask(info): + fail(where, f"{info['name']} is a mask; it has no colours to recolour") + if len(pairs) > rvtfile.RECOLOR_MAX: + fail(where, f"more than {rvtfile.RECOLOR_MAX} colour pairs") + if len(pairs) > entries(info): + fail(where, f"more colour pairs than {info['name']} has entries") + if is_565(info): + for source, target in pairs: + for color in (source, target): + if not bitmaps.is_565(color): + fail( + f'{where}."#{color.hex()}"', + "RGB565 needs opaque colours with r and b multiples of 8" + " and g a multiple of 4", + ) + + +def describe_layout(info: Entry) -> str: + return f"{info['name']} ({info['format']:#x} {info['width']}x{info['height']})" + + +def alias_fits(target: Entry, source: Entry) -> bool: + """Whether source's pixels can become target's: the same size, neither a + mask. Equal layouts are copied byte for byte; otherwise the pixels are + re-encoded, and a paletted target must hold the source's distinct colours, + which only the iPod can count.""" + return ( + target["id"] != source["id"] + and not is_mask(target) + and not is_mask(source) + and target["width"] == source["width"] + and target["height"] == source["height"] + ) + + +def check_alias( + target: Entry, source: Entry, where: str, from_other: bool = False +) -> None: + """Of the stock bitmaps; with from_other a bitmap may name itself for its + own art in the other appearance, and the compiler does the re-encoding + the iPod otherwise caps at SCRATCH_PIXELS.""" + if target["id"] == source["id"]: + fail(where, f"{target['name']} cannot alias itself without from_other") + if not alias_fits(target, source): + fail( + where, + f"{describe_layout(source)} does not fit {describe_layout(target)}: an" + " alias needs the same size and no mask on either side", + ) + pixels = target["width"] * target["height"] + if not from_other and not same_layout(target, source): + if pixels > rvtfile.SCRATCH_PIXELS: + fail( + where, + f"{describe_layout(source)} must be re-encoded into " + f"{describe_layout(target)}, which the iPod does for at most " + f"{rvtfile.SCRATCH_PIXELS} pixels", + ) + + +def check_aliases(aliases: dict, tinted: dict, names, where) -> None: + """The pack-wide alias rules: at most ALIASES_MAX, no alias of an alias, + no tinted source. aliases maps index -> source index; names(index) and + where(index) give the messages their words.""" + if len(aliases) > rvtfile.ALIASES_MAX: + fail(where(None), f"more than {rvtfile.ALIASES_MAX} aliases") + for index, source in aliases.items(): + if source in aliases: + fail(where(index), f"{names(source)} is an alias itself") + if source in tinted: + fail(where(index), f"{names(source)} is tinted") + + +def check_invert(info: Entry, where: str) -> None: + if is_mask(info): + fail(where, f"{info['name']} is a mask; tint it instead") + + +def relight_words(table: dict, where: str) -> list[int]: + values = dict(RELIGHT_DEFAULTS) + for name in rvtfile.RELIGHT_FIELDS: + if name in table: + values[name] = table[name] + return [ + to_fixed(values[name], f"{where}.{name}") for name in rvtfile.RELIGHT_FIELDS + ] + + +def relight_levels(words: list[int]) -> int: + """Palette entries a relight may need: one per gray between bg_lo and icon_hi.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + return ((w["icon_hi"] + ONE // 2) >> 8) - (w["bg_lo"] >> 8) + 1 + + +def check_relight(words: list[int], info: Entry, where: str) -> None: + """The bounds derive.c enforces, so a rule the compiler accepts is one the + iPod applies.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + if not 0 <= w["t_zero"] < w["t_full"] <= LEVEL_MAX: + fail(where, "expected 0 <= t_zero < t_full <= 255") + for name, bound in RELIGHT_BOUNDS.items(): + if abs(w[name]) > bound: + fail(f"{where}.{name}", f"expected -{bound // ONE} to {bound // ONE}") + if not 0 <= w["bg_lo"] <= w["bg_hi"] <= w["icon_lo"] <= w["icon_hi"] <= LEVEL_MAX: + fail(where, "expected 0 <= bg_lo <= bg_hi <= icon_lo <= icon_hi <= 255") + if info["format"] not in bitmaps.PALETTE_FORMATS: + fail(where, f"relight needs a paletted bitmap; {info['name']} is not") + if info["width"] * info["height"] > rvtfile.SCRATCH_PIXELS: + fail(where, f"{info['name']} has more than {rvtfile.SCRATCH_PIXELS} pixels") + if relight_levels(words) > info["palette_colors"]: + fail( + where, + f"needs {relight_levels(words)} palette entries, " + f"{info['name']} has {info['palette_colors']}", + ) + + +# Record payloads + + +def encode(kind: str, spec) -> bytes: + if kind in rvtfile.PIXEL_KINDS: + return spec + if kind == "recolor": + return struct.pack(" object: + """The spec of a payload after its structural checks; catalog checks are + the caller's.""" + if kind == "recolor": + if ( + len(payload) < 4 + rvtfile.PAIR.size + or (len(payload) - 4) % rvtfile.PAIR.size + ): + fail(where, "recolor payload must be a count and whole colour pairs") + count = struct.unpack_from(" int: + return (77 * red + 150 * green + 29 * blue) >> 8 + + +def div255(value: int) -> int: + """value / 255 rounded, as the iPod's pixel helper does.""" + return (value + 1 + (value >> 8)) >> 8 + + +def tdiv(a: int, b: int) -> int: + """Division truncating toward zero, as C does.""" + q = abs(a) // abs(b) + return q if (a < 0) == (b < 0) else -q + + +def clamp(value: int, low: int, high: int) -> int: + return max(low, min(high, value)) + + +def _palette(info, data): + start = info["data_offset"] + return [ + bytearray(data[start + i * 4 : start + i * 4 + 4]) + for i in range(info["palette_colors"]) + ] + + +def _write_palette(info, data, palette): + start = info["data_offset"] + for i, entry in enumerate(palette): + data[start + i * 4 : start + i * 4 + 4] = entry + + +def _index(info, data, x, y): + at = info["pixels_offset"] + y * info["stride"] + if info["format"] == bitmaps.INDEXED8: + return data[at + x] + return struct.unpack_from(" bytes: + table = dict(pairs) + out = bytearray(data) + for at, size in _each_slot(info, out): + target = table.get(_slot_rgba(out, at, size)) + if target is not None: + _set_slot(out, at, size, target) + return bytes(out) + + +def apply_invert(info: Entry, data: bytes) -> bytes: + out = bytearray(data) + for at, size in _each_slot(info, out): + if size == 4: + if info["palette_colors"] or out[at + 3]: + for i in range(3): + out[at + i] ^= 255 + else: + struct.pack_into( + " int: + """A coverage level with the solid floor applied: full from the floor up, + the floor scaled to the level range of the format.""" + return full if level * FULL >= rvtfile.SOLID_FLOOR * full else level + + +def apply_coverage(info: Entry, data: bytes, coverage: str) -> bytes: + """Tinted stock art as the iPod prepares it: alpha, darkness (alpha scaled + by 255 - luma) or solid coverage, on palette entries, BGRA pixels or mask + levels. Alpha coverage leaves the bytes alone.""" + if coverage == "alpha": + return data + out = bytearray(data) + if is_mask(info): + if coverage != "solid": + raise ValueError(f"{info['name']} is a mask; its coverage is its level") + start, stride = info["pixels_offset"], info["stride"] + for y in range(info["height"]): + row = start + y * stride + for x in range(info["width"]): + if info["format"] == bitmaps.MASK8: + out[row + x] = solid_level(out[row + x], FULL) + else: + at, shift = row + x // 2, 4 if x % 2 == 0 else 0 + level = solid_level(out[at] >> shift & 15, 15) + out[at] = out[at] & ~(15 << shift) | level << shift + return bytes(out) + if is_565(info): + raise ValueError(f"{info['name']} has no coverage") + for at, _ in _each_slot(info, out): + blue, green, red, alpha = out[at : at + 4] + if coverage == "darkness": + out[at + 3] = div255(alpha * (FULL - luma(red, green, blue))) + else: + out[at + 3] = solid_level(alpha, FULL) + return bytes(out) + + +def relight_coverage(words: list[int], info: Entry, data: bytes) -> bytearray: + """t per pixel, 0..FULL, after shadow pruning.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + palette = _palette(info, data) + width, height = info["width"], info["height"] + t = bytearray(width * height) + for y in range(height): + bg = palette[_index(info, data, 0, y)] + for x in range(width): + c = palette[_index(info, data, x, y)] + o = max(abs(c[i] - bg[i]) for i in range(3)) * ONE + if o <= w["t_zero"]: + value = 0 + elif o >= w["t_full"]: + value = FULL + else: + value = (o - w["t_zero"]) * FULL // (w["t_full"] - w["t_zero"]) + t[y * width + x] = value + pruned = bytearray(t) + for y in range(height): + for x in range(width): + if not 0 < t[y * width + x] < FULL: + continue + solid = False + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + nx, ny = x + dx, y + dy + if (dx or dy) and 0 <= nx < width and 0 <= ny < height: + solid |= t[ny * width + nx] == FULL + if not solid: + pruned[y * width + x] = 0 + return pruned + + +def relight_gray(words: list[int], c: bytes, bg: bytes, y: int, t: int) -> int: + """The gray of one pixel: c and bg are BGRA, t is 0..FULL.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + bgd = w["bg_base"] + tdiv( + (luma(bg[2], bg[1], bg[0]) * ONE - w["bg_ref"]) * w["bg_slope"], ONE + ) + bgd = clamp(bgd, w["bg_lo"], w["bg_hi"]) + icon = w["icon_base"] + w["icon_luma"] * luma(c[2], c[1], c[0]) + w["icon_row"] * y + icon = clamp(icon, w["icon_lo"], w["icon_hi"]) + mixed = bgd + ((icon - bgd) * t + FULL // 2) // FULL + return (mixed + ONE // 2) >> 8 + + +def apply_relight(info: Entry, data: bytes, words: list[int]) -> bytes: + out = bytearray(data) + palette = _palette(info, out) + width, height = info["width"], info["height"] + t = relight_coverage(words, info, out) + grays = bytearray(width * height) + for y in range(height): + bg = palette[_index(info, out, 0, y)] + for x in range(width): + c = palette[_index(info, out, x, y)] + grays[y * width + x] = relight_gray(words, c, bg, y, t[y * width + x]) + levels = sorted(set(grays)) + if len(levels) > info["palette_colors"]: + raise ValueError("relight produced more grays than the palette holds") + lookup = {gray: i for i, gray in enumerate(levels)} + _write_palette( + info, + out, + [bytearray((g, g, g, 255)) for g in levels] + + [bytearray(4) for _ in range(info["palette_colors"] - len(levels))], + ) + for y in range(height): + for x in range(width): + _set_index(info, out, x, y, lookup[grays[y * width + x]]) + return bytes(out) + + +def apply_alias(target: Entry, data: bytes, source: Entry, source_data: bytes) -> bytes: + """Target with the source's pixels: a byte copy for equal layouts, else the + pixels re-encoded; a paletted target takes the distinct colours in order of + first appearance and must have room for them.""" + out = bytearray(data) + if same_layout(target, source): + start = target["data_offset"] + out[start:] = source_data[start:] + return bytes(out) + pixels = bitmaps.decode_pixels(source, source_data[source["data_offset"] :]) + width, height = target["width"], target["height"] + palette = {} + for y in range(height): + at = target["pixels_offset"] + y * target["stride"] + for x in range(width): + i = (y * width + x) * 4 + red, green, blue, alpha = pixels[i : i + 4] + if target["palette_colors"]: + color = bytes((blue, green, red, alpha)) + if color not in palette: + if len(palette) == target["palette_colors"]: + raise ValueError( + f"{source['name']} has more colours than " + f"{target['name']}'s palette holds" + ) + palette[color] = len(palette) + _set_index(target, out, x, y, palette[color]) + elif is_565(target): + word = bitmaps.pack_565(red, green, blue) + struct.pack_into(" bytes: + """One record over stock(index), or over `base`, the other appearance's + pixels payload of this bitmap (of the source, for an alias). An alias + without a base reads its source from results when the pack derived or + replaced it, else from stock.""" + info = catalog.assets[index] + data = stock(index) + if base is not None: + if kind == "alias": + source = catalog.assets[spec] + return apply_alias( + info, data, source, stock(spec)[: source["data_offset"]] + base + ) + data = data[: info["data_offset"]] + base + if kind in rvtfile.PIXEL_KINDS: + return data[: info["data_offset"]] + spec + if kind == "recolor": + return apply_recolor(info, data, spec) + if kind == "invert": + return apply_invert(info, data) + if kind == "relight": + return apply_relight(info, data, spec) + source_data = results[spec] if spec in results else stock(spec) + return apply_alias(info, data, catalog.assets[spec], source_data) + + +def apply_pack(catalog: Catalog, stock, records) -> dict[int, bytes]: + """Index -> derived bitmap bytes for a pack's records (index, kind, spec), + in the device's order: everything but aliases ascending, then the aliases. + stock(index) returns a bitmap's stock bytes.""" + results = {} + aliases = [] + for index, kind, spec in records: + if kind == "alias": + aliases.append((index, spec)) + continue + results[index] = apply_record(catalog, stock, index, kind, spec, results) + for index, source in aliases: + results[index] = apply_record(catalog, stock, index, "alias", source, results) + return results diff --git a/themes/rvt/errors.py b/themes/rvt/errors.py new file mode 100644 index 0000000..78176d8 --- /dev/null +++ b/themes/rvt/errors.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The one error the toolchain raises for bad input.""" + + +def fail(where: str, message: str): + """Raise a ValueError that names where in the input the problem is.""" + raise ValueError(f"{where}: {message}" if where else message) diff --git a/themes/rvt/firmware.py b/themes/rvt/firmware.py new file mode 100644 index 0000000..3fbc8f7 --- /dev/null +++ b/themes/rvt/firmware.py @@ -0,0 +1,186 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""A local firmware image as the source of stock bitmaps: previews of derived +art, and derivation files written from an author's PNG when the PNG is a pure +recolour of the stock bitmap. The compiler and inspector never import this +module.""" + +import zlib +from collections import defaultdict + +from rvt import bitmaps, derive, inspector, rvtfile + + +class Firmware: + """Stock bitmaps read at the catalog's offsets; osos.bin or osos-cfw.bin.""" + + def __init__(self, path, catalog): + self.data = path.read_bytes() + self.catalog = catalog + self.checked = {} + + def bitmap(self, index): + info = self.catalog.assets[index] + if index not in self.checked: + data = self.data[info["offset"] : info["offset"] + info["bytes"]] + if len(data) != info["bytes"] or zlib.crc32(data) != info["crc32"]: + raise ValueError( + f"firmware: {info['name']} at {info['offset']:#x} does not carry" + " the catalog checksum" + ) + self.checked[index] = data + return self.checked[index] + + +def render(catalog, firmware, data): + """Every record of an .rvt applied to the stock bitmaps, and every tinted + stock bitmap whose coverage the iPod rewrites (kind `coverage`): + appearance -> name -> {index, kind, address, bytes, crc32, png}, plus + warnings about recolour pairs that match no stock colour.""" + result = {} + warnings = [] + for appearance, pack in inspector.inspect(data, catalog)["appearances"].items(): + records = [ + ( + record["index"], + record["kind"], + record["payload"] + if record["kind"] in rvtfile.PIXEL_KINDS + else record["spec"], + ) + for record in pack["records"] + ] + derived = derive.apply_pack(catalog, firmware.bitmap, records) + for index, tint in pack["tinted"].items(): + if index not in derived and tint["coverage"] != "alpha": + derived[index] = derive.apply_coverage( + catalog.assets[index], firmware.bitmap(index), tint["coverage"] + ) + records.append((index, "coverage", tint["coverage"])) + result[appearance] = {} + for index, kind, spec in records: + info = catalog.assets[index] + bitmap = derived[index] + result[appearance][info["name"]] = { + "index": index, + "kind": kind, + "address": info["address"], + "bytes": info["bytes"], + "crc32": zlib.crc32(bitmap), + "png": bitmaps.write_png( + info["width"], + info["height"], + bitmaps.decode_pixels(info, bitmap[info["data_offset"] :]), + ), + } + if kind == "recolor": + unused = unmatched(info, firmware.bitmap(index), spec) + if unused: + warnings.append( + f"{appearance}/apple/{info['name']}.toml: {len(unused)} of " + f"{len(spec)} pairs match no stock colour: " + + ", ".join(f"#{c.hex()}" for c in unused[:4]) + ) + return result, warnings + + +def stock_colors(info, bitmap): + """The distinct stock colours a recolour can match.""" + pixels = bitmaps.decode_pixels(info, bitmap[info["data_offset"] :]) + if info["palette_colors"]: + start = info["data_offset"] + return { + bytes( + ( + bitmap[start + i * 4 + 2], + bitmap[start + i * 4 + 1], + bitmap[start + i * 4], + bitmap[start + i * 4 + 3], + ) + ) + for i in range(info["palette_colors"]) + } + return {pixels[i : i + 4] for i in range(0, len(pixels), 4)} + + +def unmatched(info, bitmap, pairs): + colors = stock_colors(info, bitmap) + return [source for source, _ in pairs if source not in colors] + + +NOISE = 16 # channel levels an editor's dithering may spread one colour over +STRAY_SHARE = 16 # a stray colour covers at most 1/16 of a stock colour's pixels + + +def quantize_565(color): + red, green, blue, alpha = color + return bytes((red & ~7, green & ~3, blue & ~7, alpha)) + + +def distance(first, second): + """Largest channel difference of two RGBA colours with alpha applied, so + fully transparent colours are equal whatever their RGB.""" + + def visible(color): + return (*(c * color[3] // 255 for c in color[:3]), color[3]) + + return max(abs(a - b) for a, b in zip(visible(first), visible(second))) + + +def to_recolor(catalog, firmware, index, png): + """Colour pairs that turn the stock bitmap into the PNG, and notes about + stray pixels. A stock colour the PNG paints in several colours takes the + most frequent one when the others are within NOISE of it or cover at most + 1/STRAY_SHARE of its pixels; a wider spread is a ValueError naming the + colours. Targets of an RGB565 bitmap are rounded to what the format + stores.""" + info = catalog.assets[index] + width, height, rgba = bitmaps.read_png(png) + if (width, height) != (info["width"], info["height"]): + raise ValueError( + f"expected {info['width']}x{info['height']}, got {width}x{height}" + ) + bitmap = firmware.bitmap(index) + stock = bitmaps.decode_pixels(info, bitmap[info["data_offset"] :]) + targets = defaultdict(lambda: defaultdict(int)) + for i in range(0, len(rgba), 4): + target = rgba[i : i + 4] + if derive.is_565(info): + target = quantize_565(target) + targets[stock[i : i + 4]][target] += 1 + chosen = {} + conflicts = [] + notes = [] + for source, counts in targets.items(): + best = max(counts, key=counts.get) + total = sum(counts.values()) + strays = 0 + for other, count in counts.items(): + if distance(best, other) <= NOISE: + continue + if count * STRAY_SHARE <= total: + strays += count + continue + conflicts.append( + f"#{source.hex()} maps to {len(counts)} colours over {total} pixels" + ) + break + if strays: + notes.append(f"#{source.hex()}: {strays} of {total} pixels ignored") + chosen[source] = best + if conflicts: + raise ValueError( + f"not a pure recolour: {len(conflicts)} stock colours map to several " + "colours\n" + "\n".join(sorted(conflicts)) + ) + pairs = sorted( + ((source, target) for source, target in chosen.items() if source != target), + key=lambda pair: derive.key(pair[0]), + ) + derive.check_recolor(pairs, info, info["name"]) + return pairs, notes + + +def recolor_text(pairs): + lines = ['kind = "recolor"', "", "[map]"] + lines += [f'"#{source.hex()}" = "#{target.hex()}"' for source, target in pairs] + return "\n".join(lines) + "\n" diff --git a/themes/rvt/inspector.py b/themes/rvt/inspector.py new file mode 100644 index 0000000..1a7f3a6 --- /dev/null +++ b/themes/rvt/inspector.py @@ -0,0 +1,205 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Validate an .rvt and describe it, against the catalog when one is given.""" + +from rvt import assets, bitmaps, derive, lz, rvtfile, style +from rvt.catalog import Catalog +from rvt.errors import fail + + +def inspect_pack( + body: bytes, + count: int, + bitmap_count: int, + catalog: Catalog | None, + where: str, + names: dict | None = None, +) -> dict: + """Decoded style, records and extension bitmaps of one pack after checking + every record. A pixels record's `payload` is the bitmap's bytes from its + data offset, decoded for the lz kind when the catalog gives the size; an + extension bitmap's `bmap` is its decoded whole BMap. Messages name the + bitmap when there is a catalog, else its index; extension bitmaps are + named from `names` ((owner hash, asset hash) -> "id/asset") when it knows + them.""" + if catalog is not None and ( + len(body) > catalog.max_body() + rvtfile.EXTENSION_TABLE_MAX_BYTES + ): + fail(where, "pack exceeds the catalog maximum") + try: + decoded = style.decode(body[: rvtfile.STYLE_BYTES]) + except ValueError as error: + fail(where, str(error)) + entries = catalog.assets if catalog is not None else None + + def label(index): + if entries is not None and index < len(entries): + return entries[index]["name"] + return f"bitmap {index}" + + records = [] + at = rvtfile.STYLE_BYTES + previous = -1 + for _ in range(count): + if at + rvtfile.RECORD_BYTES > len(body): + fail(where, "truncated record header") + offset = at + index, word, length = rvtfile.RECORD.unpack_from(body, at) + if index <= previous: + fail(where, "records must be sorted by unique catalog index") + previous = index + if word >= len(rvtfile.KINDS): + fail(where, f"{label(index)} has unknown record kind {word:#x}") + kind = rvtfile.KINDS[word] + info = None + if entries is not None: + if index >= len(entries): + fail(where, f"catalog index {index} is outside the catalog") + info = entries[index] + if kind == "pixels" and length != catalog.payload_bytes(index): + fail(where, f"{label(index)} does not match the native bitmap") + at += rvtfile.RECORD_BYTES + end = at + length + if (not length and kind != "invert") or rvtfile.align(end) > len(body): + fail(where, "truncated record payload") + payload = body[at:end] + record = {"index": index, "kind": kind, "bytes": length, "offset": offset} + if kind in rvtfile.PIXEL_KINDS: + if kind == "pixels_lz" and info is not None: + try: + payload = lz.lz_decode(payload, catalog.payload_bytes(index)) + except ValueError as error: + fail(where, f"{label(index)}: {error}") + if info is not None and not bitmaps.palette_indices_fit(info, payload): + fail(where, f"{label(index)} has an invalid palette index") + record["payload"] = payload + else: + spec = derive.decode(kind, payload, f"{where} {label(index)}") + record["spec"] = spec + if info is not None: + check_derived(kind, spec, index, catalog, f"{where} {label(index)}") + if any(body[end : rvtfile.align(end)]): + fail(where, "record padding must be zero") + records.append(record) + at = rvtfile.align(end) + if catalog is not None and at > catalog.max_body(): + fail(where, "records exceed the catalog maximum") + decoded["extension_bitmaps"], at = assets.decode_table( + body, at, bitmap_count, where + ) + for found in decoded["extension_bitmaps"]: + found["name"] = assets.label(found, names or {}) + if at != len(body): + fail(where, "trailing bytes after the last extension bitmap") + by_index = {record["index"]: record for record in records} + derive.check_aliases( + {r["index"]: r["spec"] for r in records if r["kind"] == "alias"}, + decoded["tinted"], + label, + lambda index: where if index is None else f"{where} alias {label(index)}", + ) + for index, (role, coverage) in decoded["tinted"].items(): + record = by_index.get(index) + if record is not None and record["kind"] not in rvtfile.PIXEL_KINDS: + fail(where, f"tinted {label(index)} has a derived record") + if record is not None and coverage != "alpha": + fail(where, f"tinted {label(index)} takes its coverage from stock art") + if entries is None: + continue + if index >= len(entries): + fail(where, f"tinted catalog index {index} is outside the catalog") + if bitmaps.tint_kind(entries[index]["format"]) is None: + fail(where, f"tinted {label(index)} has no palette or coverage") + if entries is not None: + for record in records: + record["name"] = entries[record["index"]]["name"] + decoded["tinted"] = { + index: {"name": entries[index]["name"], "role": role, "coverage": coverage} + for index, (role, coverage) in decoded["tinted"].items() + } + else: + decoded["tinted"] = { + index: {"role": role, "coverage": coverage} + for index, (role, coverage) in decoded["tinted"].items() + } + decoded["records"] = records + decoded["bytes"] = len(body) + return decoded + + +def check_derived(kind: str, spec, index: int, catalog: Catalog, where: str) -> None: + """Catalog checks of a derived record.""" + info = catalog.assets[index] + if kind == "recolor": + derive.check_recolor(spec, info, where) + elif kind == "alias": + if spec >= len(catalog.assets): + fail(where, f"alias source {spec} is outside the catalog") + derive.check_alias(info, catalog.assets[spec], where) + elif kind == "invert": + derive.check_invert(info, where) + else: + derive.check_relight(spec, info, where) + + +def inspect( + data: bytes, catalog: Catalog | None = None, names: dict | None = None +) -> dict: + """Header fields and one decoded pack per appearance; raises ValueError.""" + header = rvtfile.decode_file(data) + if catalog is not None and header["fingerprint"] != catalog.fingerprint: + fail( + "header", + f"catalog fingerprint {header['fingerprint'].hex()} is not " + f"{catalog.fingerprint.hex()}", + ) + return { + "id": header["id"], + "name": header["name"], + "version": header["version"], + "fingerprint": header["fingerprint"].hex(), + "appearances": { + appearance: inspect_pack( + body, count, bitmap_count, catalog, appearance, names + ) + for appearance, (body, count, bitmap_count) in header["packs"].items() + }, + } + + +def counts(records: list[dict]) -> dict[str, int]: + """Records per kind, kinds with none left out, in rvt_kind order.""" + result = {} + for record in records: + result[record["kind"]] = result.get(record["kind"], 0) + 1 + return {kind: result[kind] for kind in rvtfile.KINDS if kind in result} + + +def describe(result: dict) -> str: + """A readable summary of an inspect() result.""" + lines = [ + f"{result['id']}: {result['name']} (version {result['version']}, " + f"catalog {result['fingerprint']})" + ] + names = {value: key for key, value in rvtfile.FLAGS.items()} + for appearance, pack in result["appearances"].items(): + flags = [names[bit] for bit in names if pack["rendering"] & bit] or ["none"] + lines.append(f"{appearance}:") + for role, value in pack["colors"].items(): + lines.append(f" {role:13} {value}") + lines.append(f" rendering {', '.join(flags)}") + kinds = ", ".join(f"{n} {kind}" for kind, n in counts(pack["records"]).items()) + lines.append( + f" bitmaps {len(pack['records'])} records" + f"{': ' + kinds if kinds else ''}; {len(pack['tinted'])} tinted; " + f"{pack['bytes']:,} bytes" + ) + listed = ", ".join( + f"{asset['name']} {asset['width']}x{asset['height']} {asset['format']}" + + (f" tinted {asset['tint']}" if asset["tint"] else "") + for asset in pack["extension_bitmaps"] + ) + lines.append( + f" extensions {len(pack['extension_bitmaps'])} extension bitmaps" + f"{': ' + listed if listed else ''}" + ) + return "\n".join(lines) diff --git a/themes/rvt/lz.py b/themes/rvt/lz.py new file mode 100644 index 0000000..0a73d69 --- /dev/null +++ b/themes/rvt/lz.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The lz codec of the RepriseOS core: the bit layout in payload/rvx/compression.c, +which the appearance extension decodes on the iPod. A copy of lz_encode and +lz_decode in rvx-sdk/rvx.py; tests/test_bitmaps.py pins the stream of a +known input so the two copies cannot drift apart unnoticed. + +Groups of a flag byte and up to 8 items, bit 0 first. A clear bit is a literal +byte. A set bit is a match of two bytes, LLLLDDDD DDDDDDDD: it copies L + 3 +bytes from D + 1 bytes back in the output; L = 15 adds the following bytes to +the length while they are 255, and the first that is not. The stream carries +no length: a decoder stops when the output is full and the stream must end +there. +""" + +from rvt import rvtfile + +WINDOW = rvtfile.LZ_WINDOW +MIN_MATCH = rvtfile.LZ_MIN_MATCH +CHAIN = 48 # earlier positions tried per match search + + +def lz_match(data, i, positions): + """Longest match for data[i:] among earlier positions in the window.""" + best_length = best_distance = 0 + limit = len(data) - i + for j in reversed(positions[-CHAIN:]): + distance = i - j + if distance > WINDOW: + break + length = MIN_MATCH + while length < limit and data[j + length] == data[i + length]: + length += 1 + if length > best_length: + best_length, best_distance = length, distance + if length == limit: + break + return best_length, best_distance + + +def lz_encode(data): + """The lz stream for `data`: greedy matching with one step of lookahead.""" + heads = {} + items = [] + + def remember(i): + if i + MIN_MATCH <= len(data): + chain = heads.setdefault(data[i : i + MIN_MATCH], []) + chain.append(i) + if len(chain) > 2 * CHAIN: + del chain[:CHAIN] + + def search(i): + if i + MIN_MATCH > len(data): + return 0, 0 + return lz_match(data, i, heads.get(data[i : i + MIN_MATCH], [])) + + i = 0 + pending = search(0) + while i < len(data): + length, distance = pending + if length: + remember(i) + ahead = search(i + 1) + if ahead[0] > length + 1: + items.append(bytes((data[i],))) + i += 1 + pending = ahead + continue + extra = length - MIN_MATCH + nibble = min(extra, 15) + match = bytes((nibble << 4 | (distance - 1) >> 8, (distance - 1) & 0xFF)) + if nibble == 15: + extra -= 15 + match += b"\xff" * (extra // 255) + bytes((extra % 255,)) + items.append(match) + for k in range(i + 1, i + length): + remember(k) + i += length + else: + items.append(bytes((data[i],))) + remember(i) + i += 1 + pending = search(i) + out = bytearray() + for group in range(0, len(items), 8): + chunk = items[group : group + 8] + out.append(sum(1 << bit for bit, item in enumerate(chunk) if len(item) > 1)) + for item in chunk: + out += item + return bytes(out) + + +def lz_decode(stream, size): + """`size` bytes decoded from an lz stream, which must end exactly there.""" + out = bytearray() + at = 0 + try: + while len(out) < size: + flags = stream[at] + at += 1 + for bit in range(8): + if len(out) == size: + break + if not flags >> bit & 1: + out.append(stream[at]) + at += 1 + continue + high, low = stream[at], stream[at + 1] + at += 2 + length = (high >> 4) + MIN_MATCH + distance = ((high & 15) << 8 | low) + 1 + if high >> 4 == 15: + while True: + more = stream[at] + at += 1 + length += more + if more != 255: + break + if distance > len(out) or len(out) + length > size: + raise ValueError("lz match outside the output") + for _ in range(length): + out.append(out[-distance]) + except IndexError: + raise ValueError("lz stream ends early") from None + if at != len(stream): + raise ValueError("lz stream continues past its output") + return bytes(out) diff --git a/themes/rvt/rvtfile.py b/themes/rvt/rvtfile.py new file mode 100644 index 0000000..09f3239 --- /dev/null +++ b/themes/rvt/rvtfile.py @@ -0,0 +1,399 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The .rvt file: header and appearance packs. + +Every constant comes from rvt/data/rvt.h, which the appearance extension +vendors byte for byte, so the two sides cannot drift apart. +""" + +import ast +import re +import struct +import zlib +from importlib.resources import files + +HEADER_FILE = files("rvt") / "data" / "rvt.h" + +ID_PATTERN = re.compile(r"[a-z0-9][a-z0-9_-]{0,30}") + + +def _evaluate(node, names): + if isinstance(node, ast.Expression): + return _evaluate(node.body, names) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.Name): + return names[node.id] + if isinstance(node, ast.BinOp): + left, right = _evaluate(node.left, names), _evaluate(node.right, names) + operators = { + ast.Add: lambda: left + right, + ast.Sub: lambda: left - right, + ast.Mult: lambda: left * right, + ast.LShift: lambda: left << right, + ast.BitOr: lambda: left | right, + } + return operators[type(node.op)]() + raise ValueError(f"unsupported expression in rvt.h: {ast.dump(node)}") + + +def parse(text: str) -> tuple[dict[str, int], dict[str, list[str]], dict[str, int]]: + """Defines (name -> int), enums (name -> ordered member names) and enum + member values (member -> int) of rvt.h. + + Enum members count from zero, or from the integer a member is given; a + define may use them, so the enums are read first.""" + text = re.sub(r"/\*.*?\*/", "", text, flags=re.S) + enums = {} + names = {} + for name, body in re.findall(r"enum\s+(\w+)\s*\{(.*?)\}\s*;", text, re.S): + members = [] + value = 0 + for item in body.split(","): + if not item.strip(): + continue + match = re.fullmatch(r"\s*(RVT_\w+)\s*(?:=\s*(\d+)\s*)?", item) + if not match: + raise ValueError(f"enum {name} has a member this parser cannot read") + member, given = match.groups() + if given is not None: + value = int(given) + members.append(member) + names[member] = value + value += 1 + enums[name] = members + defines = {} + for name, value in re.findall(r"^#define[ \t]+(RVT_\w+)[ \t]+(.+)$", text, re.M): + expression = re.sub(r"\b(0[xX][0-9a-fA-F]+|\d+)[uU]?\b", r"\1", value) + defines[name] = _evaluate(ast.parse(expression, mode="eval"), names) + names[name] = defines[name] + values = {member: names[member] for members in enums.values() for member in members} + return defines, enums, values + + +DEFINES, ENUMS, VALUES = parse(HEADER_FILE.read_text()) + + +def _names(enum, prefix): + """Lower-case member names without the prefix; the last member is the count.""" + members = ENUMS[enum][:-1] + return tuple(m.removeprefix(prefix).lower() for m in members) + + +def _values(enum, prefix): + """Lower-case member name -> value, for enums that do not count from zero.""" + return {m.removeprefix(prefix).lower(): VALUES[m] for m in ENUMS[enum][:-1]} + + +MAGIC = DEFINES["RVT_MAGIC"].to_bytes(4, "little") +VERSION = DEFINES["RVT_VERSION"] +HEADER_BYTES = DEFINES["RVT_HEADER_BYTES"] +FINGERPRINT_BYTES = DEFINES["RVT_FINGERPRINT_BYTES"] +ID_BYTES = DEFINES["RVT_ID_BYTES"] +NAME_BYTES = DEFINES["RVT_NAME_BYTES"] +PACK_HEADER_BYTES = DEFINES["RVT_PACK_HEADER_BYTES"] +APPEARANCES = { + "light": DEFINES["RVT_APPEARANCE_LIGHT"], + "dark": DEFINES["RVT_APPEARANCE_DARK"], +} +FLAGS = { + "flat_selection": DEFINES["RVT_FLAG_FLAT_SELECTION"], + "menu_covers_off": DEFINES["RVT_FLAG_MENU_COVERS_OFF"], + "flat_now_playing": DEFINES["RVT_FLAG_FLAT_NOW_PLAYING"], + "flat_icons": DEFINES["RVT_FLAG_FLAT_ICONS"], +} +TINT_NONE = DEFINES["RVT_TINT_NONE"] +TINT_ROLE = DEFINES["RVT_TINT_ROLE"] +TINT_DARKNESS = DEFINES["RVT_TINT_DARKNESS"] +TINT_SOLID = DEFINES["RVT_TINT_SOLID"] +SOLID_FLOOR = DEFINES["RVT_SOLID_FLOOR"] +CATALOG_MAX = DEFINES["RVT_CATALOG_MAX"] +STYLE_COLORS = DEFINES["RVT_STYLE_COLORS"] +STYLE_FLAGS = DEFINES["RVT_STYLE_FLAGS"] +STYLE_PALETTES = DEFINES["RVT_STYLE_PALETTES"] +STYLE_TINTS = DEFINES["RVT_STYLE_TINTS"] +STYLE_BYTES = DEFINES["RVT_STYLE_BYTES"] +RECORD_BYTES = DEFINES["RVT_RECORD_BYTES"] +RELIGHT_BYTES = DEFINES["RVT_RELIGHT_BYTES"] +SCRATCH_BYTES = DEFINES["RVT_SCRATCH_BYTES"] +RECOLOR_MAX = DEFINES["RVT_RECOLOR_MAX"] +SCRATCH_PIXELS = DEFINES["RVT_SCRATCH_PIXELS"] +ALIASES_MAX = DEFINES["RVT_ALIASES_MAX"] +EXTENSION_BITMAP_BYTES = DEFINES["RVT_EXTENSION_BITMAP_BYTES"] +# Extension bitmap kinds, name -> the kind word. +EXTENSION_KINDS = _values("rvt_extension_kind", "RVT_EXTENSION_") +BMAP_HEADER_BYTES = DEFINES["RVT_BMAP_HEADER_BYTES"] +EXTENSION_BITMAPS_MAX = DEFINES["RVT_EXTENSION_BITMAPS_MAX"] +EXTENSION_BITMAP_MAX_BYTES = DEFINES["RVT_EXTENSION_BITMAP_MAX_BYTES"] +# The largest extension bitmap table: every bitmap at the cap, padded. +EXTENSION_TABLE_MAX_BYTES = EXTENSION_BITMAPS_MAX * ( + EXTENSION_BITMAP_BYTES + EXTENSION_BITMAP_MAX_BYTES +) +# A Settings icon's rows: Mask8, stride 80, 121 rows. +MENU_ROWS_BYTES = 80 * 121 +ROLES = _names("rvt_role", "RVT_ROLE_") +ACCENTS = _names("rvt_accent", "RVT_ACCENT_") +ACCENT_SLOTS = _names("rvt_accent_slot", "RVT_SLOT_") +KINDS = _names("rvt_kind", "RVT_KIND_") +PIXEL_KINDS = ("pixels", "pixels_lz") +LZ_WINDOW = DEFINES["RVT_LZ_WINDOW"] +LZ_MIN_MATCH = DEFINES["RVT_LZ_MIN_MATCH"] +RELIGHT_FIELDS = _names("rvt_relight", "RVT_RELIGHT_") + +# The header fields in RVT_HEADER_* order; the rest up to HEADER_BYTES is zero. +HEADER = struct.Struct(f"<4sHH{FINGERPRINT_BYTES}sIIIIII{ID_BYTES}s{NAME_BYTES}s") +HEADER_OFFSETS = ( + DEFINES["RVT_HEADER_MAGIC"], + DEFINES["RVT_HEADER_VERSION"], + DEFINES["RVT_HEADER_HEADER_BYTES"], + DEFINES["RVT_HEADER_FINGERPRINT"], + DEFINES["RVT_HEADER_APPEARANCES"], + DEFINES["RVT_HEADER_LIGHT_OFFSET"], + DEFINES["RVT_HEADER_LIGHT_BYTES"], + DEFINES["RVT_HEADER_DARK_OFFSET"], + DEFINES["RVT_HEADER_DARK_BYTES"], + DEFINES["RVT_HEADER_CRC"], + DEFINES["RVT_HEADER_ID"], + DEFINES["RVT_HEADER_NAME"], +) +CRC_OFFSET = DEFINES["RVT_HEADER_CRC"] +# A pack header in RVT_PACK_* order: body bytes, record count, body CRC, +# extension bitmap count. +PACK = struct.Struct(" tuple[int, ...]: + """Where each field of a little-endian layout starts; a counted `s` is + one field, a counted number is that many.""" + offsets = [] + at = 0 + for count, code in re.findall(r"(\d*)([a-zA-Z])", layout.format): + fields = [count + code] if code == "s" else [code] * int(count or 1) + for field in fields: + offsets.append(at) + at += struct.calcsize(field) + return tuple(offsets) + + +if ( + MAGIC != b"RVT0" + or HEADER.size > HEADER_BYTES + or _field_offsets(HEADER) != HEADER_OFFSETS + or PACK.size != PACK_HEADER_BYTES + or _field_offsets(PACK) != PACK_OFFSETS + or RECORD.size != RECORD_BYTES + or EXTENSION_BITMAP.size != EXTENSION_BITMAP_BYTES + or EXTENSION_KINDS != {"bitmap": 1, "bitmap_lz": 2} + or BMAP_HEADER_BYTES != 28 + or EXTENSION_BITMAP_MAX_BYTES < BMAP_HEADER_BYTES + MENU_ROWS_BYTES + or STYLE_COLORS != 0 + or STYLE_FLAGS != len(ROLES) * 4 + or STYLE_PALETTES != STYLE_FLAGS + 4 + or STYLE_TINTS != STYLE_PALETTES + len(ACCENTS) * len(ACCENT_SLOTS) * 4 + or STYLE_BYTES != STYLE_TINTS + CATALOG_MAX + or RELIGHT.size != RELIGHT_BYTES + or KINDS != ("pixels", "recolor", "alias", "invert", "relight", "pixels_lz") + or LZ_WINDOW != 4096 + or LZ_MIN_MATCH != 3 + or TINT_ROLE + len(ROLES) > 16 + or TINT_DARKNESS < 16 + or TINT_SOLID < 16 + or TINT_DARKNESS & TINT_SOLID + or not 0 < SOLID_FLOOR <= 255 + or RECOLOR_MAX * PAIR.size > SCRATCH_BYTES + or SCRATCH_PIXELS + 256 > SCRATCH_BYTES +): + raise ValueError("rvt/data/rvt.h does not match the layout this module encodes") + + +def align(size: int) -> int: + return size + -size % 4 + + +def check_id(value: str, where: str = "id") -> str: + if not isinstance(value, str) or not ID_PATTERN.fullmatch(value): + raise ValueError(f"{where}: expected [a-z0-9][a-z0-9_-]{{0,30}}") + return value + + +def check_text(value: str, where: str, limit: int) -> str: + """A non-empty string without control characters of at most `limit` + UTF-8 bytes.""" + if not isinstance(value, str) or not value: + raise ValueError(f"{where}: expected a non-empty string") + if any(ord(c) < 32 or ord(c) == 127 for c in value): + raise ValueError(f"{where}: control characters are not allowed") + if len(value.encode()) > limit: + raise ValueError(f"{where}: exceeds {limit} UTF-8 bytes") + return value + + +def check_name(value: str, where: str = "name") -> str: + return check_text(value, where, NAME_BYTES - 1) + + +def fnv1a(data: bytes) -> int: + """FNV-1a, the hash the core keys extension ids and asset names with.""" + value = 2166136261 + for byte in data: + value = (value ^ byte) * 16777619 & 0xFFFFFFFF + return value + + +def encode_pack(body: bytes, count: int, bitmaps: int = 0) -> bytes: + """Pack header and body; the body is the style prefix, the padded records + and the `bitmaps` extension bitmaps after them.""" + if len(body) % 4: + raise ValueError("pack body is not a multiple of 4 bytes") + return PACK.pack(len(body), count, zlib.crc32(body), bitmaps) + body + + +def encode_file( + fingerprint: bytes, + identifier: str, + name: str, + packs: dict[str, tuple[bytes, int, int]], +) -> bytes: + """A complete .rvt: packs maps an appearance name to (body, record count, + extension bitmap count).""" + if len(fingerprint) != FINGERPRINT_BYTES: + raise ValueError(f"fingerprint must be {FINGERPRINT_BYTES} bytes") + check_id(identifier) + check_name(name) + if not packs: + raise ValueError("a theme needs a light or dark appearance") + mask = 0 + placement = {} + data = bytearray() + offset = HEADER_BYTES + for appearance, bit in APPEARANCES.items(): + if appearance not in packs: + continue + pack = encode_pack(*packs[appearance]) + mask |= bit + placement[appearance] = (offset, len(pack)) + data += pack + offset += len(pack) + header = bytearray(HEADER_BYTES) + HEADER.pack_into( + header, + 0, + MAGIC, + VERSION, + HEADER_BYTES, + fingerprint, + mask, + *placement.get("light", (0, 0)), + *placement.get("dark", (0, 0)), + 0, + identifier.encode("ascii"), + name.encode(), + ) + struct.pack_into(" dict: + if len(data) < HEADER_BYTES: + raise ValueError(f"header: expected {HEADER_BYTES} bytes, got {len(data)}") + ( + magic, + version, + header_bytes, + fingerprint, + mask, + light_offset, + light_bytes, + dark_offset, + dark_bytes, + crc, + raw_id, + raw_name, + ) = HEADER.unpack_from(data) + if magic != MAGIC: + raise ValueError(f"header: bad magic {magic!r}") + if version != VERSION: + raise ValueError(f"header: version {version} is not {VERSION}") + # A larger header is a later layout's; the packs start where it says. + if header_bytes < HEADER_BYTES or header_bytes % 4 or header_bytes > len(data): + raise ValueError(f"header: expected at least {HEADER_BYTES} header bytes") + sealed = bytearray(data[:HEADER_BYTES]) + struct.pack_into(" tuple[bytes, int, int]: + """(body, record count, extension bitmap count) of the pack at offset, + after checking its CRC.""" + body_bytes, count, crc, bitmaps = PACK.unpack_from(data, offset) + if body_bytes != size - PACK_HEADER_BYTES or body_bytes < STYLE_BYTES: + raise ValueError(f"pack at {offset}: body of {body_bytes} bytes does not fit") + body = bytes(data[offset + PACK_HEADER_BYTES : offset + size]) + if zlib.crc32(body) != crc: + raise ValueError(f"pack at {offset}: CRC-32 mismatch") + if bitmaps > EXTENSION_BITMAPS_MAX: + raise ValueError(f"pack at {offset}: {bitmaps} extension bitmaps") + return body, count, bitmaps + + +def decode_file(data: bytes) -> dict: + """Header fields plus packs as appearance -> (body, record count, extension + bitmap count).""" + header = decode_header(data) + header["packs"] = { + appearance: decode_pack(data, offset, size) + for appearance, (offset, size) in header["packs"].items() + } + return header diff --git a/themes/rvt/style.py b/themes/rvt/style.py new file mode 100644 index 0000000..e2797ce --- /dev/null +++ b/themes/rvt/style.py @@ -0,0 +1,189 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The style prefix of an appearance pack: colour roles, rendering flags, one +palette per named accent and one tint byte per catalog bitmap.""" + +import struct + +from rvt import rvtfile + +ROLES = rvtfile.ROLES +ACCENTS = rvtfile.ACCENTS +# The accent palette slots are the TOML keys of the roles they replace. +ACCENT_SLOTS = rvtfile.ACCENT_SLOTS +if any(slot not in ROLES for slot in ACCENT_SLOTS): + raise ValueError("accent slots do not name roles of rvt.h") +STYLE_BYTES = rvtfile.STYLE_BYTES +FLAGS_OFFSET = rvtfile.STYLE_FLAGS +PALETTE_OFFSET = rvtfile.STYLE_PALETTES +TINT_OFFSET = rvtfile.STYLE_TINTS + +ALL_FLAGS = sum(rvtfile.FLAGS.values()) +# The lowest contrast of a text and background pair that passes. +CONTRAST_MINIMUM = 4.5 + +# Classic light and dark. The dark palette comes from RepriseOS payload/dark_mode.c +# (01c89f6) by lgreitis and Alex Ball (alexballvideos-netizen). +COLOR_DEFAULTS = { + key: dict(zip(ROLES, (f"#{value}" for value in values.split()))) + for key, values in { + "light": "ffffff 202020 236cc5 3185d0 ffffff 236cc5 7e8183 3185d0", + "dark": "181818 e8e8e8 00a1ff 00a1ff ffffff 00a1ff 383838 00a1ff", + }.items() +} +# Built-in accents: light fill, light text, dark fill, dark text. Blue is Classic. +ACCENT_BUILTIN = dict( + zip( + ACCENTS, + ( + ("236cc5", "3185d0", "00a1ff", "00a1ff"), + ("8944ab", "8944ab", "964ebc", "da8fff"), + ("c41e56", "c41e56", "ce2660", "ff6491"), + ("d02028", "d02028", "d42830", "ff6961"), + ("b84800", "b84800", "be4c00", "ff9f0a"), + ("1e803a", "1e803a", "20863e", "30d158"), + ("007378", "007378", "00787d", "40d2d7"), + ("826500", "826500", "846700", "ffd60a"), + ("5c6066", "5c6066", "64686e", "bec2c8"), + ), + ) +) + + +def rgb(color): + return bytes.fromhex(color.removeprefix("#")) + + +def accent_builtin(name: str, appearance: str) -> tuple[str, str]: + """Built-in fill and text of an accent for one appearance.""" + builtin = ACCENT_BUILTIN[name] + fill, text = builtin[2:] if appearance == "dark" else builtin[:2] + return "#" + fill, "#" + text + + +def accent_palette(name: str, appearance: str, colors: dict[str, str]) -> dict: + """The palette an accent starts from: the built-in fill for accent_fill and + selection, the built-in text for accent_text and icon_tint, and the + appearance's own on_accent.""" + fill, text = accent_builtin(name, appearance) + return dict(zip(ACCENT_SLOTS, (fill, text, fill, colors["on_accent"], text))) + + +def contrast(first: str, second: str) -> float: + """WCAG contrast ratio of two #rrggbb colours.""" + + def luminance(color): + linear = [ + v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 + for v in (c / 255 for c in rgb(color)) + ] + return sum(v * w for v, w in zip(linear, (0.2126, 0.7152, 0.0722))) + + low, high = sorted((luminance(first), luminance(second))) + return (high + 0.05) / (low + 0.05) + + +CONTRAST_PAIRS = ( + ("text", "background"), + ("accent_text", "background"), + ("on_accent", "selection"), + ("on_accent", "accent_fill"), +) + + +# The accent entry of the theme's own colours, as Settings names it. +THEME_DEFAULT = "Theme Default" + + +def contrast_report(colors: dict, palettes: dict) -> list[dict]: + """Contrast of each text/background pair for Theme Default and every accent.""" + report = [] + for name, palette in [(THEME_DEFAULT, {}), *palettes.items()]: + resolved = colors | palette + for foreground, background in CONTRAST_PAIRS: + ratio = contrast(resolved[foreground], resolved[background]) + report.append( + { + "accent": name, + "foreground": foreground, + "background": background, + "ratio": round(ratio, 3), + "passes": ratio >= CONTRAST_MINIMUM, + } + ) + return report + + +COVERAGES = ("alpha", "darkness", "solid") +COVERAGE_BITS = { + "alpha": 0, + "darkness": rvtfile.TINT_DARKNESS, + "solid": rvtfile.TINT_SOLID, +} + + +def tint_byte(role: str, coverage: str = "alpha") -> int: + return rvtfile.TINT_ROLE + ROLES.index(role) | COVERAGE_BITS[coverage] + + +def encode(colors: dict, flags: int, palettes: dict, tinted: dict) -> bytes: + """The style prefix. tinted maps a catalog index to a tint role or a + (role, coverage) pair.""" + if flags & ~ALL_FLAGS: + raise ValueError(f"unknown rendering flags {flags:#x}") + tints = bytearray(rvtfile.CATALOG_MAX) + for index, tint in tinted.items(): + if not 0 <= index < rvtfile.CATALOG_MAX: + raise ValueError( + f"tinted catalog index {index} exceeds {rvtfile.CATALOG_MAX}" + ) + role, coverage = tint if isinstance(tint, tuple) else (tint, "alpha") + tints[index] = tint_byte(role, coverage) + return ( + b"".join(rgb(colors[role]) + b"\xff" for role in ROLES) + + struct.pack(" dict: + """Colours, flags, accent palettes and tinted bitmaps of a prefix.""" + if len(data) != STYLE_BYTES: + raise ValueError(f"style prefix must be {STYLE_BYTES} bytes") + if any(data[i] != 255 for i in range(3, TINT_OFFSET, 4) if i != FLAGS_OFFSET + 3): + raise ValueError("style colours must be opaque") + flags = struct.unpack_from(" None: + if not isinstance(table, dict): + fail(where, "expected a table") + for key in sorted(table): + at = f"{where}.{key}" if where else key + if key in UNSUPPORTED: + fail(at, f"unsupported capability: {UNSUPPORTED[key]} are not themeable") + if key not in allowed: + fail(at, "unknown key") + + +def color(value, where: str) -> str: + if not isinstance(value, str) or not COLOR.fullmatch(value): + fail(where, 'expected "#rrggbb"') + return value.lower() + + +def load(folder: Path) -> dict: + """The validated document; its appearance tables are resolved by the + functions below.""" + path = Path(folder) / "theme.toml" + if not path.is_file(): + fail(str(path), "not found") + if path.stat().st_size > TOML_LIMIT: + fail(path.name, f"exceeds {TOML_LIMIT:,} bytes") + try: + theme = tomllib.loads(path.read_bytes().decode("utf-8")) + except UnicodeDecodeError: + fail(path.name, "expected UTF-8") + except tomllib.TOMLDecodeError as error: + fail(path.name, f"invalid TOML: {error}") + check_keys(theme, THEME_KEYS, "") + for key in ("schema", "id", "name"): + if key not in theme: + fail(key, "required") + if type(theme["schema"]) is not int or theme["schema"] != SCHEMA: + fail("schema", f"unsupported schema {theme['schema']!r}; expected {SCHEMA}") + rvtfile.check_id(theme["id"]) + rvtfile.check_name(theme["name"]) + for key in ("author", "version"): + if key in theme: + rvtfile.check_text(theme[key], key, TEXT_LIMIT) + if not any(key in theme for key in rvtfile.APPEARANCES): + fail("", "declare [light], [dark] or both") + for key in rvtfile.APPEARANCES: + if key in theme: + check_keys(theme[key], APPEARANCE_KEYS, key) + return theme + + +# Colours, accents and rendering + + +def resolve_style(appearance: str, table: dict) -> tuple[tuple, dict, list[str]]: + """(colors, flags, palettes) of an appearance, its report, and warnings + about text and background pairs the theme itself colours that fall below + style.CONTRAST_MINIMUM; a pair no accent changes is warned about once. + icon_tint left out follows accent_text.""" + where = appearance + colors = table.get("colors", {}) + check_keys(colors, set(style.ROLES), f"{where}.colors") + resolved = dict(style.COLOR_DEFAULTS[appearance]) + for role, value in colors.items(): + resolved[role] = color(value, f"{where}.colors.{role}") + if "icon_tint" not in colors: + resolved["icon_tint"] = resolved["accent_text"] + + overrides = table.get("accents", {}) + check_keys(overrides, set(style.ACCENTS), f"{where}.accents") + palettes = { + name: accent_palette(name, appearance, resolved, overrides.get(name), where) + for name in style.ACCENTS + } + + flags = 0 + covers = table.get(MENU_COVERS_DEFAULT, True) + if not isinstance(covers, bool): + fail(f"{where}.{MENU_COVERS_DEFAULT}", "expected true or false") + if not covers: + flags |= rvtfile.FLAGS["menu_covers_off"] + rendering = table.get("rendering", {}) + if not isinstance(rendering, dict): + fail(f"{where}.rendering", "expected a table") + for key in sorted(rendering): + at = f"{where}.rendering.{key}" + if key not in RENDERING: + fail(at, "unknown key") + if not isinstance(rendering[key], bool): + fail(at, "expected true or false") + if rendering[key]: + flags |= rvtfile.FLAGS[RENDERING[key]] + + report = { + "contrast": style.contrast_report(resolved, palettes), + "accents_builtin": [name for name in style.ACCENTS if name not in overrides], + } + warnings = [] + for pair in report["contrast"]: + sides = {pair["foreground"], pair["background"]} + if pair["accent"] != style.THEME_DEFAULT and not sides & set( + style.ACCENT_SLOTS + ): + continue + owned = pair["accent"] in overrides or any( + pair[side] in colors for side in ("foreground", "background") + ) + if owned and not pair["passes"]: + warnings.append( + f"{where}: {pair['foreground']} on {pair['background']} is " + f"{pair['ratio']}:1 with accent {pair['accent']}; " + f"{style.CONTRAST_MINIMUM}:1 is the minimum" + ) + return (resolved, flags, palettes), report, warnings + + +def accent_palette(name, appearance, colors, override, where) -> dict: + """One accent's palette: the built-in fill and text with the appearance's + on_accent, then the override: one colour for fill, text, selection and + icon tint, a table with `accent` and optionally `on_accent`, or a table of + the five palette slots.""" + palette = style.accent_palette(name, appearance, colors) + at = f"{where}.accents.{name}" + if override is None: + return palette + if isinstance(override, str): + override = {"accent": override} + if not isinstance(override, dict): + fail(at, 'expected "#rrggbb" or a table') + if "accent" in override: + check_keys(override, {"accent", "on_accent"}, at) + one = color(override["accent"], f"{at}.accent") + palette.update(accent_fill=one, accent_text=one, selection=one, icon_tint=one) + if "on_accent" in override: + palette["on_accent"] = color(override["on_accent"], f"{at}.on_accent") + return palette + check_keys(override, set(style.ACCENT_SLOTS), at) + for slot, value in override.items(): + palette[slot] = color(value, f"{at}.{slot}") + return palette + + +# Tints and rules + + +def is_glob(pattern: str) -> bool: + return bool(GLOB_CHARS & set(pattern)) + + +def matching(pattern: str, catalog: Catalog, where: str) -> list[int]: + """Catalog indices a name, hex id or glob stands for; a name that is not + in the catalog is an error, a glob may match nothing.""" + if not isinstance(pattern, str): + fail(where, "expected a catalog name, hex id or glob") + if not is_glob(pattern): + return [catalog.resolve(pattern, where)] + return [ + index + for index, asset in enumerate(catalog.assets) + if fnmatch.fnmatchcase(asset["name"], pattern) + ] + + +def extension_key(pattern: str, where: str) -> tuple[str, str] | None: + """(id, asset) when a tint entry names an extension bitmap as `id/asset` + (the core's as `reprise/asset`); None for a catalog name, hex id or glob, + which never contain a slash.""" + if not isinstance(pattern, str) or "/" not in pattern: + return None + identifier, _, asset = pattern.partition("/") + if not assets.ID_PATTERN.fullmatch( + identifier + ) or not assets.ASSET_PATTERN.fullmatch(asset): + fail(where, f"{pattern!r} is not an extension bitmap /") + return identifier, asset + + +def resolve_tints( + table: dict, appearance: str, catalog: Catalog +) -> tuple[dict[int, tuple[str, str]], dict[tuple[str, str], str], list[str]]: + """Catalog index -> (role, coverage) and extension (id, asset) -> role from + [.tint], and warnings about globs that match nothing: role = + [names or globs] per role, a `darkness_coverage` list naming tinted bitmaps + whose coverage is their darkness and a `solid_coverage` list naming those + whose coverage is full from the floor up. An extension bitmap is named + `id/asset` and takes its coverage from its PNG's alpha only.""" + where = f"{appearance}.tint" + tints = table.get("tint", {}) + if not isinstance(tints, dict): + fail(where, "expected a table") + tinted: dict[int, tuple[str, str]] = {} + extensions: dict[tuple[str, str], str] = {} + warnings: list[str] = [] + for role, patterns in tints.items(): + at = f"{where}.{role}" + if role not in COVERAGE_LISTS and role not in style.ROLES: + fail(at, f"expected one of {', '.join((*style.ROLES, *COVERAGE_LISTS))}") + if not isinstance(patterns, list): + fail(at, "expected a list of catalog names, hex ids or globs") + for pattern in patterns: + key = extension_key(pattern, at) + if key is not None: + if role in COVERAGE_LISTS: + fail(at, f"{pattern} takes its coverage from its PNG's alpha") + if key in extensions: + fail(at, f"{pattern} is already tinted {extensions[key]}") + extensions[key] = role + continue + found = matching(pattern, catalog, at) + if not found: + warnings.append(f"{at}: {pattern!r} matches no catalog bitmap") + if role in COVERAGE_LISTS: + continue + for index in found: + info = catalog.assets[index] + if index in tinted: + fail(at, f"{info['name']} is already tinted {tinted[index][0]}") + if bitmaps.tint_kind(info["format"]) is None: + fail( + at, + f"{info['name']} cannot be tinted: it has no palette or coverage", + ) + tinted[index] = (role, "alpha") + for key, coverage in COVERAGE_LISTS.items(): + at = f"{where}.{key}" + for pattern in tints.get(key, []): + for index in matching(pattern, catalog, at): + name = catalog.assets[index]["name"] + if index not in tinted: + fail(at, f"{name} has no tint role") + if tinted[index][1] == coverage: + fail(at, f"{name} is listed twice") + if tinted[index][1] != "alpha": + fail( + at, f"{name} already takes its coverage from {tinted[index][1]}" + ) + tinted[index] = (tinted[index][0], coverage) + return tinted, extensions, warnings + + +def resolve_rules( + table: dict, appearance: str, catalog: Catalog, sources: dict +) -> tuple[dict[int, derive.Rule], dict[int, str], list[str]]: + """Catalog index -> Rule from [.derive], index -> the rule's + pattern, and one note per rule saying how many bitmaps it matched. A rule + matches by name, hex id or glob; it may not match nothing, a bitmap in + `sources` (one with a PNG or a per-file TOML) or a bitmap of another + rule.""" + where = f"{appearance}.derive" + rules = table.get("derive", {}) + if not isinstance(rules, dict): + fail(where, "expected a table of rules") + resolved: dict[int, derive.Rule] = {} + owner: dict[int, str] = {} + notes = [] + for pattern, spec in rules.items(): + at = f"{where}.{pattern!r}" + found = matching(pattern, catalog, at) + if not found: + fail(at, "matches no catalog bitmap") + for index in found: + name = catalog.assets[index]["name"] + if index in sources: + fail(at, f"matches {name}, which has {sources[index][1].name}") + if index in owner: + fail(at, f"matches {name}, which {owner[index]!r} matches too") + owner[index] = pattern + for index in found: + resolved[index] = derive.rule(spec, index, catalog, at) + notes.append( + f"{at} matches {len(found)} bitmap{'s' if len(found) != 1 else ''}" + ) + return resolved, owner, notes + + +# rvt new + + +def template(identifier: str, name: str) -> str: + """A theme.toml with every role and option present as a comment.""" + out = [ + "schema = 1", + f'id = "{identifier}"', + f'name = "{name}"', + '# author = ""', + '# version = "1.0"', + "", + "# Art goes beside this file: /apple/.png or", + "# .toml for Apple's bitmaps, /extensions//", + "# .png for the bitmaps of extensions (rvt catalog list", + "# --extensions), /reprise/.png for the core's own.", + ] + for appearance in rvtfile.APPEARANCES: + defaults = style.COLOR_DEFAULTS[appearance] + out += [ + "", + f"# {appearance.capitalize()} appearance; drop the table to leave it out.", + f"[{appearance}]", + f"# {MENU_COVERS_DEFAULT} = true # Menu Covers until the listener chooses", + "", + "# Roles left out keep the Classic colours shown.", + f"[{appearance}.colors]", + ] + out += [ + f'# {role} = "{value}"' + + (" # left out, it follows accent_text" if role == "icon_tint" else "") + for role, value in defaults.items() + ] + out += [ + "", + "# Accents the listener can pick. One colour fills accent_fill,", + "# accent_text, selection and icon_tint; on_accent comes from the", + "# colours above. Accents left out use the built-in fill and text.", + f"[{appearance}.accents]", + ] + for accent in style.ACCENTS: + fill, _ = style.accent_builtin(accent, appearance) + out.append(f'# {accent} = "{fill}"') + out += [ + '# yellow = { accent = "#ffcc00", on_accent = "#000000" }', + "", + f"[{appearance}.rendering]", + "# flat_selection = false # true: the selection bar is one flat colour", + "# flat_now_playing = false # true: face-on cover art, no reflection", + "# flat_icons = false # true: extension icons this theme does not", + "# # replace lose their reflection", + "", + "# Bitmaps the iPod draws in one live colour, by role; globs allowed.", + f"[{appearance}.tint]", + ] + out += [f"# {role} = []" for role in style.ROLES] + out += [ + f"# {DARKNESS} = [] # coverage from darkness, stock art only", + f"# {SOLID} = [] # coverage full from the floor up, stock art only", + "", + "# Rules that derive bitmaps from the stock art or, with", + "# from_other = true, from this theme's own PNG in the other appearance.", + f"[{appearance}.derive]", + '# "Settings_Brightness_Image" = { kind = "invert" }', + '# "Clock_*_Image_*" = { kind = "alias", from_other = true }', + ] + return "\n".join(out) + "\n" diff --git a/themes/tests/fixtures.py b/themes/tests/fixtures.py new file mode 100644 index 0000000..8665eda --- /dev/null +++ b/themes/tests/fixtures.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Synthetic PNGs, native bitmaps and a six-asset catalog for the tests.""" + +import struct +import sys +import zlib +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from rvt import catalog as catalog_module # noqa: E402 +from rvt.bitmaps import describe # noqa: E402 + + +def png(width, height, color_type, rows): + """A PNG from raw scanlines (each prefixed with its filter byte).""" + + def chunk(kind, body): + return ( + struct.pack(">I", len(body)) + + kind + + body + + struct.pack(">I", zlib.crc32(kind + body)) + ) + + header = struct.pack(">IIBBBBB", width, height, 8, color_type, 0, 0, 0) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(rows)) + + chunk(b"IEND", b"") + ) + + +def rgba_png(width, height, rgba): + rows = b"".join( + b"\0" + rgba[y * width * 4 : (y + 1) * width * 4] for y in range(height) + ) + return png(width, height, 6, rows) + + +def indexed(): + pixels = bytes([0, 1, 0, 1]) + body = struct.pack("> 8 & 255, 7, 255) for i in range(count)] + + +def record(identifier, asset, width, height, menu=False, fmt=None, colors=0): + if menu: + fmt, colors, stride, depth = assets.MASK8, 0, assets.MENU_STRIDE, 8 + else: + fmt = assets.INDEXED8 if fmt is None else fmt + depth = 8 if fmt == assets.INDEXED8 else 32 + stride = (width * depth // 8 + 3) & ~3 + return { + "id": identifier, + "asset": asset, + "menu": menu, + "format": fmt, + "width": width, + "height": height, + "stride": stride, + "depth": depth, + "palette_colors": colors, + "bytes": assets.HEADER.size + + (4 + 4 * colors if colors else 0) + + stride * height, + "preload": "optional" if menu else "never", + } + + +def table(*entries): + """An extension bitmap table from (owner, asset, kind, payload[, decoded + [, stored[, tint]]]); decoded defaults to a Settings icon, stored to the + payload, tint to none.""" + data = b"" + for owner, name, kind, payload, *rest in entries: + decoded = rest[0] if rest else MENU_BYTES + stored = rest[1] if len(rest) > 1 else len(payload) + tint = rest[2] if len(rest) > 2 else 0 + data += rvtfile.EXTENSION_BITMAP.pack(owner, name, kind, stored, decoded, tint) + data += payload + bytes(-len(data + payload) % 4) + return data + + +class EncodingTests(unittest.TestCase): + def test_encoder_is_the_sdk_copy(self): + sdk = ( + Path(os.environ.get("SDK", ROOT.parents[1] / "osos-lab" / "rvx-sdk")) + / "bitmap.py" + ) + if not sdk.is_file(): + self.skipTest("set SDK to the RVX SDK checkout") + self.assertEqual( + (ROOT / "rvt" / "data" / "bitmap.py").read_bytes(), sdk.read_bytes() + ) + + def test_committed_catalog_matches_the_build(self): + built = ROOT.parent / "build" / "assets.json" + if not built.is_file(): + self.skipTest("run make first; build/assets.json is missing") + self.assertEqual(extensions_catalog.convert(built), assets.CATALOG.read_text()) + + def test_hashes_match_the_core(self): + self.assertEqual(assets.owner_hash("reprise"), 0xB3F4A34D) + self.assertEqual(rvtfile.fnv1a(COLLIDING[0].encode()), 0x2C91828D) + self.assertEqual( + rvtfile.fnv1a(COLLIDING[0].encode()), rvtfile.fnv1a(COLLIDING[1].encode()) + ) + + def test_mask_follows_encode_mask(self): + translucent = b"".join(bytes((9, 9, 9, a)) for a in (0, 128, 255)) * ( + W * H // 3 + ) + bmap = assets.bitmap.encode_mask(W, H, translucent) + self.assertEqual(len(bmap), MENU_BYTES) + self.assertEqual(bmap[:28], assets.MENU_HEADER) + self.assertEqual( + assets.HEADER.unpack(bmap[:28]), (8, 0, 80, 8, 0, 0, 121, 78, 9680) + ) + self.assertTrue(assets.is_menu(bmap)) + self.assertEqual(bmap[28:31], bytes((0, 128, 255))) + self.assertEqual(bmap[28 + 78 : 28 + 80], bytes(2)) + gray = b"".join(bytes((v, v, v, 255)) for v in (0, 7, 200)) * (W * H // 3) + self.assertEqual( + assets.bitmap.encode_mask(W, H, gray)[28:31], bytes((0, 7, 200)) + ) + # Opaque art with an alpha hole uses alpha even where it is grayscale. + mixed = bytearray(gray) + mixed[3] = 0 + self.assertEqual( + assets.bitmap.encode_mask(W, H, bytes(mixed))[28:31], bytes((0, 255, 255)) + ) + with self.assertRaisesRegex(ValueError, "a pane icon is coverage"): + assets.bitmap.encode_mask(W, H, bytes((200, 10, 10, 255)) * (W * H)) + with self.assertRaisesRegex(ValueError, "a pane icon is 78 x 121, not 4 x 1"): + assets.bitmap.encode_mask(4, 1, bytes(16)) + + def test_picture_follows_encode_bmap(self): + # Five pixels of three colours: Indexed8, a palette of three, stride 8. + colors = [(1, 2, 3, 255), (4, 5, 6, 128), (1, 2, 3, 255), (7, 8, 9, 0)] + rgba = b"".join(bytes(c) for c in colors) + bytes((4, 5, 6, 128)) + bmap = assets.bitmap.encode_bmap(5, 1, rgba) + fmt, _, stride, depth, top, left, bottom, right, payload = assets.HEADER.unpack( + bmap[:28] + ) + self.assertEqual( + (fmt, stride, depth, top, left, bottom, right), (0x64, 8, 8, 0, 0, 1, 5) + ) + self.assertEqual(payload, 4 + 12 + 8) + self.assertEqual(len(bmap), 28 + payload) + self.assertEqual(struct.unpack_from("/", + tint % '"Third/logo"', + extensions, + ) + self.rejects( + r"light.tint.icon_tint: third/logo has no light/extensions/third/logo.png", + tint % '"third/logo"', + extensions, + ) + self.rejects( + r"light.tint.text: third/logo is already tinted icon_tint", + THEME + '[light.tint]\nicon_tint = ["third/logo"]\ntext = ["third/logo"]\n', + extensions, + **{"light/extensions/third/logo.png": colored}, + ) + self.rejects( + r"light.tint.solid_coverage: third/logo takes its coverage from its PNG", + THEME + + '[light.tint]\nicon_tint = ["third/logo"]\nsolid_coverage = ["third/logo"]\n', + extensions, + **{"light/extensions/third/logo.png": colored}, + ) + self.rejects( + r"light/extensions/third/logo.png: tinted art must be grayscale or carry alpha coverage", + tint % '"third/logo"', + extensions, + **{"light/extensions/third/logo.png": colored}, + ) + self.rejects( + r"light/extensions/appearance/settings-moon.png: a Settings icon is drawn " + r"in the icon tint already; no tint role", + tint % '"appearance/settings-moon"', + extensions, + **{MOON_PNG: icon_png()}, + ) + + def test_unknown_asset_compiles_only_as_a_settings_icon(self): + build = self.theme( + FLAT, + **{ + "light/extensions/third-party/settings-x.png": icon_png(), + MOON_PNG: icon_png(), + }, + ) + self.assertEqual( + build.warnings, + [ + "light/extensions/third-party/settings-x.png: not in the extension " + "asset catalog, compiled as a Settings icon; docs/extension-bitmaps.md " + "lists the first-party bitmaps, --extension adds others" + ], + ) + self.assertEqual( + len(build.inspection["appearances"]["light"]["extension_bitmaps"]), 2 + ) + self.rejects( + r"light/extensions/third-party/logo.png: 4x1 is not a menu bitmap and the " + r"asset is not in the extension asset catalog; pass --extension", + **{"light/extensions/third-party/logo.png": rgba_png(4, 1, bytes(16))}, + ) + + def test_art_outside_its_folder_is_rejected(self): + self.rejects( + r"light/extensions/reprise: reprise is the core's id; its bitmaps go in " + r"light/reprise/", + **{"light/extensions/reprise/settings-info.png": icon_png()}, + ) + self.rejects( + r"light/stray.png: catalog art goes in light/apple/, extension bitmaps " + r"in light/extensions//, the core's in light/reprise/", + **{"light/stray.png": icon_png()}, + ) + self.rejects( + r"dark: has art but theme.toml declares no \[dark\]", + **{"dark/reprise/settings-info.png": icon_png()}, + ) + self.rejects( + "light/reprise/Extensions.png: expected .png", + **{"light/reprise/Extensions.png": icon_png()}, + ) + + def test_reflection_warning_follows_flat_icons_for_menu_bitmaps(self): + files = {MOON_PNG: icon_png()} + build = self.theme(**files) + self.assertEqual( + build.warnings, + [ + f"{MOON_PNG}: no reflection below the art; draw one or set " + "flat_icons = true in [light.rendering]" + ], + ) + build = self.theme(THEME + "[light.rendering]\nflat_icons = true\n", **files) + self.assertEqual(build.warnings, []) + reflected = icon_png(rows=list(range(12, 63)) + [100]) + build = self.theme(**{MOON_PNG: reflected}) + self.assertEqual(build.warnings, []) + extensions = {("third", "logo"): record("third", "logo", 4, 1)} + build = self.theme( + THEME + "[light]\n", + extensions, + **{"light/extensions/third/logo.png": rgba_png(4, 1, bytes(16))}, + ) + self.assertEqual(build.warnings, []) + + def test_bad_names_and_colliding_hashes_are_rejected(self): + cases = { + "light/extensions/Appearance: expected an extension id": { + "light/extensions/Appearance/settings-moon.png": icon_png() + }, + "light/extensions/1st: expected an extension id": { + "light/extensions/1st/x.png": icon_png() + }, + "light/extensions/" + "a" * 33 + ": expected an extension id": { + "light/extensions/" + "a" * 33 + "/x.png": icon_png() + }, + "light/extensions/stray.png: expected a folder named after an extension id": { + "light/extensions/stray.png": icon_png() + }, + "light/extensions/appearance/Settings-Moon.png: expected .png": { + "light/extensions/appearance/Settings-Moon.png": icon_png() + }, + "light/extensions/appearance/settings-moon.toml: expected .png": { + "light/extensions/appearance/settings-moon.toml": b"x" + }, + "light/extensions/appearance/" + "a" * 32 + ".png: expected .png": { + "light/extensions/appearance/" + "a" * 32 + ".png": icon_png() + }, + f"{MOON_PNG}: a pane icon is 78 x 121, not 4 x 1": { + MOON_PNG: rgba_png(4, 1, bytes(16)) + }, + f"{MOON_PNG}: a pane icon is coverage": { + MOON_PNG: rgba_png(W, H, bytes((200, 10, 10, 255)) * (W * H)) + }, + f"{MOON_PNG}: truncated PNG": {MOON_PNG: icon_png()[:-20]}, + "extensions/appearance/e6apaa.png: its hashes collide with " + "extensions/appearance/7yzlaa.png": { + f"light/extensions/appearance/{COLLIDING[0]}.png": icon_png(), + f"dark/extensions/appearance/{COLLIDING[1]}.png": icon_png(), + }, + } + for pattern, files in cases.items(): + with self.subTest(pattern): + self.rejects(pattern, THEME + "[light]\n[dark]\n", **files) + # The same name in both appearances is two bitmaps, not a collision. + build = self.theme( + THEME + "[light]\n[dark]\n", + **{MOON_PNG: icon_png(), MOON_PNG.replace("light", "dark"): icon_png()}, + ) + self.assertEqual( + len(build.inspection["appearances"]["dark"]["extension_bitmaps"]), 1 + ) + self.theme(THEME + "[light]\n[dark]\n") + (self.root / "light" / "extensions" / "appearance").mkdir(parents=True) + outside = self.root.parent / "settings-moon.png" + outside.write_bytes(icon_png()) + (self.root / MOON_PNG).symlink_to(outside) + with self.assertRaisesRegex(ValueError, f"{MOON_PNG}: must be a file inside"): + compile_theme(self.catalog, self.root) + + def test_more_than_the_cap_of_extension_bitmaps_is_rejected(self): + files = { + f"light/extensions/appearance/icon-{i:02}.png": icon_png() + for i in range(65) + } + self.rejects("65 extension bitmaps exceed 64", THEME + "[light]\n", **files) + + +class CliTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.catalog = self.root / "catalog.json" + self.catalog.write_text(json.dumps(fixtures.catalog_document())) + self.previous = os.getcwd() + os.chdir(self.root) + + def tearDown(self): + os.chdir(self.previous) + self.directory.cleanup() + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + status = 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + cli.main([str(a) for a in args]) + except SystemExit as exit_: + status = exit_.code + return status, out.getvalue(), err.getvalue() + + def test_catalog_list_and_show(self): + status, out, _ = self.run_cli("catalog", "list", "--extensions") + self.assertEqual(status, 0) + lines = out.splitlines() + self.assertEqual(lines[0], "appearance settings-accent 78x121 mask8 0 menu") + self.assertEqual(len(lines), len(assets.load_catalog())) + _, out, _ = self.run_cli( + "catalog", "list", "--extensions", "--group", "reprise" + ) + self.assertEqual( + out, + "reprise settings-info 78x121 mask8 0 menu\n", + ) + _, out, _ = self.run_cli( + "catalog", "list", "--extensions", "--format", "indexed8" + ) + self.assertEqual(out, "") + status, _, err = self.run_cli( + "catalog", "list", "--extensions", "--format", "gif" + ) + self.assertEqual(status, 1) + self.assertIn("--format: expected one of mask8, indexed8, bgra8888", err) + _, out, _ = self.run_cli("catalog", "show", "reprise/settings-info") + self.assertIn("id reprise\nasset settings-info\nmenu true\nformat 0x8\n", out) + self.assertIn( + "format_name mask8\nowner_hash 0xb3f4a34d\nasset_hash 0x24c0da6b", out + ) + status, _, err = self.run_cli("catalog", "show", "nope/x") + self.assertEqual(status, 1) + self.assertIn("'nope/x' is not in the extension asset catalog", err) + addition = self.root / "assets.json" + addition.write_text(json.dumps(record("third", "logo", 4, 1)) + "\n") + _, out, _ = self.run_cli( + "catalog", + "list", + "--extensions", + "--group", + "third", + "--extension", + addition, + ) + self.assertEqual(out, "third logo 4x1 indexed8 0 bitmap\n") + _, out, _ = self.run_cli( + "catalog", "show", "third/logo", "--extension", addition + ) + self.assertIn("menu false\n", out) + + def test_compile_and_inspect_with_an_extension(self): + folder = self.root / "src" + png = folder / "light" / "extensions" / "third" / "logo.png" + png.parent.mkdir(parents=True) + png.write_bytes(rgba_png(4, 1, bytes(range(16)))) + (folder / "theme.toml").write_text(THEME + "[light]\n") + status, _, err = self.run_cli("check", folder, "--catalog", self.catalog) + self.assertEqual(status, 1) + self.assertIn("pass --extension", err) + addition = self.root / "assets.json" + addition.write_text(json.dumps(record("third", "logo", 4, 1)) + "\n") + status, out, err = self.run_cli( + "compile", folder, "--catalog", self.catalog, "--extension", addition + ) + self.assertEqual((status, err), (0, "")) + self.assertIn("1 extension bitmaps", out) + rvt = self.root / "dist" / "test" / "test.rvt" + _, out, _ = self.run_cli("inspect", rvt, "--catalog", self.catalog) + self.assertIn("1 extension bitmaps: 0x", out) + _, out, _ = self.run_cli( + "inspect", rvt, "--catalog", self.catalog, "--extension", addition + ) + self.assertIn("1 extension bitmaps: third/logo 4x1 indexed8", out) + _, out, _ = self.run_cli( + "inspect", rvt, "--catalog", self.catalog, "--extension", addition, "--json" + ) + self.assertEqual( + json.loads(out)["appearances"]["light"]["extension_bitmaps"][0]["palette"], + 4, + ) + + +class PageTests(unittest.TestCase): + def test_page_is_the_generator_output(self): + page = ROOT / "docs" / "extension-bitmaps.md" + self.assertEqual(page.read_text(), extension_bitmaps_doc.current()) + + def test_vendored_catalog_is_the_converter_output(self): + source = Path(str(assets.CATALOG)) + self.assertEqual(source.read_text(), extensions_catalog.convert(source)) + with tempfile.TemporaryDirectory() as name: + unsorted = Path(name) / "assets.json" + unsorted.write_text( + json.dumps(record("z", "a", 1, 1)) + + "\n" + + json.dumps(record("a", "b", 1, 1)) + + "\n" + + json.dumps(record("a", "a", 1, 1)) + + "\n" + ) + out = Path(name) / "extensions.json" + with contextlib.redirect_stdout(io.StringIO()): + extensions_catalog.main([str(unsorted), "--out", str(out)]) + self.assertEqual( + [json.loads(line)["asset"] for line in out.read_text().splitlines()], + ["a", "b", "a"], + ) + unsorted.write_text((json.dumps(record("a", "a", 1, 1)) + "\n") * 2) + with self.assertRaisesRegex(ValueError, "a/a is listed twice"): + extensions_catalog.convert(unsorted) + + def test_page_rows(self): + text = extension_bitmaps_doc.page( + { + ("third", "logo"): record("third", "logo", 4, 1, colors=3), + ("reprise", "settings-info"): record( + "reprise", "settings-info", 78, 121, True + ), + } + ) + self.assertIn( + "| `reprise` | `settings-info` | 78x121 | mask8 | - | yes |", text + ) + self.assertIn("| `third` | `logo` | 4x1 | indexed8 | 3 | no |", text) + self.assertLess(text.index("`reprise`"), text.index("`third`")) + with tempfile.TemporaryDirectory() as name: + out = Path(name) / "page.md" + with contextlib.redirect_stdout(io.StringIO()): + extension_bitmaps_doc.main(["--out", str(out)]) + self.assertEqual(out.read_text(), extension_bitmaps_doc.current()) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_bitmaps.py b/themes/tests/test_bitmaps.py new file mode 100644 index 0000000..a20ff8f --- /dev/null +++ b/themes/tests/test_bitmaps.py @@ -0,0 +1,278 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""PNG reading, palette fitting, the native pixel codecs and the lz codec.""" + +import os +import struct +import unittest +import zlib +from pathlib import Path + +import fixtures +from rvt import bitmaps, lz + +# The SDK checkout the extensions build uses (the root Makefile default). +SDK = Path( + os.environ.get("SDK", Path(__file__).resolve().parents[3] / "osos-lab" / "rvx-sdk") +) +RVX = SDK / "rvx.py" + + +def chunk(kind, body): + return ( + struct.pack(">I", len(body)) + + kind + + body + + struct.pack(">I", zlib.crc32(kind + body)) + ) + + +def make_png(width, height, depth, color_type, rows, extra=(), idat_parts=1): + """A PNG from filtered scanlines; `extra` chunks go between IHDR and IDAT + and the compressed rows are split over idat_parts IDAT chunks.""" + header = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0) + data = zlib.compress(rows) + size = -(-len(data) // idat_parts) + parts = [data[i : i + size] for i in range(0, len(data), size)] + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + b"".join(chunk(kind, body) for kind, body in extra) + + b"".join(chunk(b"IDAT", part) for part in parts) + + chunk(b"IEND", b"") + ) + + +def filtered(raw_rows, stride, bpp, filter_type): + """Scanlines of 8-bit samples encoded with one PNG filter.""" + out = bytearray() + previous = bytes(stride) + for row in raw_rows: + out.append(filter_type) + for x in range(stride): + a = row[x - bpp] if x >= bpp else 0 + b = previous[x] + c = previous[x - bpp] if x >= bpp else 0 + predictor = (0, a, b, (a + b) // 2, bitmaps.paeth(a, b, c))[filter_type] + out.append((row[x] - predictor) & 255) + previous = row + return bytes(out) + + +def packed_indices(indices, depth): + """One scanline of palette indices packed MSB first, with its filter byte.""" + bits = "".join(f"{i:0{depth}b}" for i in indices) + bits += "0" * (-len(bits) % 8) + return b"\0" + int(bits, 2).to_bytes(len(bits) // 8, "big") + + +class PngTests(unittest.TestCase): + RGBA = bytes([10, 20, 30, 255, 40, 50, 60, 128, 70, 80, 90, 0, 1, 2, 3, 4]) + + def test_palette_depths(self): + palette = bytes([255, 0, 0, 0, 255, 0, 0, 0, 255, 9, 9, 9]) + alpha = bytes([255, 128]) + for depth, indices in ((1, [0, 1, 1, 0]), (2, [0, 1, 2, 3]), (4, [3, 2, 1, 0])): + with self.subTest(depth=depth): + png = make_png( + 4, + 1, + depth, + 3, + packed_indices(indices, depth), + [(b"PLTE", palette), (b"tRNS", alpha)], + ) + width, height, rgba = bitmaps.read_png(png) + self.assertEqual((width, height), (4, 1)) + expected = b"".join( + palette[i * 3 : i * 3 + 3] + bytes([alpha[i] if i < 2 else 255]) + for i in indices + ) + self.assertEqual(rgba, expected) + + def test_gray_and_rgb_with_transparent_colour(self): + gray = make_png(3, 1, 8, 0, b"\0\x10\x20\x30", [(b"tRNS", b"\0\x20")]) + self.assertEqual( + bitmaps.read_png(gray)[2], + bytes([16, 16, 16, 255, 32, 32, 32, 0, 48, 48, 48, 255]), + ) + gray_alpha = make_png(2, 1, 8, 4, b"\0\x10\x80\x20\xff") + self.assertEqual( + bitmaps.read_png(gray_alpha)[2], bytes([16, 16, 16, 128, 32, 32, 32, 255]) + ) + rgb = make_png( + 2, + 1, + 8, + 2, + b"\0\x01\x02\x03\x04\x05\x06", + [(b"tRNS", b"\0\x04\0\x05\0\x06")], + ) + self.assertEqual(bitmaps.read_png(rgb)[2], bytes([1, 2, 3, 255, 4, 5, 6, 0])) + + def test_filters_and_multiple_idat_chunks(self): + rows = [self.RGBA[:8], self.RGBA[8:]] + for filter_type in range(5): + with self.subTest(filter=filter_type): + png = make_png( + 2, 2, 8, 6, filtered(rows, 8, 4, filter_type), idat_parts=3 + ) + self.assertEqual(bitmaps.read_png(png), (2, 2, self.RGBA)) + + def test_malformed_png_is_rejected(self): + good = make_png(2, 2, 8, 6, filtered([self.RGBA[:8], self.RGBA[8:]], 8, 4, 0)) + cases = { + "not a PNG": good[1:], + "truncated PNG": good[:-20], + "truncated PNG ": good[:40], + "checksum": good[:-5] + bytes([good[-5] ^ 1]) + good[-4:], + "interlaced": make_png(1, 1, 8, 6, bytes(5))[:28] + + b"\1" + + make_png(1, 1, 8, 6, bytes(5))[29:], + "pixel length": make_png(2, 2, 8, 6, bytes(9)), + "row filter": make_png(1, 1, 8, 6, b"\5\0\0\0\0"), + "exceeds palette": make_png(1, 1, 8, 3, b"\0\3", [(b"PLTE", bytes(3))]), + "16-bit": make_png(1, 1, 16, 6, bytes(9)), + } + for name, bad in cases.items(): + with self.subTest(name), self.assertRaises(ValueError): + bitmaps.read_png(bad) + + def test_write_png_round_trip(self): + png = bitmaps.write_png(2, 2, self.RGBA) + self.assertEqual(bitmaps.read_png(png), (2, 2, self.RGBA)) + + +class PaletteTests(unittest.TestCase): + def test_fit_palette_reserves_transparent_and_keeps_fitting_art(self): + rgba = b"".join(bytes((v, v, v, 255)) for v in range(16)) + bytes(4) + self.assertEqual(bitmaps.fit_palette(rgba, 17), rgba) + fitted = bitmaps.fit_palette(rgba, 4) + colors = {fitted[i : i + 4] for i in range(0, len(fitted), 4)} + self.assertEqual(len(colors), 4) + self.assertIn(bytes(4), colors) + self.assertEqual(fitted[-4:], bytes(4)) + self.assertEqual(bitmaps.distinct(rgba), 17) + + def test_fit_levels_reduces_coverage_alone(self): + levels = bytes(range(0, 256, 5)) + fitted = bitmaps.fit_levels(levels, 8) + self.assertEqual(len(set(fitted)), 8) + self.assertEqual(fitted[0], 0) + self.assertEqual( + bitmaps.fit_levels(bytes([0, 100, 200]), 3), bytes([0, 100, 200]) + ) + # The tint colour does not change which levels survive. + for tint in ("#ff0000", "#00ff00"): + tinted = bitmaps.tinted_pixels(fitted, tint) + self.assertEqual(tinted[3::4], fitted) + + +class CodecTests(unittest.TestCase): + def setUp(self): + self.catalog = fixtures.catalog() + + def round_trip(self, name, rgba): + info = self.catalog.assets[self.catalog.resolve(name, "x")] + payload = bitmaps.encode_pixels(info, info["width"], info["height"], rgba) + self.assertEqual(len(payload), info["bytes"] - info["data_offset"]) + self.assertTrue(bitmaps.palette_indices_fit(info, payload)) + return payload, bitmaps.decode_pixels(info, payload) + + def test_each_format_round_trips(self): + two = bytes([10, 20, 30, 255, 40, 50, 60, 128]) * 2 + payload, back = self.round_trip("Alpha", two) + self.assertEqual(back, two) + self.assertEqual(payload[:8], bytes([30, 20, 10, 255, 60, 50, 40, 128])) + eight = b"".join(bytes((i, i * 2, i * 3, 255)) for i in range(8)) + bytes(16) + eight = eight[:32] + eight[:16] + _, back = self.round_trip("Iota", eight) + self.assertEqual(back, eight) + bgra = bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) + payload, back = self.round_trip("Beta", bgra) + self.assertEqual(back, bgra) + self.assertEqual(payload[:4], bytes([3, 2, 1, 4])) + rgb = bytes([248, 252, 248, 255, 8, 4, 8, 255]) * 2 + payload, back = self.round_trip("Zeta", rgb) + self.assertEqual(back, rgb) + self.assertEqual(struct.unpack_from(" About |\n" + ) + self.assertEqual(appears, {"Alpha": "Settings > About"}) + document = fixtures.catalog_document()["bitmaps"] + text = bitmaps_doc.page(document, appears) + self.assertIn("## Other", text) + self.assertEqual( + bitmaps_doc.group_of("No_Content_Music_Preview_Image"), "No_Content" + ) + self.assertEqual(bitmaps_doc.group_of("Notes_Preview_Image"), "Notes") + self.assertIn("| `Alpha` | 4x1 | indexed8 | 2 | yes | Settings > About |", text) + self.assertIn("| `Delta` | 4x1 | mask8 | - | yes | |", text) + self.assertIn("| `Zeta` | 4x1 | rgb565 | - | no | |", text) + + def test_lookup_and_validation(self): + loaded = fixtures.catalog() + self.assertEqual(loaded.resolve("Alpha", "x"), 0) + self.assertEqual(loaded.resolve("0x20", "x"), 1) + # The largest payload is a relight's 48 bytes, except Iota (8 palette + # entries, a 68-byte recolour) and Kappa (12 pixels, 100 bytes). + self.assertEqual(loaded.max_body(), 856 + 11 * 12 + 9 * 48 + 68 + 100) + with self.assertRaisesRegex(ValueError, "not a catalog bitmap name"): + loaded.resolve("Nope", "x") + with self.assertRaisesRegex(ValueError, "0x00000099 is not a catalog bitmap"): + loaded.resolve("0x99", "x") + with self.assertRaisesRegex(ValueError, "ambiguous; use one of 0x00000020"): + fixtures.catalog(duplicate_name=True).resolve("Beta", "x") + document = fixtures.catalog_document() + document["bitmaps"][0]["address"] += 1 + with self.assertRaisesRegex(ValueError, "address"): + catalog.Catalog(document) + document = fixtures.catalog_document() + document["fingerprint"] = "00" * 8 + with self.assertRaisesRegex(ValueError, "stored fingerprint"): + catalog.Catalog(document) + document = fixtures.catalog_document() + document["bitmaps"][1]["id"] = 0x10 + with self.assertRaisesRegex(ValueError, "duplicate bitmap id"): + catalog.Catalog(document) + document = fixtures.catalog_document() + del document["runtime_base"] + with self.assertRaisesRegex(ValueError, "runtime_base"): + catalog.Catalog(document) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_cli.py b/themes/tests/test_cli.py new file mode 100644 index 0000000..26f76fa --- /dev/null +++ b/themes/tests/test_cli.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""rvt new, check, compile --strict, catalog, and report determinism.""" + +import contextlib +import io +import json +import os +import tempfile +import unittest +from pathlib import Path + +import fixtures +from fixtures import rgba_png +from rvt import cli + +THEME = 'schema = 1\nid = "test"\nname = "Test"\n' + + +class CliTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.catalog = self.root / "catalog.json" + self.catalog.write_text(json.dumps(fixtures.catalog_document())) + self.previous = os.getcwd() + os.chdir(self.root) + + def tearDown(self): + os.chdir(self.previous) + self.directory.cleanup() + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + status = 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + cli.main([str(a) for a in args]) + except SystemExit as exit_: + status = exit_.code + return status, out.getvalue(), err.getvalue() + + def theme(self, toml=THEME, **files): + folder = self.root / "src" + folder.mkdir(exist_ok=True) + (folder / "theme.toml").write_text(toml) + for path, content in files.items(): + target = folder / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + return folder + + def test_new_writes_a_compilable_folder(self): + status, out, _ = self.run_cli("new", "mine", "--name", "Mine") + self.assertEqual(status, 0) + self.assertIn("Wrote mine/theme.toml", out) + for appearance in ("light", "dark"): + for sub in ("apple", "reprise", "extensions"): + self.assertTrue((self.root / "mine" / appearance / sub).is_dir()) + status, out, _ = self.run_cli("check", "mine", "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertIn("mine.rvt:", out) + status, _, err = self.run_cli("new", "mine") + self.assertEqual((status, err), (1, "mine exists\n")) + status, _, err = self.run_cli("new", "classic") + self.assertIn("reserved", err) + status, _, err = self.run_cli("new", "Bad") + self.assertIn("id: expected", err) + + def test_check_prints_warnings_and_sizes_without_writing(self): + rainbow = rgba_png(4, 1, bytes(range(16))) + folder = self.theme(THEME + "[light]\n", **{"light/apple/Alpha.png": rainbow}) + status, out, err = self.run_cli("check", folder, "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertIn( + "warning: light/apple/Alpha.png: 4 colours reduced to the 2 of its palette", + err, + ) + self.assertIn("light: 1 bitmaps (1 pixels, 0 derived)", out) + self.assertFalse((self.root / "dist").exists()) + status, _, err = self.run_cli( + "check", folder, "--catalog", self.catalog, "--strict" + ) + self.assertEqual(status, 1) + self.assertIn("1 warnings with --strict", err) + status, out, err = self.run_cli( + "compile", folder, "--catalog", self.catalog, "--strict" + ) + self.assertEqual(status, 1) + self.assertFalse((self.root / "dist").exists()) + status, out, err = self.run_cli("compile", folder, "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertIn("reduced", err) + report = json.loads((self.root / "dist/test/report.json").read_text()) + self.assertEqual( + report["appearances"]["light"]["palette_reduced"], + [{"name": "Alpha", "colors": 4, "palette": 2}], + ) + + def test_report_and_file_are_deterministic(self): + folder = self.theme( + THEME + '[light.tint]\ntext = ["Delta"]\n[dark]\n', + **{"light/apple/Alpha.png": rgba_png(4, 1, bytes(16))}, + ) + outputs = [] + for out in ("one", "two"): + self.run_cli("compile", folder, "--catalog", self.catalog, "--out", out) + outputs.append( + ( + (self.root / out / "test/test.rvt").read_bytes(), + (self.root / out / "test/report.json").read_text(), + ) + ) + self.assertEqual(outputs[0], outputs[1]) + report = json.loads(outputs[0][1]) + self.assertEqual( + sorted(report["appearances"]["light"]), + [ + "accents_builtin", + "bytes", + "contrast", + "extension_bitmaps", + "extension_tinted", + "palette_reduced", + "records", + ], + ) + + def test_catalog_list_and_show(self): + status, out, _ = self.run_cli("catalog", "list", "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertEqual(out.splitlines()[0], "Alpha 4x1 indexed8 2 tintable") + self.assertEqual(len(out.splitlines()), 11) + _, out, _ = self.run_cli( + "catalog", "list", "--catalog", self.catalog, "--group", "Z" + ) + self.assertEqual(out, "Zeta 4x1 rgb565 0 untintable\n") + _, out, _ = self.run_cli( + "catalog", "list", "--catalog", self.catalog, "--format", "mask4" + ) + self.assertEqual(out, "Epsilon 4x1 mask4 0 tintable\n") + status, _, err = self.run_cli( + "catalog", "list", "--catalog", self.catalog, "--format", "gif" + ) + self.assertEqual(status, 1) + _, out, _ = self.run_cli("catalog", "show", "Iota", "--catalog", self.catalog) + self.assertIn("index 8\nid 0x90\nname Iota\n", out) + self.assertIn("format 0x65\n", out) + self.assertIn("format_name indexed16", out) + _, out, _ = self.run_cli("catalog", "show", "0x90", "--catalog", self.catalog) + self.assertIn("name Iota", out) + status, _, err = self.run_cli( + "catalog", "show", "Nope", "--catalog", self.catalog + ) + self.assertEqual(status, 1) + self.assertIn("not a catalog bitmap name", err) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_compile.py b/themes/tests/test_compile.py new file mode 100644 index 0000000..dca0b1f --- /dev/null +++ b/themes/tests/test_compile.py @@ -0,0 +1,467 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Compiling theme folders, the inspector and the rejection cases.""" + +import contextlib +import io +import json +import os +import shutil +import struct +import tempfile +import unittest +from pathlib import Path + +import fixtures +from fixtures import rgba_png +from rvt import cli, inspector, lz, rvtfile, style +from rvt.compiler import compile_theme, write + +THEME = 'schema = 1\nid = "test"\nname = "Test"\n' + + +class CompileTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) / "src" + self.root.mkdir() + self.catalog = fixtures.catalog() + rgba = bytes([10, 20, 30, 50, 40, 50, 60, 70]) * 2 + self.art = { + "alpha": rgba_png(4, 1, rgba), + "beta": rgba_png(3, 1, bytes(range(12))), + # Coverage art: an alpha ramp over a colour, and an opaque gray ramp. + "alpha-ramp": rgba_png( + 4, 1, b"".join(bytes((200, 10, 10, a)) for a in (0, 85, 170, 255)) + ), + "gray-ramp": rgba_png( + 4, 1, b"".join(bytes((v, v, v, 255)) for v in (0, 86, 170, 255)) + ), + "alpha-ramp3": rgba_png( + 3, 1, b"".join(bytes((200, 10, 10, a)) for a in (0, 128, 255)) + ), + "color": rgba_png(4, 1, bytes([200, 10, 10, 255]) * 4), + "rgb": rgba_png(4, 1, bytes([255, 0, 0, 255, 0, 255, 0, 255]) * 2), + } + + def tearDown(self): + self.directory.cleanup() + + def theme(self, toml=THEME, **files): + """Write theme.toml and art given as "light/apple/Alpha" -> fixture name.""" + (self.root / "theme.toml").write_text(toml) + for appearance in ("light", "dark"): + if (self.root / appearance).is_dir(): + shutil.rmtree(self.root / appearance) + for path, art in files.items(): + if path.endswith(".toml"): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(art) + continue + target = self.root / f"{path}.png" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(self.art[art]) + return self.root + + def compile(self, toml=THEME, catalog=None, **files): + self.theme(toml, **files) + self.build = compile_theme(catalog or self.catalog, self.root) + return self.build.data, self.build.report + + def rejects(self, pattern, toml=THEME, catalog=None, **files): + with self.assertRaisesRegex(ValueError, pattern): + self.compile(toml, catalog, **files) + + def test_mask_paletted_and_rgb565_records(self): + toml = ( + THEME + + '[light.colors]\nicon_tint = "#112233"\n[light.tint]\nicon_tint = ["Delta"]\n[dark]\n' + ) + data, report = self.compile( + toml, + **{ + "light/apple/Alpha": "alpha", + "light/apple/Delta": "gray-ramp", + "light/apple/Zeta": "rgb", + }, + ) + result = inspector.inspect(data, self.catalog) + self.assertEqual(sorted(result["appearances"]), ["dark", "light"]) + light = result["appearances"]["light"] + self.assertEqual([r["index"] for r in light["records"]], [0, 3, 5]) + self.assertEqual( + light["tinted"], + {3: {"name": "Delta", "role": "icon_tint", "coverage": "alpha"}}, + ) + self.assertEqual(light["colors"]["icon_tint"], "#112233") + body, count, bitmap_count = rvtfile.decode_file(data)["packs"]["light"] + self.assertEqual((count, bitmap_count), (3, 0)) + at = style.STYLE_BYTES + self.assertEqual(rvtfile.RECORD.unpack_from(body, at), (0, 0, 12)) + at += 12 + self.assertEqual( + body[at : at + 12], bytes([30, 20, 10, 50, 60, 50, 40, 70, 0, 1, 0, 1]) + ) + at += 12 + self.assertEqual(rvtfile.RECORD.unpack_from(body, at), (3, 0, 4)) + at += 12 + self.assertEqual(body[at : at + 4], bytes([0, 86, 170, 255])) + at += 4 + # Two repeated words compress to 7 bytes, so Zeta is an lz record. + self.assertEqual(rvtfile.RECORD.unpack_from(body, at), (5, 5, 7)) + at += 12 + words = struct.pack("<4H", 0xF800, 0x07E0, 0xF800, 0x07E0) + self.assertEqual(lz.lz_decode(body[at : at + 7], 8), words) + self.assertEqual(light["records"][2]["payload"], words) + self.assertEqual(light["records"][2]["bytes"], 7) + self.assertEqual(len(body), at + 8) + self.assertEqual( + report["appearances"]["light"]["records"], {"pixels": 2, "pixels_lz": 1} + ) + self.assertEqual(report["appearances"]["light"]["bytes"], len(body)) + dark = result["appearances"]["dark"] + self.assertEqual(dark["colors"], style.COLOR_DEFAULTS["dark"]) + self.assertEqual( + (dark["records"], dark["tinted"], dark["rendering"]), ([], {}, 0) + ) + self.assertEqual(sorted(report), ["appearances", "id", "name"]) + self.assertEqual( + sorted(report["appearances"]["light"]), + [ + "accents_builtin", + "bytes", + "contrast", + "extension_bitmaps", + "extension_tinted", + "palette_reduced", + "records", + ], + ) + self.assertEqual(len(report["appearances"]["light"]["accents_builtin"]), 9) + self.assertTrue(report["appearances"]["light"]["contrast"]) + + def test_tinted_palette_and_bgra_art_and_palette_reduction(self): + toml = ( + THEME + + '[dark.colors]\nicon_tint = "#112233"\n[dark.tint]\nicon_tint = ["Alpha"]\nselection = ["0x20"]\ntext = ["Epsilon"]\n' + ) + data, _ = self.compile( + toml, + **{ + "dark/apple/Alpha": "alpha-ramp", + "dark/apple/0x20": "alpha-ramp3", + "dark/apple/Epsilon": "alpha-ramp", + }, + ) + pack = inspector.inspect(data, self.catalog)["appearances"]["dark"] + self.assertEqual( + {i: t["role"] for i, t in pack["tinted"].items()}, + {0: "icon_tint", 1: "selection", 4: "text"}, + ) + payloads = {r["name"]: r["payload"] for r in pack["records"]} + # Paletted: transparent reserved, then the tint with the mean coverage + # of the levels the palette cannot hold. + self.assertEqual( + payloads["Alpha"][:8], bytes([0, 0, 0, 0, 0x33, 0x22, 0x11, 170]) + ) + self.assertEqual( + payloads["Beta"], + bytes([0, 0, 0, 0, 0x33, 0x22, 0x11, 128, 0x33, 0x22, 0x11, 255]), + ) + self.assertEqual(payloads["Epsilon"], bytes([0x05, 0xAF])) # 4-bit gray steps + self.assertEqual( + self.build.warnings, + ["dark/apple/Alpha.png: 4 colours reduced to the 2 of its palette"], + ) + self.assertEqual( + self.build.report["appearances"]["dark"]["palette_reduced"], + [{"name": "Alpha", "colors": 4, "palette": 2}], + ) + # A tinted mask without art sets the role and writes no record. + data, _ = self.compile(THEME + '[light.tint]\nicon_tint = ["Delta"]\n') + pack = inspector.inspect(data, self.catalog)["appearances"]["light"] + self.assertEqual((list(pack["tinted"]), pack["records"]), ([3], [])) + + def test_output_is_deterministic_and_accepted_without_catalog(self): + first, _ = self.compile(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + second, _ = self.compile(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + self.assertEqual(first, second) + self.assertEqual(inspector.inspect(first)["id"], "test") + self.assertEqual(self.build.warnings, []) + + def test_style_tables(self): + toml = THEME + ( + '[dark.colors]\naccent_fill = "#ABCDEF"\n' + '[dark.accents.teal]\nselection = "#006666"\n' + "[dark]\nmenu_covers_default = false\n" + "[dark.rendering]\nflat_selection = true\nflat_now_playing = true\n" + ) + data, report = self.compile(toml) + pack = inspector.inspect(data, self.catalog)["appearances"]["dark"] + self.assertEqual(pack["colors"]["accent_fill"], "#abcdef") + self.assertEqual(pack["rendering"], 7) + self.assertEqual(pack["accents"]["teal"]["selection"], "#006666") + self.assertEqual(pack["accents"]["teal"]["on_accent"], "#ffffff") + self.assertEqual(pack["colors"]["icon_tint"], "#00a1ff") + builtin = report["appearances"]["dark"]["accents_builtin"] + self.assertNotIn("teal", builtin) + self.assertIn("yellow", builtin) + + def test_invalid_toml_and_art_are_rejected(self): + cases = { + "schema: unsupported schema 2": THEME.replace("schema = 1", "schema = 2"), + r"^id: expected": THEME.replace('"test"', '"Test"'), + "reserved for the built-in theme": THEME.replace('"test"', '"classic"') + + "[light]\n", + "exceeds 47": THEME.replace('"Test"', '"' + "x" * 48 + '"'), + r"declare \[light\]": THEME, + "extra: unknown key": THEME + "extra = 1\n[light]\n", + "fonts: unsupported capability": THEME + "[light.fonts]\n", + "light.colours: unknown key": THEME + "[light.colours]\n", + "light.colors.accent: unknown key": THEME + + '[light.colors]\naccent = "#000000"\n', + 'light.colors.text: expected "#rrggbb"': THEME + + '[light.colors]\ntext = "#fff"\n', + "light.accents.cyan: unknown key": THEME + "[light.accents.cyan]\n", + "light.rendering.selection: unknown key": THEME + + '[light.rendering]\nselection = "rounded"\n', + "light.menu_covers_default: expected true or false": THEME + + '[light]\nmenu_covers_default = "on"\n', + "light.tint.well: expected one of": THEME + + '[light.tint]\nwell = ["Delta"]\n', + "Zeta cannot be tinted": THEME + '[light.tint]\ntext = ["Zeta"]\n', + "light.tint.text: Delta is already tinted text": THEME + + '[light.tint]\ntext = ["Delta", "0x40"]\n', + "invalid TOML": THEME + "[light]\n[light]\n", + "author: expected a non-empty string": THEME + 'author = ""\n[light]\n', + } + for pattern, toml in cases.items(): + with self.subTest(pattern): + self.rejects(pattern, toml) + light = THEME + "[light]\n" + self.rejects( + "light/apple/Nope.png: 'Nope' is not a catalog bitmap name", + light, + **{"light/apple/Nope": "alpha"}, + ) + self.rejects( + "duplicate replacement for Alpha", + light, + **{"light/apple/Alpha": "alpha", "light/apple/0x10": "alpha"}, + ) + self.rejects( + "light/apple/Alpha.png: expected 4x1, got 3x1", + light, + **{"light/apple/Alpha": "beta"}, + ) + self.rejects( + "light/apple/Zeta.png: native RGB565 requires opaque", + light, + **{"light/apple/Zeta": "alpha-ramp"}, + ) + self.rejects( + "ambiguous", + light, + fixtures.catalog(duplicate_name=True), + **{"light/apple/Beta": "beta"}, + ) + self.rejects( + "grayscale or carry alpha coverage", + light + '[light.tint]\nicon_tint = ["Delta"]\n', + **{"light/apple/Delta": "color"}, + ) + self.rejects( + r"dark: has art but theme.toml declares no \[dark\]", + light, + **{"dark/apple/Alpha": "alpha"}, + ) + # An empty folder, as `rvt new` leaves one, is not art. + self.theme(light) + (self.root / "dark" / "apple").mkdir(parents=True) + (self.root / "dark" / "extensions").mkdir() + compile_theme(self.catalog, self.root) + + def rejects_file(pattern, prepare): + self.theme(light) + (self.root / "light" / "apple").mkdir(parents=True) + prepare(self.root / "light" / "apple") + with self.assertRaisesRegex(ValueError, pattern): + compile_theme(self.catalog, self.root) + + outside = self.root.parent / "Alpha.png" + outside.write_bytes(self.art["alpha"]) + rejects_file( + "light/apple/notes.txt: expected .png", + lambda folder: (folder / "notes.txt").write_text("x"), + ) + rejects_file( + "light/apple/Alpha.png: must be a file inside the theme folder", + lambda folder: (folder / "Alpha.png").symlink_to(outside), + ) + rejects_file( + "light/apple/Alpha.png: must be a file inside the theme folder", + lambda folder: (folder / "Alpha.png").mkdir(), + ) + + def test_reserved_id_with_permission_carries_art_only(self): + classic = THEME.replace('"test"', '"classic"') + self.theme(classic + "[dark]\n") + build = compile_theme(self.catalog, self.root, allow_reserved=True) + self.assertEqual(inspector.inspect(build.data, self.catalog)["id"], "classic") + for table in ( + "[dark.rendering]\nflat_icons = true\n", + "[dark]\nmenu_covers_default = false\n", + '[dark.tint]\ntext = ["Delta"]\n', + ): + self.theme(classic + table) + with self.assertRaisesRegex(ValueError, "dark: the built-in theme carries"): + compile_theme(self.catalog, self.root, allow_reserved=True) + + def test_inspector_checks_packs_against_the_catalog(self): + data, _ = self.compile( + THEME + "[light]\n", **{"light/apple/Delta": "gray-ramp"} + ) + header = rvtfile.decode_file(data) + body, count, _ = header["packs"]["light"] + + def rebuilt(body, count=count, fingerprint=header["fingerprint"]): + return rvtfile.encode_file( + fingerprint, "test", "Test", {"light": (bytes(body), count, 0)} + ) + + def tinted(index, value=1): + data = bytearray(body) + data[style.TINT_OFFSET + index] = value + return rebuilt(data) + + cases = { + "no palette or coverage": tinted(5), + "Epsilon has unknown record kind 0x7": rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(4, 7, 4) + + body[style.STYLE_BYTES + 12 :] + ), + "outside the catalog": tinted(11), + "catalog fingerprint": rebuilt(body, fingerprint=bytes(8)), + "truncated record header": rebuilt(body[: style.STYLE_BYTES + 4]), + "trailing bytes": rebuilt(body + bytes(4)), + "truncated record payload": rebuilt( + body + rvtfile.RECORD.pack(4, 0, 2), count=2 + ), + "sorted by unique": rebuilt(body + body[style.STYLE_BYTES :], count=2), + "catalog index 90 is outside": rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(90, 0, 4) + + body[style.STYLE_BYTES + 12 :] + ), + "does not match the native bitmap": rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(3, 0, 5) + + body[style.STYLE_BYTES + 12 :] + ), + "catalog maximum": rebuilt( + body + bytes(rvtfile.EXTENSION_TABLE_MAX_BYTES + 1024), count=0 + ), + } + for pattern, bad in cases.items(): + with self.subTest(pattern), self.assertRaisesRegex(ValueError, pattern): + inspector.inspect(bad, self.catalog) + data, _ = self.compile(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + body = bytearray(rvtfile.decode_file(data)["packs"]["light"][0]) + body[-1] = 7 + with self.assertRaisesRegex(ValueError, "invalid palette index"): + inspector.inspect(rebuilt(body, 1), self.catalog) + body[-1] = 1 + padded = ( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(0, 0, 10) + + body[style.STYLE_BYTES + 12 :] + ) + with self.assertRaisesRegex(ValueError, "padding must be zero"): + inspector.inspect(rebuilt(padded, 1)) + payload = bytes(body[style.STYLE_BYTES + 12 :]) + stream = lz.lz_encode(payload + payload) + + def lz_record(stream, size=None): + return rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(0, 5, size if size is not None else len(stream)) + + stream + + bytes(-len(stream) % 4), + 1, + ) + + with self.assertRaisesRegex(ValueError, "Alpha: lz stream continues"): + inspector.inspect(lz_record(stream), self.catalog) + with self.assertRaisesRegex(ValueError, "Alpha: lz match outside"): + inspector.inspect(lz_record(bytes([1, 0, 5, 0])), self.catalog) + with self.assertRaisesRegex(ValueError, "Alpha: lz stream ends early"): + inspector.inspect(lz_record(lz.lz_encode(payload)[:-1]), self.catalog) + with self.assertRaisesRegex(ValueError, "Alpha: lz stream continues"): + inspector.inspect(lz_record(lz.lz_encode(payload) + b"\0"), self.catalog) + good = lz_record(lz.lz_encode(payload)) + record = inspector.inspect(good, self.catalog)["appearances"]["light"][ + "records" + ][0] + self.assertEqual((record["kind"], record["payload"]), ("pixels_lz", payload)) + # Without a catalog the stream stays as stored. + record = inspector.inspect(good)["appearances"]["light"]["records"][0] + self.assertEqual(record["payload"], lz.lz_encode(payload)) + + def test_cli_writes_after_validation_and_leaves_failures_untouched(self): + out = Path(self.directory.name) / "out" + catalog_path = Path(self.directory.name) / "catalog.json" + catalog_path.write_text(json.dumps(fixtures.catalog_document())) + self.theme(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + args = [ + "compile", + str(self.root), + "--out", + str(out), + "--catalog", + str(catalog_path), + ] + with contextlib.redirect_stdout(io.StringIO()): + cli.main(args) + self.assertEqual(sorted(os.listdir(out / "test")), ["report.json", "test.rvt"]) + before = (out / "test" / "test.rvt").read_bytes() + report = json.loads((out / "test" / "report.json").read_text()) + self.assertEqual(list(report["appearances"]), ["light"]) + (self.root / "theme.toml").write_text(THEME + "[light.fonts]\n") + with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()): + cli.main(args) + self.assertEqual((out / "test" / "test.rvt").read_bytes(), before) + truncated = self.art["alpha"][:-10] + (self.root / "theme.toml").write_text(THEME + "[light]\n") + (self.root / "light" / "apple" / "Alpha.png").write_bytes(truncated) + with ( + self.assertRaises(SystemExit), + contextlib.redirect_stderr(io.StringIO()) as err, + ): + cli.main(args) + self.assertIn("light/apple/Alpha.png: truncated PNG", err.getvalue()) + (self.root / "light" / "apple" / "Alpha.png").write_bytes(self.art["alpha"]) + with contextlib.redirect_stdout(io.StringIO()) as output: + cli.main( + [ + "inspect", + str(out / "test" / "test.rvt"), + "--catalog", + str(catalog_path), + ] + ) + self.assertIn("1 records: 1 pixels; 0 tinted", output.getvalue()) + self.assertIn("0 extension bitmaps", output.getvalue()) + + def test_write_returns_the_rvt_path(self): + self.theme(THEME + "[dark]\n") + path, build = write( + self.catalog, self.root, Path(self.directory.name) / "build" + ) + self.assertEqual(path.name, "test.rvt") + self.assertEqual(build.report["id"], "test") + self.assertTrue(path.with_name("report.json").is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_derive.py b/themes/tests/test_derive.py new file mode 100644 index 0000000..d46e780 --- /dev/null +++ b/themes/tests/test_derive.py @@ -0,0 +1,507 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Derived art: derivation files, record payloads, the reference arithmetic +applied to fixture bitmaps, rules resolved from the other appearance, and the +firmware helpers against a synthetic image.""" + +import shutil +import struct +import tempfile +import unittest +from pathlib import Path + +import fixtures +from fixtures import rgba_png +from rvt import bitmaps, derive, firmware, inspector +from rvt import rvtfile as format +from rvt.compiler import compile_theme + +THEME = 'schema = 1\nid = "test"\nname = "Test"\n' + +ETA, THETA, IOTA, KAPPA, LAMBDA = 6, 7, 8, 9, 10 +NARROW = 'kind = "relight"\nbg_lo = 24\nbg_hi = 26\nicon_lo = 30\nicon_hi = 31\n' + + +class DeriveTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) / "src" + self.root.mkdir() + self.catalog = fixtures.catalog() + self.image = fixtures.firmware_image() + self.firmware = firmware.Firmware(self.image_path(), self.catalog) + + def tearDown(self): + self.directory.cleanup() + + def image_path(self): + path = Path(self.directory.name) / "osos.bin" + path.write_bytes(self.image) + return path + + def theme(self, toml=THEME, **files): + (self.root / "theme.toml").write_text(toml) + for appearance in ("light", "dark"): + if (self.root / appearance).is_dir(): + shutil.rmtree(self.root / appearance) + for path, content in files.items(): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, bytes): + target.write_bytes(content) + else: + target.write_text(content) + + def compile(self, toml=THEME, **files): + self.theme(toml, **files) + self.build = compile_theme(self.catalog, self.root) + return self.build.data, self.build.report + + def rejects(self, pattern, toml=THEME, **files): + with self.assertRaisesRegex(ValueError, pattern): + self.compile(toml, **files) + + def records(self, data, appearance="dark"): + return inspector.inspect(data, self.catalog)["appearances"][appearance][ + "records" + ] + + def stock(self, index): + return fixtures.BITMAPS[index] + + # Files and payloads + + def test_recolor_file_sorts_pairs_and_encodes_them(self): + toml = 'kind = "recolor"\n[map]\n"#000000ff" = "#ffffffff"\n"#ffffffff" = "#000000ff"\n' + data, _ = self.compile(THEME + "[dark]\n", **{"dark/apple/Eta.toml": toml}) + (record,) = self.records(data) + self.assertEqual(record["kind"], "recolor") + self.assertEqual( + record["spec"], + [ + (b"\0\0\0\xff", b"\xff\xff\xff\xff"), + (b"\xff\xff\xff\xff", b"\0\0\0\xff"), + ], + ) + body = format.decode_file(data)["packs"]["dark"][0] + at = format.STYLE_BYTES + self.assertEqual(format.RECORD.unpack_from(body, at), (ETA, 1, 4 + 16)) + self.assertEqual(body[at + 12 : at + 16], struct.pack("l*u=P%#^x1{$Ky^|4#JpUhB&m56XFaBQd$%&?~^Kj_2Oh02lc}@Ln1N?q?=*&yubFj?& z)xE|nzUV3UwX&yPYa0i7(?6d&LHd*KvGK1=AtJjp{kHA&>nk5Z9n?3A9>4ZGauyxb z`#j?EbIGLif2o`pYI-sa3;i5+(9g8z-mb`R83Q2Lv#t{B6A)RGGegHI@g!e zbcxDOvB8Y_7DA+%bf=V+bEOkZ%YDwY504nOq5U$`@#WYi1jL%wYEKWwj|5m1c(pFrGsPzK-PQU z0$&ZXzFydqn;-##_;E~|`VJD)ce(!ge9Q*470Nkst%91M`GD6MS{(o9!&m)#L`}4~ zXz_n3GWc>PsMapT1u{94#u!BNZIGA95BULf9BrUDL-0#-`=5ePvGo`DHNDW-Uu=F; z5dR%3h&+_!)oidq4~b)%Wb86gI+j&}wq3Fq#YVdsu<*mG$n#qHTi~R{zC{dGpu}VT zd$BKnU_Bz@^7G@fA6j2t5nP}|k~{x1;iF7G6S!IyI$SJH;fHV<6ny`61%%gIcL-7P z$lC_5XbxBm_c<1Xa4Ki4CGK##R>;Ps!<(Ut4m_MHTE!xz*0lXPX@rM?bqIe5Q_7wy zAKsE|`k>GHkHp5~r;-VB%>f;Z`4%fQpn|qfjB8~EjAEq)28*ZYme-9%aY0kv#ro5=Ucs?@UVypD8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hx0Tb0fAshFlf!?TF_{<3^`!f^ zi+tkqY1}te<)>`i>4%M`Y`x3XZbm?>1eU=YpGl5Bx36LLH(K51&d7`zWKVJg!1mx1 zUDlY}0?Mb;Jn7Ker}cWe_8Y)E@tfAICxDYoe?t7fCSiMa`|Sd``^Spm$(SL-q|D?{ zKkxhYa+>?efjZ4kfZ1g_HMS{l>rOIG0XI2zzZN!o`a1~mI&Cjct=m(^9ufol&SWp{ zPjChvWq8v#2JBpc@hi(XUF!tDU7sg9-vs+_Dytrw-|*;h%zFLl@xOf& yvYzNZJ#O)@>eqed+ou;;zHbupll*^D{QrL=^gk%h>3bsp0000 tuple[int, int]: + """Rewrite the PNG with at most the bitmap's palette entries; returns the + colour counts before and after.""" + width, height, rgba = bitmaps.read_png(path.read_bytes()) + before = bitmaps.distinct(rgba) + capacity = entry["palette_colors"] + if capacity and before > capacity: + rgba = bitmaps.fit_palette(rgba, capacity) + path.write_bytes(bitmaps.write_png(width, height, rgba)) + return before, bitmaps.distinct(rgba) + + +def preview(path: Path, folder: Path, suffix: str) -> None: + folder.mkdir(parents=True, exist_ok=True) + subprocess.run( + [ + "magick", + str(path), + "-filter", + "point", + "-resize", + f"{SCALE * 100}%", + str(folder / f"{path.stem}-{suffix}.png"), + ], + check=True, + ) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--preview", type=Path, help="write before/after PNGs here") + args = parser.parse_args(argv) + entries = catalog.load(None) + for path in sorted((HERE / "dark" / "apple").glob("*.png")): + entry = entries.assets[entries.resolve(path.stem, path.name)] + if args.preview: + preview(path, args.preview, "before") + before, after = fit(path, entry) + if args.preview: + preview(path, args.preview, "after") + print( + f"{path.name}: {before} -> {after} colours (palette {entry['palette_colors']})" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/themes/classic/recolor.py b/themes/themes/classic/recolor.py new file mode 100644 index 0000000..0f9cc6e --- /dev/null +++ b/themes/themes/classic/recolor.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write Classic dark's generated recolour rule files from the stock colours. + +Each bitmap in RULES gets `dark/apple/.toml` mapping every stock colour +through a tonal curve: two luma anchors joined by a line, clamped between +them, give the output grey; the stock alpha is kept. Colours with a chroma at +or above the rule's threshold (the red of a calendar header, the purple of a +Genius atom) pass through unchanged, so only the greys move. Every colour the +bitmap uses is listed, which is what keeps the iPod's result free of stray +stock pixels; a colour the curve leaves unchanged is left out because the +format forbids identity pairs. RGB565 targets lose the low bits the format +drops. The remaining .toml files in dark/apple/ are hand-written. + + python3 themes/classic/recolor.py --firmware osos.bin [--check] + +--check regenerates in memory and reports files that differ, writing nothing. +""" + +import argparse +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import catalog, derive, firmware # noqa: E402 + +# A curve: (stock luma, output grey) at two points; the line through them, +# clamped to the output range. A falling curve inverts a glyph. +SURFACE = ((0x5B, 0x10), (0xFC, 0x2F)) # the recoloured status bar's range +CELL = ((0x90, 0x26), (0xFF, 0x3C)) # a step above the #181818 background +CELL_DIM = ((0x90, 0x20), (0xFF, 0x30)) +WELL = ((0x80, 0x3C), (0xFF, 0x6E)) # the Disk Mode empty bar's grey +GLYPH = ((0x00, 0xE8), (0xA0, 0xA0)) # a dark glyph on transparent, inverted +PAGE = ((0x00, 0xD8), (0xFF, 0x2E)) # a dark glyph on an opaque white page +THUMB = ((0x80, 0x80), (0xFF, 0xC8)) # a white thumb that must stay a thumb +TRACK = ((0xAC, 0x33), (0xFC, 0x4A)) # the playing progress track +# The track's translucent rows are its reflection on the floor below; at the +# stock alphas they need a brighter grey than the track to show on dark. +TRACK_REFLECTION = ((0xAC, 0x70), (0xFC, 0x90)) +DIM = ((0x80, 0x80), (0xFF, 0xE4)) # light art kept, its white taken off glare +# Relight runs on paletted bitmaps only; the one RGB565 proxy square gets a +# curve that lands on relight's background and icon greys. +SQUARE = ((0xB0, 0x8C), (0xD8, 0x19)) + +CHROMA = 24 # below this a colour counts as grey; the extension's accent tint agrees +NEUTRAL = 2 # at most this much cast: the battery outline, not its blue-cast body +CAST = 64 # greys with a colour cast still count as grey; saturated dots pass +ALL = 256 # every colour, whatever its chroma +# The status bar battery needs two curves, told apart by colour cast: its +# neutral-grey outline and nub go brighter than the stock #63 so the frame +# shows on the dark bar, its blue-cast empty body goes dark, and the +# translucent white reflection under it is dropped. +BATTERY = object() +BATTERY_OUTLINE = ((0x60, 0x6A), (0xC8, 0x90)) +BATTERY_BODY = ((0x54, 0x26), (0xA4, 0x50)) + +RULES = { + "Lozenge_Left_White_Image": (SURFACE, CHROMA), + "Lozenge_Middle_White_Image": (SURFACE, CHROMA), + "Lozenge_Right_White_Image": (SURFACE, CHROMA), + "System_Input_Field_Left_Image": (SURFACE, CHROMA), + "System_Input_Field_Middle_Image": (SURFACE, CHROMA), + "System_Input_Field_Right_Image": (SURFACE, CHROMA), + "OptionBar_White_Well_Center_Image": (SURFACE, CHROMA), + "OptionBar_White_Well_LeftCap_Image": (SURFACE, CHROMA), + "OptionBar_White_Well_RightCap_Image": (SURFACE, CHROMA), + "OptionBar_NowPlaying_Well_Center_Image": (SURFACE, CHROMA), + "OptionBar_NowPlaying_Well_LeftCap_Image": (SURFACE, CHROMA), + "OptionBar_NowPlaying_Well_RightCap_Image": (SURFACE, CHROMA), + "WorldClock_Graybar_Image": (SURFACE, CHROMA), + "Calendar_Active_Cell": (CELL, ALL), + "Calendar_Inactive_Cell": (CELL_DIM, ALL), + "Settings_DateTime_Calendar_Image": (DIM, 96), + "Genius_Slider_Image": (CELL, CHROMA), + "NowPlaying_ProgressBar_Active_Background_Image": (TRACK, CHROMA), + "CapacityView_Detailed_EmptyCenter_Image": (WELL, CHROMA), + "CapacityView_Detailed_EmptyLeft_Image": (WELL, CHROMA), + "CapacityView_Detailed_EmptyRight_Image": (WELL, CHROMA), + "CapacityView_Detailed_Edge_Image": (WELL, CHROMA), + "Settings_About_Capacity_Fill_Image": (WELL, CHROMA), + "Settings_About_Capacity_LeftCap_Image": (WELL, CHROMA), + "Settings_About_Capacity_RightCap_Image": (WELL, CHROMA), + **{f"StatusBarWhite_Battery_Image_{i}": (BATTERY, CHROMA) for i in range(23)}, + "StatusBarWhite_Battery_Image_Charge": (GLYPH, CHROMA), + "StatusBarWhite_Battery_Image_Plug": (GLYPH, CHROMA), + "Media_VideoStatusIcon_Image": (GLYPH, CHROMA), + "Podcasts_video_solo_Image": (GLYPH, CHROMA), + "Media_Genius_Refresh_Image": (GLYPH, CHROMA), + "Media_Genius_Normal_Image": (GLYPH, CAST), + "Playlist_Genius_Icon": (GLYPH, CAST), + "Settings_About_Bubble_Deselected_Image": (GLYPH, CHROMA), + "Media_OTGPlaylist_Image": (PAGE, CHROMA), + "No_Content_iTunesU_Small_Image": (SQUARE, ALL), + "OptionBar_NowPlaying_Thumb_Center_Image": (THUMB, CHROMA), + "OptionBar_NowPlaying_Thumb_LeftCap_Image": (THUMB, CHROMA), + "OptionBar_NowPlaying_Thumb_RightCap_Image": (THUMB, CHROMA), +} + + +def gray(curve, level: int) -> int: + (x0, y0), (x1, y1) = curve + value = y0 + (level - x0) * (y1 - y0) / (x1 - x0) + return round(min(max(value, min(y0, y1)), max(y0, y1))) + + +def target(color: bytes, curve, chroma: int, rgb565: bool) -> bytes | None: + """The replacement for one stock colour, or None to leave it alone.""" + red, green, blue, alpha = color + cast = max(red, green, blue) - min(red, green, blue) + if alpha == 0 or cast >= chroma: + return None + luma = derive.luma(red, green, blue) + if curve is BATTERY: + if alpha < 255 and luma > 0xC0: + return bytes(4) + curve = BATTERY_OUTLINE if cast <= NEUTRAL else BATTERY_BODY + elif curve is TRACK and alpha < 255: + curve = TRACK_REFLECTION + level = gray(curve, luma) + out = bytes((level, level, level, alpha)) + if rgb565: + out = firmware.quantize_565(out) + return None if out == color else out + + +def pairs(entries, stock, name: str): + """The sorted colour pairs of one rule file.""" + index = entries.resolve(name, name) + info = entries.assets[index] + curve, chroma = RULES[name] + rgb565 = derive.is_565(info) + result = [] + for color in firmware.stock_colors(info, stock.bitmap(index)): + out = target(color, curve, chroma, rgb565) + if out is not None: + result.append((color, out)) + result.sort(key=lambda pair: derive.key(pair[0])) + derive.check_recolor(result, info, name) + return result + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--firmware", type=Path, required=True, help="osos.bin") + parser.add_argument("--check", action="store_true", help="compare, write nothing") + args = parser.parse_args(argv) + entries = catalog.load(None) + stock = firmware.Firmware(args.firmware, entries) + stale = [] + for name in sorted(RULES): + path = HERE / "dark" / "apple" / f"{name}.toml" + rules = pairs(entries, stock, name) + text = firmware.recolor_text(rules) + if args.check: + if not path.exists() or path.read_text() != text: + stale.append(path.name) + else: + path.write_text(text) + print(f"{path.name}: {len(rules)} colour pairs") + for name in stale: + print(f"{name}: differs from the table", file=sys.stderr) + return 1 if stale else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/themes/classic/theme.toml b/themes/themes/classic/theme.toml new file mode 100644 index 0000000..852a368 --- /dev/null +++ b/themes/themes/classic/theme.toml @@ -0,0 +1,14 @@ +schema = 1 +id = "classic" +name = "Classic" + +[dark.derive] +"Media_NowPlayingIcon_*Black_Image" = { kind = "invert" } +"No_Content_Albums_Small_Image" = { kind = "alias", source = "Media_AlbumsProxy_Image" } +"No_Content_AudioBooks_Small_Image" = { kind = "alias", source = "Media_AudioBooksProxy_Image" } +"No_Content_MusicVideos_Small_Image" = { kind = "alias", source = "Media_MusicVideosProxy_Image" } +"No_Content_Podcasts_Small_Image" = { kind = "alias", source = "Media_PodcastsProxy_Image" } +"No_Content_TVShows_Small_Image" = { kind = "alias", source = "Media_TVShowsProxy_Image" } +"No_Content_Videos_Small_Image" = { kind = "alias", source = "Media_VideosProxy_Image" } +"NowPlaying_White_Pause_Image" = { kind = "alias", source = "NowPlaying_Black_Pause_Image" } +"NowPlaying_White_Play_Image" = { kind = "alias", source = "NowPlaying_Black_Play_Image" } diff --git a/themes/tools/bitmaps_doc.py b/themes/tools/bitmaps_doc.py new file mode 100644 index 0000000..d4343d2 --- /dev/null +++ b/themes/tools/bitmaps_doc.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write docs/bitmaps.md, the catalog as a page: every bitmap a theme can +replace, grouped by name prefix, with its size, format, palette size and +whether it can be tinted. The "Appears" column is written by hand; the +generator keeps what the committed page says.""" + +import argparse +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import bitmaps, catalog # noqa: E402 + +PAGE = ROOT / "docs" / "bitmaps.md" +# Prefixes with fewer bitmaps than this share the Other group. +GROUP_MINIMUM = 4 +OTHER = "Other" +ROW = re.compile(r"\| `([^`]+)` \| [^|]* \| [^|]* \| [^|]* \| [^|]* \| ([^|]*) \|") +HEAD = """# Bitmaps + +Every bitmap of Apple's 2.0.5 firmware a theme can replace, from the +[catalog](catalog.md), grouped by name prefix. Size is width x height in +pixels. Palette is the number of native palette entries. Tintable says whether +`[.tint]` may name it. Appears is filled in by hand. + +Regenerate with `python3 tools/bitmaps_doc.py`; the Appears column survives. +""" + + +def group_of(name: str) -> str: + """The name's first word; a leading No_ belongs to the next word.""" + parts = name.split("_", 2) + if parts[0] == "No" and len(parts) > 1: + return "_".join(parts[:2]) + return parts[0] + + +def natural(name: str) -> list: + return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", name)] + + +def groups(assets: list) -> dict[str, list]: + """Prefix -> bitmaps, small prefixes merged into Other, Other last.""" + by_prefix: dict[str, list] = {} + for asset in assets: + by_prefix.setdefault(group_of(asset["name"]), []).append(asset) + result = {} + other = [] + for prefix in sorted(by_prefix): + if len(by_prefix[prefix]) < GROUP_MINIMUM: + other += by_prefix[prefix] + else: + result[prefix] = by_prefix[prefix] + if other: + result[OTHER] = other + return result + + +def appears_from(text: str) -> dict[str, str]: + """Name -> the Appears cell of an existing page.""" + return {name: cell.strip() for name, cell in ROW.findall(text)} + + +def page(assets: list, appears: dict[str, str]) -> str: + lines = [HEAD] + for group, members in groups(assets).items(): + lines += [ + f"## {group}", + "", + "| Name | Size | Format | Palette | Tintable | Appears |", + "|---|---|---|---|---|---|", + ] + for asset in sorted(members, key=lambda a: natural(a["name"])): + palette = asset["palette_colors"] or "-" + tintable = "yes" if bitmaps.tint_kind(asset["format"]) else "no" + lines.append( + f"| `{asset['name']}` | {asset['width']}x{asset['height']} | " + f"{catalog.FORMAT_NAMES[asset['format']]} | {palette} | {tintable} | " + f"{appears.get(asset['name'], '')} |" + ) + lines.append("") + return "\n".join(lines) + + +def current(path: Path = PAGE) -> str: + """The page as the generator writes it today.""" + assets = catalog.load(None).assets + existing = appears_from(path.read_text()) if path.is_file() else {} + return page(assets, existing) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--out", type=Path, default=PAGE) + args = parser.parse_args(argv) + args.out.write_text(current(args.out)) + print(f"Wrote {args.out}") + + +if __name__ == "__main__": + main() diff --git a/themes/tools/extension_bitmaps_doc.py b/themes/tools/extension_bitmaps_doc.py new file mode 100644 index 0000000..46075af --- /dev/null +++ b/themes/tools/extension_bitmaps_doc.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write docs/extension-bitmaps.md: the bitmaps of the first-party extensions +a theme can replace, from the vendored extension asset catalog +rvt/data/extensions.json.""" + +import argparse +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import assets # noqa: E402 + +PAGE = ROOT / "docs" / "extension-bitmaps.md" +HEAD = """# Extension bitmaps + +The first-party extension bitmaps a theme can replace with +`/extensions//.png`, or `/reprise/.png` +for the core's (id `reprise`). See [Authoring](authoring.md#extension-bitmaps). +Size is width x height in pixels, which the art must match. Menu marks a +Settings icon, a 78 x 121 coverage mask drawn in the icon tint. + +The catalog and how to regenerate it are in +[Catalog](catalog.md#extension-asset-catalog). + +Regenerate this page with `python3 tools/extension_bitmaps_doc.py`. +""" + + +def page(records: dict[tuple[str, str], dict]) -> str: + lines = [ + HEAD, + "| Id | Asset | Size | Format | Palette | Menu |", + "|---|---|---|---|---|---|", + ] + for (identifier, asset), record in sorted(records.items()): + fmt = assets.FORMAT_NAMES.get(record["format"], f"{record['format']:#x}") + lines.append( + f"| `{identifier}` | `{asset}` | {record['width']}x{record['height']} | " + f"{fmt} | {record['palette_colors'] or '-'} | " + f"{'yes' if record['menu'] else 'no'} |" + ) + return "\n".join(lines) + "\n" + + +def current() -> str: + """The page as the generator writes it today.""" + return page(assets.load_catalog()) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--out", type=Path, default=PAGE) + args = parser.parse_args(argv) + args.out.write_text(current()) + print(f"Wrote {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/tools/extensions_catalog.py b/themes/tools/extensions_catalog.py new file mode 100644 index 0000000..ef59621 --- /dev/null +++ b/themes/tools/extensions_catalog.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write rvt/data/extensions.json from the `build/assets.json` the extensions +build writes: every record checked, one per line with sorted keys, ordered by +id then asset so that diffs read.""" + +import argparse +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import assets # noqa: E402 + + +def convert(source: Path) -> str: + records = sorted(assets.read_json(source), key=lambda r: (r["id"], r["asset"])) + seen = set() + for record in records: + key = (record["id"], record["asset"]) + if key in seen: + raise ValueError(f"{source}: {key[0]}/{key[1]} is listed twice") + seen.add(key) + return "".join(json.dumps(record, sort_keys=True) + "\n" for record in records) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument( + "assets", + type=Path, + nargs="?", + default=Path(__file__).resolve().parents[2] / "build" / "assets.json", + help="the extensions build's assets.json (default: ../build/assets.json)", + ) + parser.add_argument("--out", type=Path, default=Path(str(assets.CATALOG))) + args = parser.parse_args(argv) + try: + args.out.write_text(convert(args.assets)) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + print(f"Wrote {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 7dfce2b8ef65f88fecff6b8e0f784f1e8b75bebc Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 11:56:50 +0000 Subject: [PATCH 14/20] feat: add Appearance Settings > Appearance, after Brightness: Theme, Accent, Dark Mode (Auto by sunset and sunrise, On or Off), Menu Covers and Now Playing Cover. Classic's dark look is derived from the stock artwork on the iPod at switch time; other themes are .rvt files in /Reprise/Themes, compiled by the rvt compiler in themes/, which also supplies the format header, the bitmap catalog and the Classic asset the build packs. The first load imports the core's former Dark Mode switch. Night Shift's row joins the Appearance menu after Dark Mode. The root make also writes build/assets.json for the theme tooling. From RevolaOS extensions a32d616f5a06. --- Makefile | 17 +- NOTICE | 8 +- README.md | 3 +- catalog/sources.toml | 5 + extensions/appearance/Makefile | 29 + extensions/appearance/README.md | 48 + extensions/appearance/assets.c | 142 + extensions/appearance/assets.h | 45 + .../appearance/assets/LICENSE.cupertino-icons | 20 + extensions/appearance/assets/render.py | 49 + .../appearance/assets/settings-accent.png | Bin 0 -> 1372 bytes .../appearance/assets/settings-appearance.png | Bin 0 -> 1383 bytes .../appearance/assets/settings-cover.png | Bin 0 -> 1452 bytes .../appearance/assets/settings-covers.png | Bin 0 -> 948 bytes .../appearance/assets/settings-moon.png | Bin 0 -> 1332 bytes .../appearance/assets/settings-theme.png | Bin 0 -> 1787 bytes extensions/appearance/catalog.c | 233 ++ extensions/appearance/catalog.h | 91 + extensions/appearance/crc.c | 21 + extensions/appearance/crc.h | 12 + extensions/appearance/dark_mode.c | 40 + extensions/appearance/dark_mode.h | 18 + extensions/appearance/derive.c | 393 +++ extensions/appearance/derive.h | 35 + extensions/appearance/ext.h | 33 + extensions/appearance/flat_cover.c | 81 + extensions/appearance/flat_cover.h | 19 + extensions/appearance/latch.c | 53 + extensions/appearance/latch.h | 17 + extensions/appearance/listing.toml | 9 + extensions/appearance/look.c | 285 ++ extensions/appearance/look.h | 79 + extensions/appearance/lz.c | 77 + extensions/appearance/lz.h | 20 + extensions/appearance/main.c | 309 ++ extensions/appearance/manifest.toml | 55 + extensions/appearance/menu_covers.c | 28 + extensions/appearance/menu_covers.h | 18 + extensions/appearance/pack.c | 356 +++ extensions/appearance/pack.h | 44 + extensions/appearance/pixel.h | 65 + extensions/appearance/render.c | 395 +++ extensions/appearance/render.h | 12 + .../appearance/screenshots/appearance.png | Bin 0 -> 27400 bytes .../appearance/screenshots/dark-mode.png | Bin 0 -> 25590 bytes extensions/appearance/selection_bar.c | 79 + extensions/appearance/selection_bar.h | 13 + extensions/appearance/services.h | 56 + extensions/appearance/stock.c | 104 + extensions/appearance/stock.h | 29 + extensions/appearance/style.c | 189 ++ extensions/appearance/style.h | 62 + extensions/appearance/switch.c | 155 + extensions/appearance/switch.h | 22 + extensions/appearance/tests/catalog.inc | 23 + extensions/appearance/tests/contracts.c | 2846 +++++++++++++++++ extensions/appearance/tests/run.py | 51 + extensions/appearance/theme.c | 279 ++ extensions/appearance/theme.h | 46 + extensions/appearance/theme_picker.c | 120 + extensions/appearance/theme_picker.h | 22 + extensions/appearance/tint.c | 306 ++ extensions/appearance/tint.h | 49 + extensions/appearance/tools/catalog_inc.py | 161 + themes/tests/test_style.py | 2 - 65 files changed, 7771 insertions(+), 7 deletions(-) create mode 100644 extensions/appearance/Makefile create mode 100644 extensions/appearance/README.md create mode 100644 extensions/appearance/assets.c create mode 100644 extensions/appearance/assets.h create mode 100644 extensions/appearance/assets/LICENSE.cupertino-icons create mode 100755 extensions/appearance/assets/render.py create mode 100644 extensions/appearance/assets/settings-accent.png create mode 100644 extensions/appearance/assets/settings-appearance.png create mode 100644 extensions/appearance/assets/settings-cover.png create mode 100644 extensions/appearance/assets/settings-covers.png create mode 100644 extensions/appearance/assets/settings-moon.png create mode 100644 extensions/appearance/assets/settings-theme.png create mode 100644 extensions/appearance/catalog.c create mode 100644 extensions/appearance/catalog.h create mode 100644 extensions/appearance/crc.c create mode 100644 extensions/appearance/crc.h create mode 100644 extensions/appearance/dark_mode.c create mode 100644 extensions/appearance/dark_mode.h create mode 100644 extensions/appearance/derive.c create mode 100644 extensions/appearance/derive.h create mode 100644 extensions/appearance/ext.h create mode 100644 extensions/appearance/flat_cover.c create mode 100644 extensions/appearance/flat_cover.h create mode 100644 extensions/appearance/latch.c create mode 100644 extensions/appearance/latch.h create mode 100644 extensions/appearance/listing.toml create mode 100644 extensions/appearance/look.c create mode 100644 extensions/appearance/look.h create mode 100644 extensions/appearance/lz.c create mode 100644 extensions/appearance/lz.h create mode 100644 extensions/appearance/main.c create mode 100644 extensions/appearance/manifest.toml create mode 100644 extensions/appearance/menu_covers.c create mode 100644 extensions/appearance/menu_covers.h create mode 100644 extensions/appearance/pack.c create mode 100644 extensions/appearance/pack.h create mode 100644 extensions/appearance/pixel.h create mode 100644 extensions/appearance/render.c create mode 100644 extensions/appearance/render.h create mode 100644 extensions/appearance/screenshots/appearance.png create mode 100644 extensions/appearance/screenshots/dark-mode.png create mode 100644 extensions/appearance/selection_bar.c create mode 100644 extensions/appearance/selection_bar.h create mode 100644 extensions/appearance/services.h create mode 100644 extensions/appearance/stock.c create mode 100644 extensions/appearance/stock.h create mode 100644 extensions/appearance/style.c create mode 100644 extensions/appearance/style.h create mode 100644 extensions/appearance/switch.c create mode 100644 extensions/appearance/switch.h create mode 100644 extensions/appearance/tests/catalog.inc create mode 100644 extensions/appearance/tests/contracts.c create mode 100755 extensions/appearance/tests/run.py create mode 100644 extensions/appearance/theme.c create mode 100644 extensions/appearance/theme.h create mode 100644 extensions/appearance/theme_picker.c create mode 100644 extensions/appearance/theme_picker.h create mode 100644 extensions/appearance/tint.c create mode 100644 extensions/appearance/tint.h create mode 100755 extensions/appearance/tools/catalog_inc.py diff --git a/Makefile b/Makefile index 737c342..13d3858 100644 --- a/Makefile +++ b/Makefile @@ -1,20 +1,31 @@ # SPDX-License-Identifier: GPL-3.0-only SDK ?= ../osos-lab/rvx-sdk OUT ?= build -extensions := album-artists balance clicker-modes crossfeed dsp equalizer eu-volume-limit \ - file-info homebrew iap-auth-bypass night-shift playback-log playback-queue +extensions := album-artists appearance 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) +all: $(extensions) $(OUT)/assets.json $(extensions): $(MAKE) -C extensions/$@ all SDK="$(abspath $(SDK))" OUT="$(abspath $(OUT))/.work/$@" @mkdir -p "$(OUT)/Extensions" cp "$(OUT)/.work/$@/$@.rvx" "$(OUT)/Extensions/$@.rvx" +# The bitmap assets of the core and every extension, for the theme tooling +# (themes/docs/catalog.md). +$(OUT)/assets.json: $(extensions) + cat "$(abspath $(SDK))/assets.json" > $@ + @for extension in $(extensions); do \ + $(PYTHON) "$(abspath $(SDK))/assets.py" extensions/$$extension/manifest.toml \ + "$(OUT)/Extensions/$$extension.rvx" >> $@ || exit 1; \ + done + .PHONY: check check: $(PYTHON) extensions/album-artists/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/appearance/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))" diff --git a/NOTICE b/NOTICE index 9dac7e2..d463540 100644 --- a/NOTICE +++ b/NOTICE @@ -19,7 +19,13 @@ 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. +Icons glyph (MIT). Appearance is from RevolaOS extensions, revision +a32d616f5a06, and derives from the RepriseOS core's Dark Mode by lgreitis and +Alex Ball; its Settings icons are Cupertino Icons glyphs (MIT), see the +LICENSE.cupertino-icons beside them, and the Classic theme it carries is built +by the rvt compiler in themes/ (see themes/NOTICE). Night Shift's hosted row and +choice screen are from RevolaOS extensions, revision d04fa7d. 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 472e1a0..3148bb0 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,9 @@ This repository hosts the source for these RepriseOS extensions and accepts proposals for the extension catalog. +- [Appearance](extensions/appearance/) adds Dark Mode with Auto, accent colours and themes from `/Reprise/Themes` that recolour the screens and replace the artwork. - [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. +- [Night Shift](extensions/night-shift/) warms the display manually or automatically from sunset to sunrise; its row joins the Appearance menu when that extension runs. - [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. diff --git a/catalog/sources.toml b/catalog/sources.toml index 10f27b3..ae6140d 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -8,6 +8,11 @@ repo = "RepriseOS/repriseos-extensions" path = "extensions/crossfeed" tag_prefix = "crossfeed/v" +[appearance] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/appearance" +tag_prefix = "appearance/v" + [night-shift] repo = "RepriseOS/repriseos-extensions" path = "extensions/night-shift" diff --git a/extensions/appearance/Makefile b/extensions/appearance/Makefile new file mode 100644 index 0000000..ffab405 --- /dev/null +++ b/extensions/appearance/Makefile @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c look.c style.c render.c catalog.c crc.c tint.c selection_bar.c \ + menu_covers.c flat_cover.c latch.c theme.c theme_picker.c lz.c assets.c dark_mode.c \ + ../shared/schedule.c ../shared/sun.c +switch_SOURCES := switch.c pack.c derive.c stock.c +OUT ?= build +# The theme compiler and the Classic theme live in themes/ at the repository +# root: rvt.h and the bitmap catalog come from there, and the Classic dark +# artwork is compiled from there into build/classic.rvt, which stays under +# build/ whatever OUT is, where manifest.toml names it. +THEMES ?= ../../themes +RVT_DATA := $(THEMES)/rvt/data +CATALOG := $(RVT_DATA)/osos-2.0.5.json +CLASSIC := build/classic.rvt +EXTRA_CFLAGS := -I$(OUT) -I../shared -I$(RVT_DATA) +include $(SDK)/rv.mk + +$(OUT)/catalog.inc: $(CATALOG) tools/catalog_inc.py | $(OUT) + $(PYTHON) tools/catalog_inc.py $< $@ +$(OUT)/main/catalog.c.o: $(OUT)/catalog.inc + +$(CLASSIC): $(THEMES)/themes/classic/theme.toml \ + $(wildcard $(THEMES)/themes/classic/dark/apple/*) $(wildcard $(THEMES)/rvt/*.py) \ + $(wildcard $(RVT_DATA)/*) tools/catalog_inc.py + mkdir -p build + cd $(THEMES) && $(PYTHON) -m rvt compile themes/classic --allow-reserved --strict \ + --out $(abspath build)/classic-build >/dev/null + $(PYTHON) tools/catalog_inc.py $(CATALOG) --check build/classic-build/classic/classic.rvt + cp build/classic-build/classic/classic.rvt $@ diff --git a/extensions/appearance/README.md b/extensions/appearance/README.md new file mode 100644 index 0000000..8cef0b5 --- /dev/null +++ b/extensions/appearance/README.md @@ -0,0 +1,48 @@ +# Appearance + +Derives from the core's former Dark Mode (payload/dark_mode.c, 01c89f6) by lgreitis and Alex Ball (alexballvideos-netizen). The Classic theme's dark background is the core's former themes/dark/background-dark-image.png by lgreitis. + +Adds Settings > Appearance, after Brightness, with five rows: + +| Row | Does | +|---|---| +| Theme | replaces colours and artwork | +| Accent | replaces the stock blue in the selection bar, the accent artwork and accent labels | +| Dark Mode | turns the look dark: Auto, On or Off | +| Menu Covers | shows the highlighted row's cover in the Main and Music menus; its Theme value follows the look, which is on for Classic | +| Now Playing Cover | draws the Now Playing cover tilted with its reflection, or flat; its Theme value follows the look, which is tilted for Classic | + +Other extensions can add rows to the menu after any of these (their ids are `theme`, `accent`, `dark-mode`, `menu-covers` and `now-playing-cover`); Night Shift's row follows Dark Mode. + +Themes are `.rvt` files in `/Reprise/Themes/`, built with the compiler in this repository's [themes directory](../../themes/README.md), which also holds the Classic theme. The Theme row lists Classic and up to 64 themes by name, rescanned each time it opens. A theme with the id `classic` is ignored. + +A theme may have a light appearance, a dark one or both. With only one, Dark Mode shows that one, its row value says which, and the pane says "Theme only supports dark mode" or "Theme only supports light mode". If the chosen theme's file is missing, Classic shows and Theme says "Theme unavailable"; the choice comes back with the file. + +A theme that cannot be read leaves the look unchanged. One that fails part way through is undone to the stock light look, and the row the action came from says so. If the stock artwork cannot be restored from `/osos-cfw.bin`, the Appearance row disappears until the next boot. Presses queued during a switch cannot reverse it. Turning the extension off restores the stock artwork. + +## Auto + +Dark Mode's Auto follows sunset and sunrise in the city set under Settings > Date & Time > Time Zone, by the iPod's clock, checked once a minute: dark from the sunset minute to the sunrise minute. Without a time zone, Auto is light and says "Set a time zone". + +A theme with one appearance turns Dark Mode's Auto into the value it shows, as it does On and Off. + +## Colour roles + +| Role | Classic light | Classic dark | Draws | +|---|---|---|---| +| background | `#ffffff` | `#181818` | surfaces, the light greys of the stock screens | +| text | `#202020` | `#e8e8e8` | labels and the dark greys | +| accent_fill | `#236cc5` | `#00a1ff` | accent fills and the artwork that follows the accent | +| accent_text | `#3185d0` | `#00a1ff` | accent-coloured labels | +| on_accent | `#ffffff` | `#ffffff` | labels on the selection bar and on accent fills | +| selection | `#236cc5` | `#00a1ff` | the selection bar | +| cover_border | `#7e8183` | `#383838` | the Cover Flow border | +| icon_tint | `#3185d0` | `#00a1ff` | under a theme, extension icons and the artwork the theme tints with it | + +The accents are Blue, Teal, Green, Yellow, Orange, Red, Pink, Purple and Graphite. Theme Default keeps the look's own, and a theme may give each accent its own palette. A theme can replace extension bitmaps in Settings panes and canvases; the rest keep the extension's art. With `flat_icons`, Settings icons are drawn without their reflection. + +| | | +|---|---| +| Default | off | +| Memory | idle: the main module with the bitmap catalog and its state; Dark Mode on Auto: one timer; a look on: an index entry per bitmap the theme holds for extensions and the draw hook blocks; during a switch: the switch module; during a switch: one scratch block; the Theme list open: one entry per theme | +| Settings | theme id, Accent, Dark Mode, Menu Covers, Now Playing Cover, and `available`, the hidden bool that shows the Appearance row. The first load imports the core's former Dark Mode switch | diff --git a/extensions/appearance/assets.c b/extensions/appearance/assets.c new file mode 100644 index 0000000..41776f2 --- /dev/null +++ b/extensions/appearance/assets.c @@ -0,0 +1,142 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "assets.h" +#include "ext.h" +#include "look.h" +#include "osos-2.0.5.h" +#include "pixel.h" +#include "rv_libc.h" +#include "rv_theme.h" +#include "rvt.h" +#include "style.h" +#include "theme.h" +#include "tint.h" +#include + +static struct asset_entry + *live; /* the active look's index, which the provider answers from */ +static struct asset_entry + *pending; /* the next look's, under construction by a switch */ +static uint32_t live_count, pending_count; +static int providing; /* the core's provider is ours */ + +struct asset_entry *assets_reserve(uint32_t count) +{ + if (pending) + api->free(self, pending); + pending = count ? api->alloc(self, count * sizeof *pending) : NULL; + pending_count = pending ? count : 0; + return pending; +} + +void assets_commit(void) +{ + if (live) + api->free(self, live); + live = pending; + live_count = pending_count; + pending = NULL; + pending_count = 0; +} + +void assets_drop(void) +{ + assets_reserve(0); + assets_commit(); +} + +static const struct asset_entry *find(uint32_t owner, uint32_t asset) +{ + uint32_t low = 0, high = live_count; + while (low < high) { + uint32_t mid = low + (high - low) / 2; + const struct asset_entry *entry = live + mid; + if (entry->owner == owner && entry->asset == asset) + return entry; + if (asset_before(entry, owner, asset)) + low = mid + 1; + else + high = mid; + } + return NULL; +} + +/* The core's probe: how the look stores its bitmap for the asset, from the + * index. */ +static int replacement(uint32_t owner, uint32_t asset, struct rv_asset_stream *stream) +{ + const struct asset_entry *entry = find(owner, asset); + if (!entry) + return 0; + stream->codec = entry->kind == RVT_EXTENSION_BITMAP_LZ ? RV_ASSET_LZ : RV_ASSET_RAW; + stream->stored = entry->bytes; + stream->bytes = entry->decoded; + return 1; +} + +/* The core's read: the stored bitmap from the look's file. The core decodes + * and checks it; a read that fails returns 0 and the core decodes the + * extension's own bitmap instead. Nothing here binds or releases: the core + * is in the middle of a decode or a preload. */ +static int replacement_read(uint32_t owner, uint32_t asset, void *out, uint32_t stored) +{ + struct rv_file *file; + const struct asset_entry *entry = find(owner, asset); + if (!entry || stored != entry->bytes || !look_file_open(look_active(), &file)) + return 0; + int whole = api->file_seek(self, file, entry->offset) == RV_OK && + read_exact(file, out, stored); + api->file_close(self, file); + return whole; +} + +/* An extension's Settings icon as the core decodes it: the art in the upper + * rows of a 78 by 121 Mask8, its mirrored reflection below ICON_ART_ROWS. */ +enum { ICON_WIDTH = 78, ICON_HEIGHT = 121, ICON_STRIDE = 80, ICON_ART_ROWS = 79 }; + +static int menu_bitmap(const uint8_t *b, uint32_t bytes) +{ + return bytes == BMap_payload + ICON_STRIDE * ICON_HEIGHT && + le16(b + BMap_format) == BMapFormat_Mask8 && + le16(b + BMap_stride) == ICON_STRIDE && le16(b + BMap_depth) == 8 && + !le32(b + BMap_bounds) && !le32(b + BMap_bounds + 4) && + le32(b + BMap_bounds + 8) == ICON_HEIGHT && + le32(b + BMap_bounds + 12) == ICON_WIDTH && + le32(b + BMap_payload_bytes) == ICON_STRIDE * ICON_HEIGHT; +} + +/* A decoded bitmap, the look's replacement or the extension's own: a tinted + * replacement picture is painted in its role; under a flat-icon look a + * Settings icon loses its reflection. */ +static int adjust(uint32_t owner, uint32_t asset, void *bmap, uint32_t bytes) +{ + const struct asset_entry *entry = find(owner, asset); + if (entry && entry->tint != RVT_TINT_NONE && !menu_bitmap(bmap, bytes)) + return tint_bmap(bmap, bytes, + style_color((enum rvt_role)(entry->tint - RVT_TINT_ROLE))); + if (!(style_flags() & RVT_FLAG_FLAT_ICONS) || !menu_bitmap(bmap, bytes)) + return 0; + memset((uint8_t *)bmap + BMap_payload + ICON_ART_ROWS * ICON_STRIDE, 0, + (ICON_HEIGHT - ICON_ART_ROWS) * ICON_STRIDE); + return 1; +} + +static const struct rv_asset_provider provider = {replacement, replacement_read, + adjust}; + +int assets_bind(void) +{ + if (!live_count && !(style_flags() & RVT_FLAG_FLAT_ICONS)) { + assets_release(); + return 1; + } + providing = api->asset_set_provider(self, &provider) == RV_OK; + return providing; +} + +void assets_release(void) +{ + if (providing) + api->asset_set_provider(self, NULL); + providing = 0; +} diff --git a/extensions/appearance/assets.h b/extensions/appearance/assets.h new file mode 100644 index 0000000..490a24f --- /dev/null +++ b/extensions/appearance/assets.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* A theme's bitmaps for extensions: the pack's extension bitmap table as an + * index into the active look's file, and the asset provider that serves the + * core from it when it decodes an extension's bitmap, for a Settings pane or + * a canvas alike. The index is main's, since the provider answers while the + * switch module is unloaded; the switch module fills it through main_service. */ + +#ifndef ASSETS_H +#define ASSETS_H +#include "rv_api.h" +#include + +/* One bitmap of the look: where it is in the look's file, the bytes stored + * there (the whole BMap raw or as one lz stream), the bytes it decodes to and + * the tint word of the pack's table: RVT_TINT_NONE, or RVT_TINT_ROLE plus the + * role the provider paints the decoded picture in. */ +struct asset_entry { + uint32_t owner, asset, offset, bytes, decoded; + uint16_t kind; + uint8_t tint; +}; + +/* The index order: by owner, then asset. */ +static inline int asset_before(const struct asset_entry *a, uint32_t owner, + uint32_t asset) +{ + return a->owner < owner || (a->owner == owner && a->asset < asset); +} + +/* A switch builds the next index beside the active one, which answers until + * the switch succeeds: assets_reserve frees any index under construction and, + * for a count above 0, allocates one of `count` entries to fill in (owner, + * asset) order, NULL for no memory; assets_commit makes it the active one; + * assets_drop frees both. */ +struct asset_entry *assets_reserve(uint32_t count); +void assets_commit(void); +void assets_drop(void); +/* Holds the core's asset provider while the active index has entries or the + * look asks for flat icons, which also makes the core decode the bitmaps on + * screen again; releases it otherwise. 0 when the core refused. */ +int assets_bind(void); +void assets_release(void); + +#endif diff --git a/extensions/appearance/assets/LICENSE.cupertino-icons b/extensions/appearance/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/appearance/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/appearance/assets/render.py b/extensions/appearance/assets/render.py new file mode 100755 index 0000000..3674533 --- /dev/null +++ b/extensions/appearance/assets/render.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render the Settings pane icons: a Cupertino Icons glyph each, fitted into +the art box of the stock Settings icons on a 78 x 121 gray coverage mask, lit +from the top and mirrored in a fading reflection below. Drawing uses +ImageMagick's `magick`; the font (CupertinoIcons.ttf from the Flutter +`cupertino_icons` package, MIT, see LICENSE.cupertino-icons) is not in the +repository. + + python3 assets/render.py --font CupertinoIcons.ttf + python3 assets/render.py --font CupertinoIcons.ttf --check +""" + +import sys +from functools import partial +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import ART_BOTTOM, ART_TOP, glyph, icon, main + +# Icon file stem, the glyph's code point in the font, and its reach: the +# longer side of the box the glyph is fitted into, centred on the art box. +ICONS = { + "settings-appearance": (0xF7E8, 52), # sparkles + "settings-theme": (0xF72F, 52), # paintbrush_fill + "settings-accent": (0xF665, 52), # eyedropper_full + "settings-moon": (0xF719, 52), # moon_fill + "settings-covers": (0xF809, 52), # square_lefthalf_fill + "settings-cover": (0xF758, 52), # perspective, mirrored to lean like the cover +} +MIRRORED = {"settings-cover"} + + +def render(out, work, font, code, reach, mirror): + icon(out, work, glyph(work, font, code, reach, mirror), ART_TOP, ART_BOTTOM) + + +if __name__ == "__main__": + main( + __doc__, + { + HERE / f"{stem}.png": partial( + render, code=code, reach=reach, mirror=stem in MIRRORED + ) + for stem, (code, reach) in ICONS.items() + }, + font=True, + ) diff --git a/extensions/appearance/assets/settings-accent.png b/extensions/appearance/assets/settings-accent.png new file mode 100644 index 0000000000000000000000000000000000000000..675720a9d22cc78ac7998ec4be3fbad8888415a5 GIT binary patch literal 1372 zcmZ{kdpHw%7{`B9t}RK<7NebPp-pAcWE0W=bAY=A-; zpwKR8lo=XrhBVbjBF&IUQ>eSc|A0X9Rexf{*8#h;qbpKC@4p6`f1odwb|sMVb!I>Q zg&qLgPug3ba`79U9h@ic#lYl0%?}H`m^E~R>J~w6u%W+kJ9+*h31I=!`W&V8MYh*<@y`+^g|mN9jlmP)REb2hj~V&l{UVLZc;~Q znp7r!?zAjlCKj=n#AiR$t?b-w1G};RI57vmYz ziGpgQ`DNX>IE6Az>hZm)0ZcZV24{-I>TT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nl4!4=VC&YmlTgYZ7A2xs=7y(k-T4=6!&I_p!)=4OO|ag-L&4G z4M)+G#(ovVaXB!Ik|{~LM7l>YD+97DOy8Q&zpt5mKB0dkZQ0PUbAZ`ruwm-56q7T& zKHC-SJMyYCd5eT3Y%!mrh?|hNq!Ud-gIwZ7!L#V{yPk(8b?096TD|skxLMKa zRz15mq=yL;xs-oXTP_>c!>mtJ6UK-0Pywix*k}SkiV~gs{O*(%azuyVN@RrD$59! zYM4_}?}3gf2sgD1QU-SuxKtRN$EVHzK-#C!lii7`H)N%+If1N0-!n~g{3Z{voJWl|JG5$k!Cx175I zCmDjQa?0!xqDjQln||xj!O`U(Dh%yrzr~XYxnD>67?B&kCi2g@^b#S*sbRyuB-`HG zu3zCR5{^Jb&(%og3IN`VpLl6*N2e#rPZNA6pdm6HyaVqgJKTU*=Fvb|5MZuN~;?+Rv|Urcjt ziH9@aR=TDkHF{U%^pk8up?EiE8@9S8O{eTa^mISFcEgXwf)R{yY@`kZ zB`wTT0@9BvK2#aidpc@Fo2EX05yI)*Z)uwy)2_J}_fM$Jlt-ICiigzq_DfMI&1^3^ zp)c5H?_g&y3Xr`R(D7J#5W#CHtPA6`7Y+uG=IJCH5+WklCaVoi$kVrXo?gPk2U2GY z<&!2#t+ETwQ@l!V1?I?C4eSi{xIX>;E!x=hQ@9{!I>ws4p zUJ&HHupuML*SH%Ol#|2%h#sjfZcDb!5BH-2)1ec8X>+f8(?5=e8;caI&#{Z^w;L~t OUlAaaXi$Zjd)yC@(Pnx8 literal 0 HcmV?d00001 diff --git a/extensions/appearance/assets/settings-cover.png b/extensions/appearance/assets/settings-cover.png new file mode 100644 index 0000000000000000000000000000000000000000..65fe22b2f328d0b9b49b6fe3aa9b52a26cfa99fe GIT binary patch literal 1452 zcmZ{kc{mh!7{`Ck(J&G%QJ8r~A~ItV8Yy9N)Mzjw$L1JU4LN2o#xZN1iAb)PEt`yE z5o29D5rtU9pe(~C9gZAB?#0eu`#k$cf4uMKdB5-Td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F<`o8@O1TaS?83{1OUZ_mev3O literal 0 HcmV?d00001 diff --git a/extensions/appearance/assets/settings-moon.png b/extensions/appearance/assets/settings-moon.png new file mode 100644 index 0000000000000000000000000000000000000000..6de0cf1f6c3eab70a2e758fe40782a613c88fd45 GIT binary patch literal 1332 zcmZ{kdpHw%7{`AqVP(!yY~>Om8nLayu+zbIYCR+74swbczYb`kzii`h|vuMYqzI{;v30I~B&b2_RCoLw?2d_1^VWWYe4yH0eQ*Bu>@d3;*Iy2nmXkxfp02+yQ+=W8z zLZK;WlnWZ|g2dP&kuFFi1{SdYe?UAVEIK0j`vAdvYFQ1~{FlItjt@^_(&H1p&upVT zumNBloQQL$M7>zJE@eD-giC011C6m`Bt&J>uq3c(kB{EYv(5M-dcm7|1980=YDB(^ zQ4E&D$s0c>H9pUx_dwzGy6}2x&}RIF(tKVSu~4C`@uHp3A9g;Fk# zyASI?9NJD}Q*QZwVIWSgjEKv$DvP4>goRDCV(G(2y>sbP65&^~wHk^&(1#@}eNF}< z@b^@o#?<3`brEX;P>G2b2hv=tj{p!Q=kid;B_C{~CXFaGOG$Z~t+ue8DktU$emkT~ zrQKVHMj9$rAJ&{sYBKlQFw^Ydu(vUrD&U&rLYdzIllCpCIE7NWh`|X~XA#)7jWx*jctK@oTxWKLf zTJvZk@@~G^RqyxXVV^_%g|SHjA?xiie!-!h!h}*tU4`Yb#2=c%iuT6x*nj_>3Oc#4t!|-57+tBQgfCZ|$>=d13E{H5kK6 z=CzbPU)Uq8LEkE}@uk60y%SLA+zguGCaRs}ysV-PFBlp4ogG!RNH-XU);ez|iJgw+ zX_^~TP5JdT%5UT6AEf)4IA|9I7u~;g1qt2S;umPnX!&Ht>2Xgx@%}RVK5XfdXSkj5 zT?bQ#?v!Aa62o~ZqB_f;l*y#~gtW-bUVG7#-!40q9X{PQwqD0rBvQ21{K#iaHa`_6 zc=#eY}B zZZxK5s88;u_cg?!+mvrNRgBZ~ku+E>(z`r641wyNX z0$M$~IoTR)L5D4SKqvY6@>|LDd-pu4qKofev#6cBt+8?X9nZ6qg0{&VfTbOTgR3Wd z?Y8CmrB>>ry@$Hpe*MX!V9UVuOf01OmDN&QjYxbwDDDZ}I22TNJagu9&r23lWek4M zf*HuU%$sX3M-0B1qLgfkox=DCXQH7tMd@x(l4oASk)G%wSw;jGQJ#?3;K;gRW~N__ zD-_pRI8IyIZ}(Sls_xft1FN(Y5Y2uOY9e`;IR)NR+0q@o`JzGWprM6M`%<`n;Ta8` W&)(R?dMQHvR{#-D!qs_%p8XfbnOLL% literal 0 HcmV?d00001 diff --git a/extensions/appearance/assets/settings-theme.png b/extensions/appearance/assets/settings-theme.png new file mode 100644 index 0000000000000000000000000000000000000000..ef936672c0cec8f86db29baa2accb3d143c6848e GIT binary patch literal 1787 zcmZ`)c{Ce%7yZ>%v9v}8DLRPS%OpV&MoVKvNoo&ct5_=39=nzfL)v5O7&ItDEiGcE zi>jrzT53xh)KWxAErW{MTOwcn`Mz_$KjxnE-aYTWbI<$ho_EIl)M5!6as+NYXG3{10WMt+-zsUTksLB zEinMpWGbV0(@C-w&f?^%sF;*A#Hb=nkSD2-EnLXH-ef>tUy^^^zZi@eyCI$ONlD&h&{@tVC)u|4E z;G7l4%rSuZnd)}KAxgfleR+dG z3+WccW_SGan14HEqYfKmZwR*ia=LRE9*NYD9_#kGMSQsYae}4HeG& zh$>imKbSDhm#!x*a&UJ%ZD&K=G4*odpRYXkCgyX>e{V;WR_=$Co68gD|LpQgzkK%! z4yPGfwjWwX~SwgU6Enf$^->*1&EaT{Saft%3p7)>cL-rpOHBa}AUp4cCOTugxTJMy8JJzroWwHaE>-U26xRVC-3GdWS33_v)hiwAkCx$`R zmS#y^=waF~J$kw2?jgHkFwTXL*(us{Y0ga5n}YEJ6(2)(mS7DiHbKK|KRsiSo6py8 za@T9{@bZ50#@9*63xcC9%itg8~{bH`9(7|}b)E;s>RmtM(0_SWBut~Q|sJni)Fpq_~c z6$X@BXQ?5$Q{(i-l?53Ca)1SCX150V<`k6!!q%s$(bGikD_fgv=Tugy*F}f6ctrVO zE8X{>W;MVk3^R%tRHwx{Rh(o5!1+A5f$tEwAkmM;1OaWIk^Y2U5-*nj1!qF@xDCpm zsR}4wxaRzhR8aH zAq1T*Fi8timX-t7=aWpI3lz?^^ z#-~cmKxX?CjxX@oKj;aJOi-4DjAy(uI|pBo;J-$qd*KTY0^;1~!wrb@p!xx;%By8C zKXrw+!YkoW$F3Bmixt4ekozki(j!&~Pp==wl|2^G%tyl+7D zePJ&j>cCL7n$2NVy7(F5qpS-`;PjfjtFD=ej4sH)#2;2Exm9u wDUu{D+xfj}BiFdVjN2?HAM97*Cw$EIqMNoi=R>3idG7&OS>Q4C=GT7x56Y7}DgXcg literal 0 HcmV?d00001 diff --git a/extensions/appearance/catalog.c b/extensions/appearance/catalog.c new file mode 100644 index 0000000..6e4c17e --- /dev/null +++ b/extensions/appearance/catalog.c @@ -0,0 +1,233 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "catalog.h" +#include "osos-2.0.5.h" +#include "pixel.h" + +struct contrast_text { + uint32_t first; + uint16_t count, index; +}; + +struct accent_art { + uint16_t index; + uint8_t role; +}; + +/* catalog_offsets[i] is bitmap i's offset from the bank base, word aligned, + * with the padding that follows it in the low two bits; the last entry ends + * the bank. */ +#include "catalog.inc" +_Static_assert(sizeof contrast_text / sizeof *contrast_text == CATALOG_CONTRAST_TEXTS, + "catalog.h names the contrast text count"); + +static uint32_t offset_of(uint32_t index) +{ + return catalog_offsets[index] & ~3u; +} + +uint32_t catalog_count(void) +{ + return CATALOG_COUNT; +} + +const uint8_t *catalog_fingerprint(void) +{ + return fingerprint; +} + +uint8_t *catalog_data(uint32_t index) +{ + return (uint8_t *)CATALOG_BASE + offset_of(index); +} + +uint32_t catalog_size(uint32_t index) +{ + return offset_of(index + 1) - offset_of(index) - (catalog_offsets[index] & 3u); +} + +uint32_t catalog_crc(uint32_t index) +{ + return catalog_crcs[index]; +} + +uint32_t catalog_file_offset(uint32_t index) +{ + return CATALOG_FILE_OFFSET + offset_of(index); +} + +/* A BMap: the header's format, stride, depth and bounds, then its data length + * word right before the data, which a bank bitmap holds at BMap_payload_bytes + * or one word later; then for paletted formats the colour count and the BGRA + * palette, then the rows. The bounds start at the origin. */ +int catalog_layout(uint32_t index, struct layout *b) +{ + if (index >= CATALOG_COUNT || index >= RVT_CATALOG_MAX) + return 0; + uint32_t size = catalog_size(index); + const uint8_t *p = catalog_data(index); + if (size < RVT_BMAP_HEADER_BYTES) + return 0; + b->start = le32(p + BMap_payload_bytes) == size - BMap_payload ? BMap_payload + : BMap_payload + 4; + if (size < b->start || le32(p + b->start - 4) != size - b->start) + return 0; + uint32_t format = le16(p + BMap_format); + b->mask = format == BMapFormat_Mask4 || format == BMapFormat_Mask8; + b->depth = format == BMapFormat_Mask4 ? 4 + : format == BMapFormat_Mask8 || format == BMapFormat_Indexed8 ? 8 + : format == BMapFormat_Indexed16 || format == BMapFormat_RGB565 ? 16 + : format == BMapFormat_BGRA8888 ? 32 + : 0; + b->stride = le16(p + BMap_stride); + b->height = le32(p + BMap_bounds + 8); + b->width = le32(p + BMap_bounds + 12); + b->colors = 0; + if (le32(p + BMap_bounds) || le32(p + BMap_bounds + 4)) + return 0; + if (!b->depth || le16(p + BMap_depth) != b->depth || !b->width || !b->height || + !b->stride || b->width > 0xffffu || b->height > 0xffffu || + b->width * b->depth > b->stride * 8) + return 0; + if (format == BMapFormat_Indexed8 || format == BMapFormat_Indexed16) { + if (size - b->start < 4) + return 0; + b->colors = le32(p + b->start); + b->start += 4; + if (!b->colors || b->colors > (1u << b->depth) || + b->colors > (size - b->start) / 4) + return 0; + } + b->pixels = b->start + b->colors * 4; + return b->pixels <= size && b->height * b->stride == size - b->pixels; +} + +/* The last answers: a screen draws the same few bitmaps again and again. */ +enum { RECENT = 8 }; + +static struct { + const uint8_t *pixels; + uint32_t index; +} recent[RECENT]; + +static unsigned recent_next; + +static int catalog_contains(const uint8_t *pixels) +{ + const uint8_t *base = (const uint8_t *)CATALOG_BASE; + return pixels >= base && pixels < base + CATALOG_BANK_BYTES; +} + +int catalog_from_pixels(const uint8_t *pixels, uint32_t *index) +{ + const uint8_t *base = (const uint8_t *)CATALOG_BASE; + if (!catalog_contains(pixels) || pixels < base + RVT_BMAP_HEADER_BYTES) + return 0; + for (unsigned i = 0; i < RECENT; i++) + if (recent[i].pixels == pixels) { + *index = recent[i].index; + return 1; + } + /* The header the pixels follow, found by bisection over the offsets. */ + uint32_t at = (uint32_t)(pixels - base) - RVT_BMAP_HEADER_BYTES, low = 0, + high = CATALOG_COUNT; + while (high - low > 1) { + uint32_t mid = (low + high) / 2; + if (offset_of(mid) <= at) + low = mid; + else + high = mid; + } + struct layout b; + if (offset_of(low) != at || !catalog_layout(low, &b)) + return 0; + recent[recent_next].pixels = pixels; + recent[recent_next].index = low; + recent_next = (recent_next + 1) % RECENT; + *index = low; + return 1; +} + +uint8_t *catalog_palette(uint32_t index, uint32_t *colors) +{ + struct layout b; + if (!catalog_layout(index, &b) || !b.colors) + return 0; + *colors = b.colors; + return catalog_data(index) + b.start; +} + +uint8_t *catalog_argb(uint32_t index, uint32_t *width, uint32_t *height, + uint32_t *stride) +{ + struct layout b; + if (!catalog_layout(index, &b) || b.depth != 32) + return 0; + *width = b.width; + *height = b.height; + *stride = b.stride; + return catalog_data(index) + b.pixels; +} + +int catalog_center_pixel(uint32_t index, uint8_t out[4]) +{ + struct layout b; + if (!catalog_layout(index, &b) || b.mask || (b.depth == 16 && !b.colors)) + return 0; + const uint8_t *data = catalog_data(index); + const uint8_t *row = data + b.pixels + ((b.height - 1) / 2) * b.stride; + const uint8_t *pixel; + if (b.colors) { + uint32_t column = (b.width - 1) / 2; + uint32_t entry = b.depth == 16 ? le16(row + column * 2) : row[column]; + if (entry >= b.colors) + return 0; + pixel = data + b.start + entry * 4; + } else { + pixel = row + ((b.width - 1) / 2) * 4; + } + if (!pixel[3]) + return 0; + out[0] = pixel[2]; + out[1] = pixel[1]; + out[2] = pixel[0]; + out[3] = 255; + return 1; +} + +uint32_t catalog_well_center(unsigned well) +{ + return well_centers[well < WELLS ? well : 0]; +} + +uint32_t catalog_field_center(void) +{ + return field_center; +} + +uint32_t catalog_calendar_cell(unsigned place) +{ + return calendar_cells[place < CALENDAR_CELLS ? place : 0]; +} + +int catalog_accent_art(uint32_t i, uint32_t *index, uint8_t *role) +{ + if (i >= sizeof accent_art / sizeof *accent_art) + return 0; + *index = accent_art[i].index; + *role = accent_art[i].role; + return 1; +} + +int catalog_contrast_text(uint32_t view) +{ + for (uint32_t i = 0; i < CATALOG_CONTRAST_TEXTS; i++) + if (view - contrast_text[i].first < contrast_text[i].count) + return (int)i; + return -1; +} + +uint32_t catalog_contrast_art(unsigned entry) +{ + return contrast_text[entry < CATALOG_CONTRAST_TEXTS ? entry : 0].index; +} diff --git a/extensions/appearance/catalog.h b/extensions/appearance/catalog.h new file mode 100644 index 0000000..3f8e63b --- /dev/null +++ b/extensions/appearance/catalog.h @@ -0,0 +1,91 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The firmware's bitmap bank: Apple's BMaps lie one after another in RAM, + * word aligned, in catalog order. The catalog (catalog.inc, generated from the + * themes directory's osos-2.0.5.json) gives each bitmap's offset in the bank + * and its stock checksum, and names the ones the extension treats specially. */ + +#ifndef CATALOG_H +#define CATALOG_H +#include "rvt.h" +#include + +#define BITMAP_WORDS (RVT_CATALOG_MAX / 32) + +/* Where a bitmap's bytes are: the palette or pixels start at `start`, the + * pixels at `pixels`; `colors` is the palette size, 0 without one; `mask` for + * the coverage formats the system colours while drawing. */ +struct layout { + uint32_t start, pixels, colors, stride, width, height, depth, mask; +}; + +static inline int same_layout(const struct layout *a, const struct layout *b) +{ + return a->start == b->start && a->pixels == b->pixels && a->colors == b->colors && + a->stride == b->stride && a->width == b->width && a->height == b->height && + a->depth == b->depth && a->mask == b->mask; +} + +uint32_t catalog_count(void); +const uint8_t *catalog_fingerprint(void); +uint8_t *catalog_data(uint32_t index); +uint32_t catalog_size(uint32_t index); +/* The low 16 bits of the stock bytes' CRC-32. */ +uint32_t catalog_crc(uint32_t index); +/* The offset of a bitmap's bytes in the firmware file. */ +uint32_t catalog_file_offset(uint32_t index); +/* 0 for an index past the catalog or a header that does not describe the + * bitmap's bytes. */ +int catalog_layout(uint32_t index, struct layout *b); +/* The catalog index of the bitmap whose pixel data starts at `pixels`. */ +int catalog_from_pixels(const uint8_t *pixels, uint32_t *index); +/* The resident BGRA palette of a paletted bitmap, or NULL. */ +uint8_t *catalog_palette(uint32_t index, uint32_t *colors); +/* The resident BGRA rows of an ARGB bitmap, or NULL. */ +uint8_t *catalog_argb(uint32_t index, uint32_t *width, uint32_t *height, + uint32_t *stride); +/* The opaque RGBA of the centre pixel of a paletted or ARGB bitmap; 0 for + * masks, RGB565, a bad layout or a clear pixel. */ +int catalog_center_pixel(uint32_t index, uint8_t out[4]); + +/* Option bar wells, which the keyboard and the option bars draw their labels + * on: white and black take the look, Now Playing's shuffle selector has its + * own colours, and its labels follow a theme or Classic dark. */ +enum { WELL_WHITE, WELL_BLACK, WELL_NOW_PLAYING, WELLS }; + +uint32_t catalog_well_center(unsigned well); +/* The Search input field's middle slice. */ +uint32_t catalog_field_center(void); + +/* Calendar day cells by what they show, then the page the weekday names sit + * on, which is no cell. */ +enum calendar_place { + CALENDAR_ACTIVE, + CALENDAR_INACTIVE, + CALENDAR_HILITE, + CALENDAR_CELLS, + CALENDAR_HEADER = CALENDAR_CELLS +}; + +/* The bitmap of a cell place, below CALENDAR_CELLS. */ +uint32_t catalog_calendar_cell(unsigned place); +/* Stock blue art that follows the accent: entry i's index and role; 0 past the end. */ +int catalog_accent_art(uint32_t i, uint32_t *index, uint8_t *role); +/* Labels drawn in a fixed colour over art: the entry (below + * CATALOG_CONTRAST_TEXTS) a view id belongs to, -1 for other views, and the + * art behind an entry. */ +#define CATALOG_CONTRAST_TEXTS 5 +int catalog_contrast_text(uint32_t view); +uint32_t catalog_contrast_art(unsigned entry); + +static inline int bit_test(const uint32_t *bits, uint32_t index) +{ + return (bits[index / 32] >> (index % 32)) & 1; +} + +static inline void bit_set(uint32_t *bits, uint32_t index) +{ + bits[index / 32] |= 1u << (index % 32); +} + +#endif diff --git a/extensions/appearance/crc.c b/extensions/appearance/crc.c new file mode 100644 index 0000000..dc8ce23 --- /dev/null +++ b/extensions/appearance/crc.c @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "crc.h" + +/* Polynomial 0xedb88320, four bits at a time. */ +static const uint32_t crc_nibbles[16] = { + 0x00000000u, 0x1db71064u, 0x3b6e20c8u, 0x26d930acu, 0x76dc4190u, 0x6b6b51f4u, + 0x4db26158u, 0x5005713cu, 0xedb88320u, 0xf00f9344u, 0xd6d6a3e8u, 0xcb61b38cu, + 0x9b64c2b0u, 0x86d3d2d4u, 0xa00ae278u, 0xbdbdf21cu, +}; + +uint32_t crc32_update(uint32_t crc, const void *data, uint32_t size) +{ + const uint8_t *p = data; + while (size--) { + crc ^= *p++; + crc = (crc >> 4) ^ crc_nibbles[crc & 15u]; + crc = (crc >> 4) ^ crc_nibbles[crc & 15u]; + } + return crc; +} diff --git a/extensions/appearance/crc.h b/extensions/appearance/crc.h new file mode 100644 index 0000000..0c2a3e9 --- /dev/null +++ b/extensions/appearance/crc.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef CRC_H +#define CRC_H +#include + +/* Reflected CRC-32 over an inverted seed: start from 0xffffffff, invert the + * result. The main module holds the one copy; the switch module calls it + * through main_service. */ +uint32_t crc32_update(uint32_t crc, const void *data, uint32_t size); + +#endif diff --git a/extensions/appearance/dark_mode.c b/extensions/appearance/dark_mode.c new file mode 100644 index 0000000..6e6807b --- /dev/null +++ b/extensions/appearance/dark_mode.c @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "dark_mode.h" +#include "look.h" +#include "schedule.h" +#include "style.h" + +const char *const dark_mode_labels[3] = {"Auto", "On", "Off"}; +static int choice = DARK_OFF; + +void dark_mode_set(int value) +{ + choice = value; +} + +int dark_mode_auto(void) +{ + return choice == DARK_AUTO; +} + +int dark_mode_wanted(void) +{ + struct schedule s; + if (choice != DARK_AUTO) + return choice == DARK_ON; + schedule_read(&s); + return schedule_night(&s); +} + +const char *dark_mode_caption(void) +{ + const char *problem = look_problem(PANE_DARK), *note = look_appearance_note(); + if (problem) + return problem; + if (note) + return note; + if (choice == DARK_AUTO) + return schedule_caption(); + return style_dark() ? "On" : "Off"; +} diff --git a/extensions/appearance/dark_mode.h b/extensions/appearance/dark_mode.h new file mode 100644 index 0000000..b7ea8f5 --- /dev/null +++ b/extensions/appearance/dark_mode.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef DARK_MODE_H +#define DARK_MODE_H + +/* Dark Mode: Auto from sunset to sunrise by the schedule, On or Off. The + * look on the screen is the switch's business; this is what the setting + * asks for. */ +enum { DARK_AUTO, DARK_ON, DARK_OFF }; + +extern const char *const dark_mode_labels[3]; +void dark_mode_set(int mode); +int dark_mode_auto(void); +/* Whether the setting asks for the dark appearance right now. */ +int dark_mode_wanted(void); +const char *dark_mode_caption(void); + +#endif diff --git a/extensions/appearance/derive.c b/extensions/appearance/derive.c new file mode 100644 index 0000000..d316bed --- /dev/null +++ b/extensions/appearance/derive.c @@ -0,0 +1,393 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "derive.h" +#include "pixel.h" +#include "rv_libc.h" +#include "switch.h" + +enum { ONE = 256, FULL = 255, GRAY_MAP = 256 }; + +static int luma(const uint8_t *bgra) +{ + return (77 * bgra[2] + 150 * bgra[1] + 29 * bgra[0]) >> 8; +} + +static int is_565(const struct layout *b) +{ + return b->depth == 16 && !b->colors && !b->mask; +} + +/* A BGRA entry or pixel as the RGBA word the tables are keyed by. */ +static uint32_t key_bgra(const uint8_t *p) +{ + return p[2] | (uint32_t)p[1] << 8 | (uint32_t)p[0] << 16 | (uint32_t)p[3] << 24; +} + +static uint32_t key_565(uint32_t w) +{ + uint8_t rgb[3]; + rgb565_unpack(w, rgb); + return rgb[0] | (uint32_t)rgb[1] << 8 | (uint32_t)rgb[2] << 16 | 0xff000000u; +} + +static uint32_t index_at(const struct layout *b, const uint8_t *rows, uint32_t x, + uint32_t y) +{ + const uint8_t *row = rows + y * b->stride; + return b->depth == 8 ? row[x] : le16(row + x * 2); +} + +static void set_index(const struct layout *b, uint8_t *rows, uint32_t x, uint32_t y, + uint32_t v) +{ + uint8_t *row = rows + y * b->stride; + if (b->depth == 8) { + row[x] = (uint8_t)v; + } else { + row[x * 2] = (uint8_t)v; + row[x * 2 + 1] = (uint8_t)(v >> 8); + } +} + +/* The pair whose `from` is `k`, or NULL. */ +static const uint8_t *lookup(const uint8_t *table, uint32_t count, uint32_t k) +{ + uint32_t low = 0, high = count; + while (low < high) { + uint32_t mid = (low + high) / 2, at = le32(table + mid * 8); + if (at == k) + return table + mid * 8 + 4; + if (at < k) + low = mid + 1; + else + high = mid; + } + return NULL; +} + +static int exact_565(const uint8_t *rgba) +{ + return !(rgba[0] & 7) && !(rgba[1] & 3) && !(rgba[2] & 7) && rgba[3] == 255; +} + +int derive_recolor(uint32_t asset, const struct layout *b, const uint8_t *table, + uint32_t count) +{ + uint8_t *data = main_module->catalog_data(asset); + if (b->mask || !count || count > RVT_RECOLOR_MAX) + return 0; + for (uint32_t i = 0; i < count; i++) { + const uint8_t *pair = table + i * 8; + if ((i && le32(pair) <= le32(pair - 8)) || le32(pair) == le32(pair + 4) || + (is_565(b) && !(exact_565(pair) && exact_565(pair + 4)))) + return 0; + } + if (b->colors) { + uint8_t *entry = data + b->start; + for (uint32_t i = 0; i < b->colors; i++, entry += 4) { + const uint8_t *to = lookup(table, count, key_bgra(entry)); + if (to) + entry[0] = to[2], entry[1] = to[1], entry[2] = to[0], entry[3] = to[3]; + } + return 1; + } + uint8_t *row = data + b->pixels; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) { + if (is_565(b)) { + uint8_t *p = row + x * 2; + const uint8_t *to = lookup(table, count, key_565(le16(p))); + if (to) { + uint32_t w = rgb565_pack(to); + p[0] = (uint8_t)w, p[1] = (uint8_t)(w >> 8); + } + } else { + uint8_t *p = row + x * 4; + const uint8_t *to = lookup(table, count, key_bgra(p)); + if (to) + p[0] = to[2], p[1] = to[1], p[2] = to[0], p[3] = to[3]; + } + } + return 1; +} + +int derive_invert(uint32_t asset, const struct layout *b) +{ + uint8_t *data = main_module->catalog_data(asset); + if (b->mask) + return 0; + if (b->colors) { + uint8_t *entry = data + b->start; + for (uint32_t i = 0; i < b->colors; i++, entry += 4) + entry[0] ^= 255, entry[1] ^= 255, entry[2] ^= 255; + return 1; + } + uint8_t *row = data + b->pixels; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) { + uint8_t *p = row + x * (b->depth / 8); + if (is_565(b)) + p[0] ^= 255, p[1] ^= 255; + else if (p[3]) + p[0] ^= 255, p[1] ^= 255, p[2] ^= 255; + } + return 1; +} + +/* Relight words: see enum rvt_relight. */ +enum { + DEAD = RVT_RELIGHT_T_ZERO, + K = RVT_RELIGHT_T_FULL, + BG_BASE = RVT_RELIGHT_BG_BASE, + BG_REF = RVT_RELIGHT_BG_REF, + BG_SLOPE = RVT_RELIGHT_BG_SLOPE, + BG_LO = RVT_RELIGHT_BG_LO, + BG_HI = RVT_RELIGHT_BG_HI, + ICON_BASE = RVT_RELIGHT_ICON_BASE, + ICON_LUMA = RVT_RELIGHT_ICON_LUMA, + ICON_ROW = RVT_RELIGHT_ICON_ROW, + ICON_LO = RVT_RELIGHT_ICON_LO, + ICON_HI = RVT_RELIGHT_ICON_HI, +}; + +/* The words a product can take without overflowing 32 bits: offsets and + * lumas are at most 255 in 8.8, rows below RVT_SCRATCH_PIXELS. */ +enum { + LEVEL_MAX = 255 * ONE, + BASE_MAX = 1024 * ONE, + SLOPE_MAX = 16 * ONE, +}; + +static int within(int32_t value, int32_t bound) +{ + return value >= -bound && value <= bound; +} + +static int relight_valid(const struct layout *b, const int32_t *p) +{ + int32_t levels = ((p[ICON_HI] + ONE / 2) >> 8) - (p[BG_LO] >> 8) + 1; + return b->colors && b->width * b->height <= RVT_SCRATCH_PIXELS && 0 <= p[DEAD] && + p[DEAD] < p[K] && p[K] <= LEVEL_MAX && within(p[BG_BASE], BASE_MAX) && + within(p[BG_REF], LEVEL_MAX) && within(p[BG_SLOPE], SLOPE_MAX) && + within(p[ICON_BASE], BASE_MAX) && within(p[ICON_LUMA], LEVEL_MAX) && + within(p[ICON_ROW], LEVEL_MAX) && 0 <= p[BG_LO] && p[BG_LO] <= p[BG_HI] && + p[BG_HI] <= p[ICON_LO] && p[ICON_LO] <= p[ICON_HI] && + p[ICON_HI] <= LEVEL_MAX && levels <= (int32_t)b->colors; +} + +static int32_t offset_from(const uint8_t *c, const uint8_t *bg) +{ + int32_t o = 0; + for (unsigned i = 0; i < 3; i++) { + int32_t d = c[i] > bg[i] ? c[i] - bg[i] : bg[i] - c[i]; + o = d > o ? d : o; + } + return o * ONE; +} + +int derive_relight(uint32_t asset, const struct layout *b, const int32_t *p, + uint8_t *scratch) +{ + uint8_t *data = main_module->catalog_data(asset), *palette = data + b->start; + uint8_t *rows = data + b->pixels; + uint32_t w = b->width, h = b->height; + uint8_t *t = scratch, *map = scratch + RVT_SCRATCH_PIXELS; + if (!relight_valid(b, p)) + return 0; + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) + if (index_at(b, rows, x, y) >= b->colors) + return 0; + uint64_t range = reciprocal((uint32_t)(p[K] - p[DEAD])); + /* Coverage, then shadows: a partly covered pixel with no fully covered + * neighbour. Pruning in place is safe because only full pixels count as + * neighbours and pruning never creates one. */ + for (uint32_t y = 0; y < h; y++) { + const uint8_t *bg = palette + index_at(b, rows, 0, y) * 4; + for (uint32_t x = 0; x < w; x++) { + int32_t o = offset_from(palette + index_at(b, rows, x, y) * 4, bg); + t[y * w + x] = + (uint8_t)(o <= p[DEAD] ? 0 + : o >= p[K] ? FULL + : divide((uint32_t)(o - p[DEAD]) * FULL, range)); + } + } + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) { + if (!t[y * w + x] || t[y * w + x] == FULL) + continue; + int solid = 0; + for (int dy = -1; dy <= 1; dy++) + for (int dx = -1; dx <= 1; dx++) { + int32_t nx = (int32_t)x + dx, ny = (int32_t)y + dy; + if ((dx || dy) && nx >= 0 && ny >= 0 && nx < (int32_t)w && + ny < (int32_t)h && t[ny * w + nx] == FULL) + solid = 1; + } + if (!solid) + t[y * w + x] = 0; + } + /* The grays overwrite the coverage in place; the palette is read here and + * rewritten only after this pass. */ + for (uint32_t y = 0; y < h; y++) { + const uint8_t *bg = palette + index_at(b, rows, 0, y) * 4; + int32_t bgd = p[BG_BASE] + (luma(bg) * ONE - p[BG_REF]) * p[BG_SLOPE] / ONE; + bgd = clamp(bgd, p[BG_LO], p[BG_HI]); + for (uint32_t x = 0; x < w; x++) { + const uint8_t *c = palette + index_at(b, rows, x, y) * 4; + int32_t icon = + p[ICON_BASE] + p[ICON_LUMA] * luma(c) + p[ICON_ROW] * (int32_t)y; + icon = clamp(icon, p[ICON_LO], p[ICON_HI]); + int32_t mixed = + bgd + (int32_t)divide((uint32_t)(icon - bgd) * t[y * w + x] + FULL / 2, + reciprocal(FULL)); + t[y * w + x] = (uint8_t)((mixed + ONE / 2) >> 8); + } + } + memset(map, 0, GRAY_MAP); + for (uint32_t i = 0; i < w * h; i++) + map[t[i]] = 1; + uint32_t n = 0; + for (uint32_t g = 0; g < GRAY_MAP; g++) + if (map[g]) { + if (n == b->colors) { + /* More grays than entries: a half-written bitmap, zeroed for the caller. */ + memset(data + b->start, 0, main_module->catalog_size(asset) - b->start); + return 0; + } + palette[n * 4] = palette[n * 4 + 1] = palette[n * 4 + 2] = (uint8_t)g; + palette[n * 4 + 3] = 255; + map[g] = (uint8_t)n++; + } + memset(palette + n * 4, 0, (b->colors - n) * 4); + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) + set_index(b, rows, x, y, map[t[y * w + x]]); + return 1; +} + +/* The RGBA of a source pixel, whatever its format. */ +static void source_pixel(const struct layout *s, const uint8_t *data, uint32_t x, + uint32_t y, uint8_t rgba[4]) +{ + const uint8_t *p; + if (s->colors) { + p = data + s->start + index_at(s, data + s->pixels, x, y) * 4; + } else if (is_565(s)) { + rgb565_unpack(le16(data + s->pixels + y * s->stride + x * 2), rgba); + rgba[3] = 255; + return; + } else { + p = data + s->pixels + y * s->stride + x * 4; + } + rgba[0] = p[2], rgba[1] = p[1], rgba[2] = p[0], rgba[3] = p[3]; +} + +int derive_alias(uint32_t asset, const struct layout *b, uint32_t source) +{ + struct layout s; + uint8_t *data = main_module->catalog_data(asset); + if (source == asset || !main_module->catalog_layout(source, &s) || b->mask || + s.mask || b->width != s.width || b->height != s.height) + return 0; + const uint8_t *from = main_module->catalog_data(source); + if (same_layout(b, &s) && + main_module->catalog_size(asset) == main_module->catalog_size(source)) { + memcpy(data + b->start, from + s.start, + main_module->catalog_size(asset) - b->start); + return 1; + } + if (b->width * b->height > RVT_SCRATCH_PIXELS) + return 0; + if (s.colors) + for (uint32_t y = 0; y < s.height; y++) + for (uint32_t x = 0; x < s.width; x++) + if (index_at(&s, from + s.pixels, x, y) >= s.colors) + return 0; + uint8_t *palette = data + b->start, *rows = data + b->pixels; + uint32_t n = 0; + for (uint32_t y = 0; y < b->height; y++) + for (uint32_t x = 0; x < b->width; x++) { + uint8_t rgba[4]; + source_pixel(&s, from, x, y, rgba); + if (b->colors) { + uint8_t bgra[4] = {rgba[2], rgba[1], rgba[0], rgba[3]}; + uint32_t i = 0; + while (i < n && memcmp(palette + i * 4, bgra, 4)) + i++; + if (i == n) { + if (n == b->colors) { + /* Out of palette entries: a half-written bitmap, zeroed for the caller. */ + memset(data + b->start, 0, + main_module->catalog_size(asset) - b->start); + return 0; + } + memcpy(palette + n++ * 4, bgra, 4); + } + set_index(b, rows, x, y, i); + } else if (is_565(b)) { + uint32_t w = rgb565_pack(rgba); + uint8_t *p = rows + y * b->stride + x * 2; + p[0] = (uint8_t)w, p[1] = (uint8_t)(w >> 8); + } else { + uint8_t *p = rows + y * b->stride + x * 4; + p[0] = rgba[2], p[1] = rgba[1], p[2] = rgba[0], p[3] = rgba[3]; + } + } + if (b->colors) + memset(palette + n * 4, 0, (b->colors - n) * 4); + return 1; +} + +/* A coverage level of `full` with the solid floor applied: full from the + * floor up, the floor scaled to the level range. */ +static unsigned solid_level(unsigned level, unsigned full) +{ + return level * FULL >= RVT_SOLID_FLOOR * full ? full : level; +} + +/* One BGRA colour's alpha as tint coverage: as it is, scaled by how dark the + * colour is when the tint reads coverage from darkness, or made full from the + * floor up when it is solid. */ +static void coverage_of(uint8_t *bgra, int darkness, int solid) +{ + if (darkness) + bgra[3] = (uint8_t)div255((unsigned)bgra[3] * (unsigned)(255 - luma(bgra))); + if (solid) + bgra[3] = (uint8_t)solid_level(bgra[3], FULL); +} + +static void solid_mask(const struct layout *b, uint8_t *row) +{ + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) { + if (b->depth == 8) { + row[x] = (uint8_t)solid_level(row[x], FULL); + } else { + unsigned shift = x % 2 ? 0 : 4; + unsigned level = solid_level((row[x / 2] >> shift) & 15, 15); + row[x / 2] = (uint8_t)((row[x / 2] & ~(15u << shift)) | level << shift); + } + } +} + +int derive_coverage(uint32_t asset, const struct layout *b, int darkness, int solid) +{ + uint8_t *data = main_module->catalog_data(asset); + if (is_565(b) || (b->mask && (darkness || !solid))) + return 0; + if (b->mask) { + solid_mask(b, data + b->pixels); + return 1; + } + if (b->colors) { + for (uint32_t i = 0; i < b->colors; i++) + coverage_of(data + b->start + i * 4, darkness, solid); + return 1; + } + uint8_t *row = data + b->pixels; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) + coverage_of(row + x * 4, darkness, solid); + return 1; +} diff --git a/extensions/appearance/derive.h b/extensions/appearance/derive.h new file mode 100644 index 0000000..3ff4ddd --- /dev/null +++ b/extensions/appearance/derive.h @@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Derived art: a bitmap computed in place from the stock bytes it holds, + * which pack_apply has made sure of first. Every function takes the bitmap's + * layout from catalog_layout and returns 0 when the record does not fit the + * bitmap, before writing anything. */ + +#ifndef DERIVE_H +#define DERIVE_H +#include "catalog.h" +#include + +/* `table` holds `count` pairs {from RGBA, to RGBA} ascending by `from` as a + * little-endian word; matching palette entries, ARGB pixels or RGB565 words + * take their `to`. */ +int derive_recolor(uint32_t asset, const struct layout *b, const uint8_t *table, + uint32_t count); +/* RGB inverted, alpha kept; not for masks. */ +int derive_invert(uint32_t asset, const struct layout *b); +/* The relight rule of rvt.h over a paletted bitmap; `scratch` is + * RVT_SCRATCH_BYTES. */ +int derive_relight(uint32_t asset, const struct layout *b, const int32_t *rule, + uint8_t *scratch); +/* The source's pixels as it holds them now: a byte copy for an equal layout, + * else re-encoded, for which the bitmap is at most RVT_SCRATCH_PIXELS; the + * same size, neither a mask, and a paletted bitmap needs room for the + * source's colours. */ +int derive_alias(uint32_t asset, const struct layout *b, uint32_t source); +/* A tinted bitmap without a record: its coverage as the tint paints it. On a + * paletted or ARGB bitmap the alpha, as it is or, with `darkness`, scaled to + * alpha x (255 - luma) / 255; with `solid` every level from RVT_SOLID_FLOOR + * up becomes full, on a mask's levels too. A mask takes `solid` only. */ +int derive_coverage(uint32_t asset, const struct layout *b, int darkness, int solid); + +#endif diff --git a/extensions/appearance/ext.h b/extensions/appearance/ext.h new file mode 100644 index 0000000..df83be1 --- /dev/null +++ b/extensions/appearance/ext.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef EXT_H +#define EXT_H +#include "rv_api.h" +#include + +/* The core's table and this extension's handle, set by each module's entry. */ +extern const struct rv_api *api; +extern rv_extension_handle self; + +/* The settings. KEY_AVAILABLE shows the Appearance row: on from load until a + * failed restore turns theming off for the session. */ +enum { + KEY_THEME = 1, /* string: the theme id, empty for Classic */ + KEY_DARK, /* choice: Auto, On, Off */ + KEY_ACCENT, /* choice */ + KEY_MENU_COVERS, /* choice: Theme, On, Off */ + KEY_AVAILABLE, /* bool without a row */ + KEY_NOW_PLAYING_COVER, /* choice: Theme, Tilted, Flat */ +}; + +/* The manual module that streams a switch, by its index in the manifest. */ +#define SWITCH_MODULE 1 + +/* Exactly `bytes` of `file` into `out`. */ +static inline int read_exact(struct rv_file *file, void *out, uint32_t bytes) +{ + uint32_t got = 0; + return api->file_read(self, file, out, bytes, &got) == RV_OK && got == bytes; +} + +#endif diff --git a/extensions/appearance/flat_cover.c b/extensions/appearance/flat_cover.c new file mode 100644 index 0000000..bb2f187 --- /dev/null +++ b/extensions/appearance/flat_cover.c @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Now Playing draws its cover with GLES into a 320 by 240 RGB565 buffer: the + * tilted, reflected artwork, then smoothed lines along its edges. A flat look + * copies the artwork's pixels into the buffer instead, face on and unscaled + * where the stock cover starts, and skips the edge lines. The look asks for + * it with a flag; the Now Playing Cover setting can say otherwise. */ + +#include "flat_cover.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "rvt.h" +#include "style.h" +#include + +enum { + TARGET_WIDTH = 320, + ART_SIZE = 128, + ART_STRIDE = ART_SIZE * 2, + FLAT_X = 18, + FLAT_Y = 38 +}; + +const char *const now_playing_cover_labels[3] = {"Theme", "Tilted", "Flat"}; +static int cover_choice; /* the setting */ +static void * + drawing_view; /* the album art view inside its draw, where the renderer is called */ + +void flat_cover_set(int value) +{ + cover_choice = value; +} + +int flat_cover_flat(void) +{ + if (cover_choice == NP_COVER_THEME) + return style_flags() & RVT_FLAG_FLAT_NOW_PLAYING; + return cover_choice == NP_COVER_FLAT; +} + +uint32_t flat_cover_view_draw(uint32_t view, uint32_t argument, uint32_t clip, + const void *next) +{ + drawing_view = (void *)view; + uint32_t result = api->hook_next(next, view, argument, clip, 0, 0, 0); + drawing_view = NULL; + return result; +} + +/* The stock cover is a 128 by 128 RGB565 bitmap with packed rows; any other + * image keeps the stock drawing. */ +static int copyable(const uint8_t *image) +{ + const int32_t *bounds = (const int32_t *)(image + Bitmap_bounds); + return RV_FIELD(image, Bitmap_format, uint16_t) == BMapFormat_RGB565 && + RV_FIELD(image, Bitmap_stride, uint32_t) == ART_STRIDE && + bounds[2] - bounds[0] == ART_SIZE && bounds[3] - bounds[1] == ART_SIZE; +} + +uint32_t flat_cover_renderer_draw(uint32_t renderer, const void *next) +{ + if (!flat_cover_flat() || !drawing_view) + return api->hook_next(next, renderer, 0, 0, 0, 0, 0); + const uint8_t *image = GLAlbumArtView_GetImage(drawing_view); + void *buffer = NULL; + if (image) + GameGraphics_GetCurrentPixelBuffer(&buffer); + if (!image || !buffer || !copyable(image)) + return api->hook_next(next, renderer, 0, 0, 0, 0, 0); + const uint16_t *pixels = RV_FIELD(image, Bitmap_pixels, const uint16_t *); + uint16_t *target = (uint16_t *)buffer + FLAT_Y * TARGET_WIDTH + FLAT_X; + for (int row = 0; row < ART_SIZE; row++, target += TARGET_WIDTH) + for (int column = 0; column < ART_SIZE; column++) + target[column] = *pixels++; + return 0; +} + +uint32_t flat_cover_edge_lines(uint32_t buffer, const void *next) +{ + return flat_cover_flat() ? 0 : api->hook_next(next, buffer, 0, 0, 0, 0, 0); +} diff --git a/extensions/appearance/flat_cover.h b/extensions/appearance/flat_cover.h new file mode 100644 index 0000000..c91364e --- /dev/null +++ b/extensions/appearance/flat_cover.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef FLAT_COVER_H +#define FLAT_COVER_H +#include + +/* The Now Playing cover drawn face on. The setting is Theme (what the look + * says; stock tilts it), Tilted or Flat. */ +enum { NP_COVER_THEME, NP_COVER_TILTED, NP_COVER_FLAT }; + +extern const char *const now_playing_cover_labels[3]; +void flat_cover_set(int choice); +int flat_cover_flat(void); +uint32_t flat_cover_view_draw(uint32_t view, uint32_t argument, uint32_t clip, + const void *next); +uint32_t flat_cover_renderer_draw(uint32_t renderer, const void *next); +uint32_t flat_cover_edge_lines(uint32_t buffer, const void *next); + +#endif diff --git a/extensions/appearance/latch.c b/extensions/appearance/latch.c new file mode 100644 index 0000000..b136354 --- /dev/null +++ b/extensions/appearance/latch.c @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "latch.h" +#include "ext.h" +#include "rv_sites.h" +#include "rv_ui.h" + +static int loading, + latched; /* a switch runs; presses are held off and the watch is bound */ + +static uint32_t process_message(uint32_t wait, uint32_t quit, const void *next); +static const struct rv_hook watch = + RV_HOOK_FILTER(RV_SITE_UI_ProcessMessage_call, process_message); + +/* (wait, quit): one turn of the message loop; the result says a message was + * handled. The first idle turn after the switch opens the latch and ends the + * watch: a handler may unbind itself once hook_next has returned. */ +static uint32_t process_message(uint32_t wait, uint32_t quit, const void *next) +{ + uint32_t handled = api->hook_next(next, wait, quit, 0, 0, 0, 0); + if (!handled && !loading) { + latched = 0; + api->hook_unbind(self, &watch); + } + return handled; +} + +int latch_begin(void) +{ + if (latched) + return 0; + /* Without memory for the watch the switch runs unlatched. */ + latched = api->hook_bind(self, &watch) == RV_OK; + loading = 1; + return 1; +} + +void latch_finish(void) +{ + loading = 0; +} + +int latch_held(void) +{ + return latched; +} + +void latch_unload(void) +{ + if (latched) + api->hook_unbind(self, &watch); + loading = latched = 0; +} diff --git a/extensions/appearance/latch.h b/extensions/appearance/latch.h new file mode 100644 index 0000000..5ec0f7f --- /dev/null +++ b/extensions/appearance/latch.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef LATCH_H +#define LATCH_H + +/* A switch blocks the UI task while it streams, and the presses that queue + * meanwhile must not undo it: the first action latches and watches the + * message loop; the latch opens and the watch ends once the loop reports an + * empty queue after the switch is done. Nothing is bound while idle. */ +int latch_begin(void); +void latch_finish(void); +/* A switch's latch is still closed: another switch would be refused. */ +int latch_held(void); +/* Ends the watch, before the extension unloads. */ +void latch_unload(void); + +#endif diff --git a/extensions/appearance/listing.toml b/extensions/appearance/listing.toml new file mode 100644 index 0000000..804e147 --- /dev/null +++ b/extensions/appearance/listing.toml @@ -0,0 +1,9 @@ +details = "Settings > Appearance, after Brightness, holds Theme, Accent, Dark Mode (Auto, On or Off), Menu Covers and Now Playing Cover. Classic's dark look is derived from the stock artwork on the iPod; other themes are .rvt files in /Reprise/Themes, built with the compiler in the extensions repository. The first load imports the core's former Dark Mode switch." + +[[screenshots]] +file = "screenshots/appearance.png" +alt = "Settings > Appearance with the Theme, Accent, Dark Mode, Menu Covers and Now Playing Cover rows." + +[[screenshots]] +file = "screenshots/dark-mode.png" +alt = "The Settings menu in Classic dark: light text on a dark background with the blue accent." diff --git a/extensions/appearance/look.c b/extensions/appearance/look.c new file mode 100644 index 0000000..2536aa1 --- /dev/null +++ b/extensions/appearance/look.c @@ -0,0 +1,285 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "look.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "assets.h" +#include "dark_mode.h" +#include "latch.h" +#include "render.h" +#include "rv_libc.h" +#include "selection_bar.h" +#include "services.h" +#include "style.h" +#include "theme.h" +#include + +struct look_state look_state; +static int switcher_loaded; /* the switch module is held until finish releases it */ +static int busy; /* a switch is writing settings */ +static int theming_off; /* a restore failed: no theming until the next boot */ +static const char *problem; /* what the last switch could not do */ +static enum look_pane problem_at; /* the pane that shows it */ +static int + standing_in; /* Classic is on screen for a stored theme whose file is missing */ + +/* The canvas roles: the look's, with the secondary shades mixed from text + * toward the background as the stock greys are. */ +static rv_color canvas_roles[RV_COLOR_ROLE_COUNT]; + +const struct look *look_active(void) +{ + return &look_state.active; +} + +/* Whether the look has the other appearance to switch to. */ +static int look_dark_available(void) +{ + return !look_state.active.id[0] || look_state.active.appearances == + (RVT_APPEARANCE_LIGHT | RVT_APPEARANCE_DARK); +} + +const char *look_appearance_note(void) +{ + if (look_dark_available()) + return NULL; + return look_state.active.appearances == RVT_APPEARANCE_DARK + ? "Theme only supports dark mode" + : "Theme only supports light mode"; +} + +const char *look_problem(enum look_pane pane) +{ + return problem && problem_at == pane ? problem : NULL; +} + +int look_busy(void) +{ + return busy; +} + +int look_theming_off(void) +{ + return theming_off; +} + +void look_volume_changed(void) +{ + const struct look *active = &look_state.active; + look_state.stock_checked = 0; + if (active->id[0] && !theme_file_matches(active->id, active->header_crc)) { + assets_drop(); + assets_bind(); + } +} + +#define OPAQUE 0xff000000u + +static rv_color argb(const uint8_t *color) +{ + return OPAQUE | (uint32_t)color[0] << 16 | (uint32_t)color[1] << 8 | color[2]; +} + +static void apply_roles(void) +{ + uint8_t mixed[4], bar[3][4]; + const uint8_t *text = style_color(RVT_ROLE_TEXT), + *background = style_color(RVT_ROLE_BACKGROUND); + if (!style_not_stock()) { + api->ui_set_colors(self, NULL); + return; + } + canvas_roles[RV_COLOR_BACKGROUND] = argb(background); + canvas_roles[RV_COLOR_TEXT] = argb(text); + canvas_roles[RV_COLOR_HIGHLIGHT] = argb(style_color(RVT_ROLE_SELECTION)); + canvas_roles[RV_COLOR_HIGHLIGHT_TEXT] = argb(style_color(RVT_ROLE_ON_ACCENT)); + color_mix(mixed, text, background, 107); + canvas_roles[RV_COLOR_DIM] = argb(mixed); + color_mix(mixed, text, background, 66); + canvas_roles[RV_COLOR_PARAGRAPH] = argb(mixed); + canvas_roles[RV_COLOR_ACCENT_TEXT] = argb(style_color(RVT_ROLE_ACCENT_TEXT)); + /* The bar the lists get: the look's stops, or the stock ones when the + * stock bar stays. The RAM renderer draws no bottom line. */ + if (style_selection_bar(bar)) { + canvas_roles[RV_COLOR_BAR_TOP_LINE] = argb(bar[2]); + canvas_roles[RV_COLOR_BAR_START] = argb(bar[0]); + canvas_roles[RV_COLOR_BAR_END] = canvas_roles[RV_COLOR_BAR_BOTTOM_LINE] = + argb(bar[1]); + } else { + canvas_roles[RV_COLOR_BAR_TOP_LINE] = OPAQUE | SelectionBarColor_TopLine; + canvas_roles[RV_COLOR_BAR_START] = OPAQUE | SelectionBarColor_GradientStart; + canvas_roles[RV_COLOR_BAR_END] = OPAQUE | SelectionBarColor_GradientEnd; + canvas_roles[RV_COLOR_BAR_BOTTOM_LINE] = OPAQUE | SelectionBarColor_BottomLine; + } + api->ui_set_colors(self, canvas_roles); +} + +static uint32_t theme_setting(char id[RVT_ID_BYTES]) +{ + memset(id, 0, RVT_ID_BYTES); + return api->setting_read(self, KEY_THEME, id, RVT_ID_BYTES - 1); +} + +/* Writes the settings to say what is on the screen; `asked` is the appearance + * the action wanted. Auto stays while the screen shows what it asked for. */ +static void settings_write_back(int asked) +{ + char id[RVT_ID_BYTES]; + busy = 1; + theme_setting(id); + if (!standing_in && memcmp(id, look_state.active.id, RVT_ID_BYTES)) + api->setting_write(self, KEY_THEME, RV_SETTING_TYPE_STRING, + look_state.active.id, + (uint32_t)strlen(look_state.active.id)); + if (asked != look_state.active.dark) + api->setting_set_int(self, KEY_DARK, + look_state.active.dark ? DARK_ON : DARK_OFF); + if ((unsigned)api->setting_get_int(self, KEY_ACCENT) != look_state.active.accent) + api->setting_set_int(self, KEY_ACCENT, (int32_t)look_state.active.accent); + busy = 0; +} + +static const struct switch_service *switcher_load(void) +{ + switcher_loaded = api->module_load(self, SWITCH_MODULE) == RV_OK; + return switcher_loaded ? api->module_service(self, SWITCH_MODULE) : NULL; +} + +static void switcher_unload(void) +{ + if (switcher_loaded) + api->module_unload(self, SWITCH_MODULE); + switcher_loaded = 0; +} + +/* After a switch or an accent change, `accent` saying which: the settings, + * the canvas colours, the draw hooks, the cached drawings and the screens + * follow what is there; the switch module is let go. */ +static void finish(enum switch_result result, int asked, int accent, + enum look_pane pane) +{ + if (result != SWITCH_OK && !problem) + problem = result == SWITCH_RESTORE_FAILED ? "Could not restore artwork" + : accent ? "Could not change accent" + : result == SWITCH_RECOVERED ? "Could not apply theme" + : "Could not load theme"; + if (problem) + problem_at = pane; + if (result == SWITCH_RESTORE_FAILED) { + theming_off = 1; + busy = 1; + api->setting_set_int(self, KEY_AVAILABLE, 0); + busy = 0; + } + switcher_unload(); + settings_write_back(asked); + apply_roles(); + /* Binding again after an accent change makes the core decode the + * pictures on screen anew, so tinted extension bitmaps take the colour. */ + if (!assets_bind() && !accent && !problem) { + problem = "Artwork held by another extension"; + problem_at = PANE_THEME; + } + if (!render_bind(style_not_stock()) && !problem) { + problem = "Not enough memory"; + problem_at = pane; + } + selection_bar_apply(); + api->ui_refresh(self, "theme"); + api->ui_redraw(self); + latch_finish(); +} + +void look_switch(const char *id, int dark, unsigned accent, enum look_pane pane) +{ + struct look look; + struct pack_place pack = {0, 0}; + struct rv_file *file = NULL; + const struct switch_service *switcher; + enum switch_result result = SWITCH_LOAD_FAILED; + enum look_pane at = pane; + int asked = dark; + memset(&look, 0, sizeof look); + if (!latch_begin()) { + /* Presses queued behind a switch change nothing; the settings follow the screen. */ + settings_write_back(dark_mode_wanted()); + return; + } + problem = NULL; + standing_in = 0; + if (id[0]) { + enum theme_result opened = theme_open(id, dark, &file, &look, &pack); + if (opened == THEME_UNAVAILABLE) { + /* Classic in the same appearance and accent, the stored theme kept. */ + problem = "Theme unavailable"; + standing_in = 1; + id = ""; + } else { + if (opened == THEME_NOT_IN_APPEARANCE && + !memcmp(look.id, look_state.active.id, RVT_ID_BYTES) && + look.dark == look_state.active.dark && + accent == look_state.active.accent) { + /* The theme's one appearance is on the screen already: only + * the settings have to say so. */ + api->file_close(self, file); + finish(SWITCH_OK, asked, 0, pane); + return; + } + dark = look.dark; + } + } + look.dark = dark; + look.accent = accent; + if (!id[0] && dark && + (!look_file_open(&look, &file) || !look_pack_place(file, &look, &pack))) { + problem = "Could not load dark artwork"; + at = PANE_DARK; + } else if (!(switcher = switcher_load())) { + problem = "Not enough memory"; + } else { + result = switcher->apply(file, &look, &pack); + } + if (file) + api->file_close(self, file); + finish(result, asked, 0, at); +} + +void look_select(const char *id) +{ + look_switch(id, dark_mode_wanted(), + (unsigned)api->setting_get_int(self, KEY_ACCENT), PANE_THEME); +} + +void look_accent(unsigned accent) +{ + const struct switch_service *switcher; + if (accent == look_state.active.accent) + return; + int asked = dark_mode_wanted(); + if (!latch_begin()) { + settings_write_back(asked); + return; + } + problem = NULL; + if (!(switcher = switcher_load())) { + problem = "Not enough memory"; + finish(SWITCH_LOAD_FAILED, asked, 1, PANE_ACCENT); + return; + } + finish(switcher->accent(accent), asked, 1, PANE_ACCENT); +} + +void look_unload(void) +{ + const struct switch_service *switcher = switcher_load(); + if (switcher) + switcher->restore_all(); + switcher_unload(); + assets_release(); + assets_drop(); + latch_unload(); + render_bind(0); + selection_bar_restore(); + api->ui_set_colors(self, NULL); + api->ui_redraw(self); +} diff --git a/extensions/appearance/look.h b/extensions/appearance/look.h new file mode 100644 index 0000000..68bfae2 --- /dev/null +++ b/extensions/appearance/look.h @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* A look is what the screen shows: Classic or a theme, in the light or dark + * appearance, with an accent. Putting one on the screen loads the switch + * module, streams the artwork, applies the colours and writes the settings + * back to say what is there. */ + +#ifndef LOOK_H +#define LOOK_H +#include "catalog.h" +#include "rv_api.h" +#include + +struct look { + char id[RVT_ID_BYTES]; /* empty for Classic */ + char name[RVT_NAME_BYTES]; + uint32_t appearances; /* RVT_APPEARANCE_* bits the theme file has */ + int dark; + unsigned accent; + uint32_t header_crc; /* the header checksum word of the look's file */ +}; + +/* Where a look's pack is in its file: the pack header's offset and the + * pack's size, header included. */ +struct pack_place { + uint32_t offset, bytes; +}; + +enum switch_result { + SWITCH_OK, + SWITCH_LOAD_FAILED, /* the pack or the firmware file is unusable; nothing changed */ + SWITCH_RECOVERED, /* a write failed; the stock light look is back */ + SWITCH_RESTORE_FAILED /* and some bitmaps could not be restored: theming is off */ +}; + +/* What outlives a switch: the look on the screen, the bitmaps that differ + * from stock (the pack's replacements and the tinted accent art), which of + * those are the accent art, and whether the firmware file has been checked + * against the resident bank this session. */ +struct look_state { + struct look active; + uint32_t assets[BITMAP_WORDS]; + uint32_t accented[BITMAP_WORDS]; + int stock_checked; +}; + +extern struct look_state look_state; +const struct look *look_active(void); +/* For the Dark Mode pane of a theme with one appearance: which it has; NULL + * when both are there. */ +const char *look_appearance_note(void); + +/* The pane an action came from, which is where its failure is shown. */ +enum look_pane { PANE_THEME, PANE_DARK, PANE_ACCENT }; + +/* What the last switch could not do, or NULL; shown under `pane` only. */ +const char *look_problem(enum look_pane pane); + +/* Theme `id` ("" for Classic) in the current appearance and accent, from the + * picker. */ +void look_select(const char *id); +/* Theme `id`, or Classic in the `dark` or light appearance, with `accent`. + * A theme whose file is missing shows Classic and says so under Theme; the + * stored id stays, so the theme returns when its file does. */ +void look_switch(const char *id, int dark, unsigned accent, enum look_pane pane); +/* Another accent on the current look. */ +void look_accent(unsigned accent); +/* A switch is writing settings; their change callbacks are its own. */ +int look_busy(void); +/* A restore failed this session: theming stays off until the next boot. */ +int look_theming_off(void); +/* Disk mode may have replaced the firmware file and the theme file: the first + * is checked again next switch; the second is checked now, and when it is + * another file or gone, the index of its bitmaps for extensions goes. */ +void look_volume_changed(void); +/* Every bitmap back to stock and the stock colours, before the extension unloads. */ +void look_unload(void); + +#endif diff --git a/extensions/appearance/lz.c b/extensions/appearance/lz.c new file mode 100644 index 0000000..47c5ba2 --- /dev/null +++ b/extensions/appearance/lz.c @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "lz.h" +#include "crc.h" +#include "ext.h" +#include "rvt.h" + +struct lz_input { + struct rv_file *file; + uint32_t left; /* stream bytes still in the file */ + uint32_t have; /* bytes left in `chunk` */ + const uint8_t *next; /* the next of them */ + uint32_t crc; + uint8_t chunk[256]; +}; + +/* The next stream byte, -1 at the end or on a short read. */ +static int next_byte(struct lz_input *in) +{ + if (!in->have) { + uint32_t n = in->left < sizeof in->chunk ? in->left : sizeof in->chunk, got = 0; + if (!n || api->file_read(self, in->file, in->chunk, n, &got) != RV_OK || + got != n) + return -1; + in->crc = crc32_update(in->crc, in->chunk, n); + in->next = in->chunk; + in->have = n; + in->left -= n; + } + in->have--; + return *in->next++; +} + +static int decode(struct lz_input *in, uint8_t *out, uint32_t bytes) +{ + uint32_t done = 0; + while (done < bytes) { + int flags = next_byte(in); + if (flags < 0) + return 0; + for (uint32_t bit = 0; bit < 8 && done < bytes; bit++) { + int high = next_byte(in); + if (high < 0) + return 0; + if (!(flags >> bit & 1)) { + out[done++] = (uint8_t)high; + continue; + } + int low = next_byte(in); + uint32_t length = (uint32_t)(high >> 4) + RVT_LZ_MIN_MATCH; + uint32_t distance = + ((uint32_t)(high & 15) << 8 | (uint32_t)(low & 255)) + 1; + for (int more = high >> 4 == 15 ? 255 : 0; more == 255; + length += (uint32_t)more) + if ((more = next_byte(in)) < 0) + return 0; + if (low < 0 || distance > done || length > bytes - done) + return 0; + for (uint32_t end = done + length; done < end; done++) + out[done] = out[done - distance]; + } + } + return !in->have && !in->left; +} + +int lz_decode(struct rv_file *file, uint32_t stream_bytes, uint8_t *out, uint32_t bytes, + uint32_t *crc) +{ + struct lz_input in; + in.file = file; + in.left = stream_bytes; + in.have = 0; + in.crc = *crc; + int whole = decode(&in, out, bytes); + *crc = in.crc; + return whole; +} diff --git a/extensions/appearance/lz.h b/extensions/appearance/lz.h new file mode 100644 index 0000000..2ce1bb5 --- /dev/null +++ b/extensions/appearance/lz.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The RVT_LZ stream of a pixels record or an extension bitmap, read from the + * file in stack-sized pieces and decoded straight into its destination. In + * the main module, so the asset provider has it while the switch module is + * unloaded; the switch module calls it through main_service. */ + +#ifndef LZ_H +#define LZ_H +#include "rv_api.h" +#include + +/* Decodes the stream of `stream_bytes` at the file's position into exactly + * `bytes` of `out`, continuing *crc over every stream byte read: 0 when the + * stream ends early, a match reaches before the output, the output would + * overrun, or the stream does not end where the output is full. */ +int lz_decode(struct rv_file *file, uint32_t stream_bytes, uint8_t *out, uint32_t bytes, + uint32_t *crc); + +#endif diff --git a/extensions/appearance/main.c b/extensions/appearance/main.c new file mode 100644 index 0000000..893b785 --- /dev/null +++ b/extensions/appearance/main.c @@ -0,0 +1,309 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Appearance: a Settings row after Brightness opening a menu of Theme, + * Accent, Dark Mode, Menu Covers and Now Playing Cover, whose rows other + * extensions anchor theirs on. A look is a theme file's pack or the Classic + * dark art from the `classic` asset streamed into the resident bitmaps, plus + * the colour roles the draw hooks map the stock screens to; the core's + * canvases follow through ui_set_colors. The settings hold the theme id, Dark + * Mode and the accent; whatever cannot be put on the screen is written back + * as what is. While Dark Mode is on Auto, a minute timer reads the schedule + * and it follows. + * + * This module is always loaded: the bitmap catalog, colour roles, draw hooks + * (bound only while the look is not stock light; the cover and menu cover + * hooks always), the index of the look's extension bitmaps and the provider + * that reads them when the core decodes one, the Theme list and the settings. + * Reading a theme file, deriving art and restoring stock bitmaps are in the + * switch module. */ + +#include "../shared/legacy.h" +#include "catalog.h" +#include "crc.h" +#include "dark_mode.h" +#include "ext.h" +#include "assets.h" +#include "flat_cover.h" +#include "latch.h" +#include "look.h" +#include "lz.h" +#include "menu_covers.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "schedule.h" +#include "services.h" +#include "style.h" +#include "theme_picker.h" +#include "tint.h" +#include + +const struct rv_api *api; +rv_extension_handle self; + +static const struct rv_setting settings[] = { + RV_SETTING_CHOICE(KEY_DARK, "Dark Mode", DARK_OFF, dark_mode_labels), + RV_SETTING_CHOICE(KEY_ACCENT, "Accent", ACCENT_DEFAULT, accent_labels), + RV_SETTING_CHOICE(KEY_MENU_COVERS, "Menu Covers", COVERS_THEME, menu_covers_labels), + RV_SETTING_CHOICE(KEY_NOW_PLAYING_COVER, "Now Playing Cover", NP_COVER_THEME, + now_playing_cover_labels), + RV_SETTING_BOOL(KEY_AVAILABLE, "Appearance", 1), +}; + +static struct rv_timer *timer; /* the minute tick while Dark Mode is on Auto */ +static int zone_known; + +/* In Auto, the appearance the schedule asks for; a switch in progress, or + * one whose latch is still closed, keeps the setting and waits a minute. */ +static void dark_follow(const struct schedule *s) +{ + char id[RVT_ID_BYTES]; + int night = schedule_night(s); + if (!dark_mode_auto() || look_theming_off() || look_busy() || latch_held() || + night == look_active()->dark) + return; + memset(id, 0, sizeof id); + api->setting_read(self, KEY_THEME, id, sizeof id - 1); + look_switch(id, night, (unsigned)api->setting_get_int(self, KEY_ACCENT), PANE_DARK); +} + +static void tick(void *arg) +{ + (void)arg; + struct schedule s; + schedule_read(&s); + dark_follow(&s); + if (zone_known != (s.state != SCHEDULE_NO_ZONE)) { + zone_known = !zone_known; + api->ui_pane_refresh(self); + } +} + +/* The minute timer while Dark Mode is on Auto. At load the extension runs inside + * Apple's preferences load, before the browser holds the preferences object + * that names the time zone: a read that finds no zone is tried again from the + * event loop a second later, so the first screen already follows Auto. */ +static void watch(int on) +{ + struct schedule s; + if (on && !timer) { + timer = api->timer_start(self, 60 * 1000, 1, tick, NULL); + schedule_read(&s); + zone_known = s.state != SCHEDULE_NO_ZONE; + if (!zone_known) + api->timer_start(self, 1000, 0, tick, NULL); + } + if (!on) + rv_timer_cancel(api, self, &timer); +} + +/* The stored theme in appearance `dark` with `accent` is what the screen shows. */ +static int on_screen(const char *id, int dark, unsigned accent) +{ + const struct look *active = look_active(); + return !memcmp(id, active->id, RVT_ID_BYTES) && dark == active->dark && + accent == active->accent; +} + +/* The core's former Dark Mode switch, store record DARK = DRK1, comes in once on + * the first load as Dark Mode On; the write it makes is not a change of its own. */ +static int first_load = 1, importing; + +static void setting_changed(uint16_t key) +{ + char id[RVT_ID_BYTES]; + if (importing) + return; + if (key == RV_SETTING_KEY_ALL) { + importing = 1; + migrate_switch(api, self, first_load, KEY_DARK, 0x4b524144, 0x314b5244, DARK_ON, + DARK_OFF, RV_SETTING_TYPE_INT); + importing = 0; + first_load = 0; + } + if (key == RV_SETTING_KEY_ALL || key == KEY_DARK) + dark_mode_set(api->setting_get_int(self, KEY_DARK)); + watch(dark_mode_auto()); + if (look_busy()) + return; + int dark = dark_mode_wanted(); + unsigned accent = (unsigned)api->setting_get_int(self, KEY_ACCENT); + switch (key) { + case RV_SETTING_KEY_ALL: + /* At load, and after Reset All Settings emptied the store. */ + if (!api->setting_get_int(self, KEY_AVAILABLE) && !look_theming_off()) + api->setting_set_int(self, KEY_AVAILABLE, 1); + menu_covers_set(api->setting_get_int(self, KEY_MENU_COVERS)); + flat_cover_set(api->setting_get_int(self, KEY_NOW_PLAYING_COVER)); + memset(id, 0, sizeof id); + api->setting_read(self, KEY_THEME, id, sizeof id - 1); + if (!on_screen(id, dark, accent)) + look_switch(id, dark, accent, PANE_THEME); + break; + case KEY_DARK: + /* The stored theme, not the active one: while Classic stands in for a + * theme whose file was missing, the ids differ and the theme is tried again. */ + memset(id, 0, sizeof id); + api->setting_read(self, KEY_THEME, id, sizeof id - 1); + if (!on_screen(id, dark, accent)) + look_switch(id, dark, accent, PANE_DARK); + break; + case KEY_ACCENT: + look_accent(accent); + break; + case KEY_MENU_COVERS: + menu_covers_set(api->setting_get_int(self, KEY_MENU_COVERS)); + break; + case KEY_NOW_PLAYING_COVER: + flat_cover_set(api->setting_get_int(self, KEY_NOW_PLAYING_COVER)); + break; + default: + break; + } +} + +static const char *theme_caption(const struct rv_context *ctx) +{ + (void)ctx; + const struct look *active = look_active(); + const char *problem = look_problem(PANE_THEME); + return problem ? problem : active->id[0] ? active->name : "Classic"; +} + +static const char *dark_pane(const struct rv_context *ctx) +{ + (void)ctx; + return dark_mode_caption(); +} + +/* The row says Theme; the pane has room for the full phrase. */ +static const char *accent_caption(const struct rv_context *ctx) +{ + (void)ctx; + const char *problem = look_problem(PANE_ACCENT); + if (problem) + return problem; + return style_accent() == ACCENT_DEFAULT ? "Theme Default" + : accent_labels[style_accent()]; +} + +static const char *covers_caption(const struct rv_context *ctx) +{ + (void)ctx; + return menu_covers_enabled() ? "On" : "Off"; +} + +static const char *cover_caption(const struct rv_context *ctx) +{ + (void)ctx; + return flat_cover_flat() ? "Flat" : "Tilted"; +} + +/* The Appearance menu: each row with its own pane caption and icon, and an id + * other extensions anchor their rows on. */ +static const struct rv_row rows[] = { + RV_ROW_PUSH("Theme", "theme", .id = "theme"), + RV_ROW_SETTING("Accent", KEY_ACCENT, .id = "accent"), + RV_ROW_SETTING("Dark Mode", KEY_DARK, .id = "dark-mode"), + RV_ROW_SETTING("Menu Covers", KEY_MENU_COVERS, .id = "menu-covers"), + RV_ROW_SETTING("Now Playing Cover", KEY_NOW_PLAYING_COVER, + .id = "now-playing-cover"), +}; +static const struct rv_pane panes[] = { + {.caption_text = theme_caption, .bitmap = RV_BITMAP("settings-theme")}, + {.caption_text = accent_caption, .bitmap = RV_BITMAP("settings-accent")}, + {.caption_text = dark_pane, .bitmap = RV_BITMAP("settings-moon")}, + {.caption_text = covers_caption, .bitmap = RV_BITMAP("settings-covers")}, + {.caption_text = cover_caption, .bitmap = RV_BITMAP("settings-cover")}, +}; +/* The choice screens the rows open, declared for their pane icons; the + * screens the core makes from the settings have none. */ +static const struct rv_screen screens[] = { + RV_SCREEN_LIST_PANES("appearance", "Appearance", rows, panes), + THEME_PICKER_SCREEN, + RV_SCREEN_CHOICE("accent", "Accent", KEY_ACCENT, accent_labels, + .bitmap = RV_BITMAP("settings-accent")), + RV_SCREEN_CHOICE("dark-mode", "Dark Mode", KEY_DARK, dark_mode_labels, + .bitmap = RV_BITMAP("settings-moon")), + RV_SCREEN_CHOICE("menu-covers", "Menu Covers", KEY_MENU_COVERS, menu_covers_labels, + .bitmap = RV_BITMAP("settings-covers")), + RV_SCREEN_CHOICE("now-playing-cover", "Now Playing Cover", KEY_NOW_PLAYING_COVER, + now_playing_cover_labels, .bitmap = RV_BITMAP("settings-cover")), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_BRIGHTNESS, + RV_ROW_PUSH("Appearance", "appearance"), + .pane = RV_PANE(.caption = "Make It Your Own", + .bitmap = RV_BITMAP("settings-appearance")), + .shown_by = KEY_AVAILABLE), +}; + +/* No arguments: disk mode has ended and the volume, firmware file included, + * is readable again. */ +static uint32_t disk_mode_exit(const void *next) +{ + look_volume_changed(); + return api->hook_next(next, 0, 0, 0, 0, 0, 0); +} + +/* The hooks bound in every look, the Menu Covers and Now Playing Cover hooks + * among them; the draw hooks are bound while a look is on. */ +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER(RV_SITE_MediaArtworkProvider_GetSlotArtwork_entry, + menu_covers_query), + RV_HOOK_FILTER(RV_SITE_GLAlbumArtView_Draw_slot, flat_cover_view_draw), + RV_HOOK_FILTER(RV_SITE_AlbumArt_RendererDraw_call, flat_cover_renderer_draw), + RV_HOOK_FILTER(RV_SITE_AlbumArt_EdgeLines_call, flat_cover_edge_lines), + RV_HOOK_FILTER(RV_SITE_DiskModeExit_PopToMainScreen_call, disk_mode_exit), +}; + +/* The core stops the timer itself as the module unloads. */ +static void unload(void) +{ + timer = NULL; + look_unload(); +} + +static const struct main_service service = { + .state = &look_state, + .crc32_update = crc32_update, + .catalog_count = catalog_count, + .catalog_fingerprint = catalog_fingerprint, + .catalog_data = catalog_data, + .catalog_size = catalog_size, + .catalog_crc = catalog_crc, + .catalog_file_offset = catalog_file_offset, + .catalog_layout = catalog_layout, + .style_set = style_set, + .style_reset = style_reset, + .style_set_dark = style_set_dark, + .style_set_accent = style_set_accent, + .tint_refresh = tint_refresh, + .tint_accent_art = tint_accent_art, + .lz_decode = lz_decode, + .assets_reserve = assets_reserve, + .assets_commit = assets_commit, + .assets_drop = assets_drop, +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .unload = unload, + .setting_changed = setting_changed, + RV_SCREENS(screens), + 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/appearance/manifest.toml b/extensions/appearance/manifest.toml new file mode 100644 index 0000000..01f9d7e --- /dev/null +++ b/extensions/appearance/manifest.toml @@ -0,0 +1,55 @@ +id = "appearance" +name = "Appearance" +description = "Dark Mode, Accent and themes that recolour the screens and replace the artwork." +version = "0.1.0" +author = "RepriseOS and RevolaOS contributors" +license = "GPL-3.0-only" +api = "1.89" +category = "system" +content = "Themes" + +[libraries] +optional = ["reprise"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "switch" +trigger = "manual" + +[[asset]] +name = "settings-appearance" +file = "assets/settings-appearance.png" +pane = "icon" + +[[asset]] +name = "settings-theme" +file = "assets/settings-theme.png" +pane = "icon" + +[[asset]] +name = "settings-moon" +file = "assets/settings-moon.png" +pane = "icon" + +[[asset]] +name = "settings-accent" +file = "assets/settings-accent.png" +pane = "icon" + +[[asset]] +name = "settings-covers" +file = "assets/settings-covers.png" +pane = "icon" + +[[asset]] +name = "settings-cover" +file = "assets/settings-cover.png" +pane = "icon" + +[[asset]] +name = "classic" +file = "build/classic.rvt" +compress = false diff --git a/extensions/appearance/menu_covers.c b/extensions/appearance/menu_covers.c new file mode 100644 index 0000000..8f6e3b9 --- /dev/null +++ b/extensions/appearance/menu_covers.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "menu_covers.h" +#include "ext.h" +#include "rvt.h" +#include "style.h" + +const char *const menu_covers_labels[3] = {"Theme", "On", "Off"}; +static int choice; /* the setting */ + +void menu_covers_set(int value) +{ + choice = value; +} + +int menu_covers_enabled(void) +{ + if (choice == COVERS_THEME) + return !(style_flags() & RVT_FLAG_MENU_COVERS_OFF); + return choice == COVERS_ON; +} + +uint32_t menu_covers_query(uint32_t provider, uint32_t slot, const void *next) +{ + if (slot == 0 && !menu_covers_enabled()) + return 0; + return api->hook_next(next, provider, slot, 0, 0, 0, 0); +} diff --git a/extensions/appearance/menu_covers.h b/extensions/appearance/menu_covers.h new file mode 100644 index 0000000..5d82e16 --- /dev/null +++ b/extensions/appearance/menu_covers.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef MENU_COVERS_H +#define MENU_COVERS_H +#include "rv_api.h" + +/* Menu Covers: whether the Main and Music menus show the highlighted row's + * cover. The setting is Theme (what the look says; stock shows them), On or + * Off. */ +enum { COVERS_THEME, COVERS_ON, COVERS_OFF }; + +extern const char *const menu_covers_labels[3]; +void menu_covers_set(int choice); +int menu_covers_enabled(void); +/* (provider, slot): the artwork lookup the menus make; 0 hides the cover. */ +uint32_t menu_covers_query(uint32_t provider, uint32_t slot, const void *next); + +#endif diff --git a/extensions/appearance/pack.c b/extensions/appearance/pack.c new file mode 100644 index 0000000..9012418 --- /dev/null +++ b/extensions/appearance/pack.c @@ -0,0 +1,356 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "pack.h" +#include "derive.h" +#include "ext.h" +#include "pixel.h" +#include "rv_libc.h" +#include "stock.h" +#include "switch.h" + +static uint32_t checksum(uint32_t sum, const void *data, uint32_t size) +{ + return main_module->crc32_update(sum, data, size); +} + +static const uint8_t *tint_bytes(const struct pack *pack) +{ + return (const uint8_t *)pack->style + RVT_STYLE_TINTS; +} + +/* Opaque colours, known flags, and tint bytes that name a role on a bitmap + * the catalog has; checked before anything is written. */ +static int style_valid(const uint8_t *style, uint32_t catalog_count) +{ + const uint8_t *p = style + RVT_STYLE_COLORS; + for (unsigned i = 0; i < RVT_ROLES; i++) + if (p[i * 4 + 3] != 255) + return 0; + if (le32(style + RVT_STYLE_FLAGS) & + ~(uint32_t)(RVT_FLAG_FLAT_SELECTION | RVT_FLAG_MENU_COVERS_OFF | + RVT_FLAG_FLAT_NOW_PLAYING | RVT_FLAG_FLAT_ICONS)) + return 0; + p = style + RVT_STYLE_PALETTES; + for (unsigned i = 0; i < RVT_ACCENTS * RVT_ACCENT_SLOTS; i++) + if (p[i * 4 + 3] != 255) + return 0; + p = style + RVT_STYLE_TINTS; + for (unsigned i = 0; i < RVT_CATALOG_MAX; i++) { + unsigned coverage = p[i] & (RVT_TINT_DARKNESS | RVT_TINT_SOLID); + unsigned tint = p[i] & ~coverage; + if (coverage == (RVT_TINT_DARKNESS | RVT_TINT_SOLID) || + tint >= RVT_TINT_ROLE + RVT_ROLES || (coverage && tint == RVT_TINT_NONE) || + (p[i] && i >= catalog_count)) + return 0; + } + return 1; +} + +int pack_plain(const struct pack *pack) +{ + const uint8_t *tint = tint_bytes(pack); + if (le32((const uint8_t *)pack->style + RVT_STYLE_FLAGS)) + return 0; + for (unsigned i = 0; i < RVT_CATALOG_MAX; i++) + if (tint[i]) + return 0; + return 1; +} + +int pack_open(struct rv_file *file, uint32_t header_crc, const struct pack_place *place, + struct pack *pack) +{ + uint8_t pack_header[RVT_PACK_HEADER_BYTES]; + uint32_t crc; + memset(pack, 0, sizeof *pack); + if (api->file_seek(self, file, RVT_HEADER_CRC) != RV_OK || + !read_exact(file, &crc, sizeof crc) || crc != header_crc || + api->file_seek(self, file, place->offset) != RV_OK || + !read_exact(file, pack_header, sizeof pack_header)) + return 0; + pack->body = place->offset + RVT_PACK_HEADER_BYTES; + pack->body_bytes = le32(pack_header + RVT_PACK_BODY_BYTES); + pack->count = le32(pack_header + RVT_PACK_RECORDS); + pack->crc = le32(pack_header + RVT_PACK_CRC); + pack->extension_bitmaps = le32(pack_header + RVT_PACK_EXTENSION_BITMAPS); + if (pack->body_bytes != place->bytes - RVT_PACK_HEADER_BYTES || + pack->count > main_module->catalog_count() || + pack->extension_bitmaps > RVT_EXTENSION_BITMAPS_MAX || + !read_exact(file, pack->style, RVT_STYLE_BYTES) || + !style_valid((const uint8_t *)pack->style, main_module->catalog_count())) + return 0; + pack->file = file; + return 1; +} + +/* The payload bytes a kind allows for a bitmap. */ +static int record_valid(uint32_t asset, uint32_t kind, uint32_t size, uint32_t i, + uint32_t previous, struct layout *b) +{ + if ((i && asset <= previous) || !main_module->catalog_layout(asset, b)) + return 0; + switch (kind) { + case RVT_KIND_PIXELS: + return size == main_module->catalog_size(asset) - b->start; + case RVT_KIND_PIXELS_LZ: + return size > 0; + case RVT_KIND_RECOLOR: + return size >= 4 + 8 && (size - 4) % 8 == 0 && + (size - 4) / 8 <= RVT_RECOLOR_MAX; + case RVT_KIND_ALIAS: + return size == 4; + case RVT_KIND_INVERT: + return size == 0; + case RVT_KIND_RELIGHT: + return size == RVT_RELIGHT_BYTES; + } + return 0; +} + +/* Every pixel of a paletted bitmap names a palette entry; `data` starts at + * the palette. */ +static int indices_valid(const struct layout *b, const uint8_t *data) +{ + uint32_t colors = b->colors; + if (!colors || (b->depth == 8 && colors >= 256)) + return 1; + const uint8_t *row = data + b->pixels - b->start; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) + if ((b->depth == 8 ? row[x] : le16(row + x * 2)) >= colors) + return 0; + return 1; +} + +/* One bit per tinted bitmap. A pixels record clears its bit; a derived record + * on a tinted bitmap is invalid; what remains is tinted stock art. */ +static void tint_pending(const uint8_t *tint, uint32_t *pending) +{ + memset(pending, 0, BITMAP_WORDS * 4); + for (uint32_t i = 0; i < RVT_CATALOG_MAX; i++) + if (tint[i]) + bit_set(pending, i); +} + +/* The bitmap holds its stock bytes: fetched when the active look changed it. */ +static int stock_ready(uint32_t asset, const struct layout *b, const uint32_t *current) +{ + return !bit_test(current, asset) || + stock_fetch(asset, main_module->catalog_data(asset) + b->start); +} + +struct alias { + uint16_t asset, source; +}; + +/* The stored bytes a kind allows for a bitmap of `decoded` bytes: the same, + * or an lz stream, which is at most a flag byte per eight literals longer. + * The decoded size holds at least a header and at most the cap. */ +static int bitmap_size_valid(uint32_t kind, uint32_t stored, uint32_t decoded) +{ + if (!stored || decoded <= RVT_BMAP_HEADER_BYTES || + decoded > RVT_EXTENSION_BITMAP_MAX_BYTES) + return 0; + if (kind == RVT_EXTENSION_BITMAP) + return stored == decoded; + return stored <= decoded + (decoded + 7) / 8; +} + +/* An extension bitmap's tint word: none, or a role without coverage bits. */ +static int tint_word_valid(uint32_t tint) +{ + return tint == RVT_TINT_NONE || + (tint >= RVT_TINT_ROLE && tint < RVT_TINT_ROLE + RVT_ROLES); +} + +/* Bytes the switch leaves in the file, read for the checksum only. */ +static int checksum_skip(struct rv_file *file, uint32_t bytes, uint32_t *sum) +{ + uint8_t chunk[256]; + while (bytes) { + uint32_t n = bytes < sizeof chunk ? bytes : sizeof chunk; + if (!read_exact(file, chunk, n)) + return 0; + *sum = checksum(*sum, chunk, n); + bytes -= n; + } + return 1; +} + +/* The extension bitmaps after the records into the index: each entry is + * checked and its payload's place kept; the payload is read into the checksum + * only and served as stored by the provider, since the core checks a bitmap + * once it has decoded it. */ +static int bitmaps_index(struct pack *pack, uint32_t *consumed, uint32_t *sum) +{ + struct asset_entry *entries = main_module->assets_reserve(pack->extension_bitmaps); + if (pack->extension_bitmaps && !entries) + return 0; + for (uint32_t i = 0; i < pack->extension_bitmaps; i++) { + uint32_t entry[RVT_EXTENSION_BITMAP_BYTES / 4], zero = 0; + if (pack->body_bytes - *consumed < sizeof entry || + !read_exact(pack->file, entry, sizeof entry)) + return 0; + *consumed += sizeof entry; + *sum = checksum(*sum, entry, sizeof entry); + uint32_t owner = entry[0], asset = entry[1], kind = entry[2], size = entry[3]; + uint32_t decoded = entry[4], tint = entry[5], padding = (0u - size) & 3u; + if ((i && !asset_before(entries + i - 1, owner, asset)) || + (kind != RVT_EXTENSION_BITMAP && kind != RVT_EXTENSION_BITMAP_LZ) || + !bitmap_size_valid(kind, size, decoded) || !tint_word_valid(tint) || + size > pack->body_bytes - *consumed || + padding > pack->body_bytes - *consumed - size) + return 0; + entries[i].owner = owner; + entries[i].asset = asset; + entries[i].offset = pack->body + *consumed; + entries[i].bytes = size; + entries[i].decoded = decoded; + entries[i].kind = (uint16_t)kind; + entries[i].tint = (uint8_t)tint; + if (!checksum_skip(pack->file, size, sum) || + (padding && (!read_exact(pack->file, &zero, padding) || zero))) + return 0; + *sum = checksum(*sum, &zero, padding); + *consumed += size + padding; + } + return 1; +} + +int pack_apply(struct pack *pack, uint32_t *written, const uint32_t *current) +{ + struct rv_file *file = pack->file; + uint32_t pending[BITMAP_WORDS], previous = 0; + uint32_t sum = checksum(0xffffffffu, pack->style, RVT_STYLE_BYTES); + uint32_t consumed = RVT_STYLE_BYTES; + struct alias aliases[RVT_ALIASES_MAX]; + uint32_t naliases = 0; + uint8_t *scratch = NULL; + int ok = 0; + tint_pending(tint_bytes(pack), pending); + for (uint32_t i = 0; i < pack->count; i++) { + uint32_t record[3], payload[RVT_RELIGHT_WORDS]; + struct layout b; + if (pack->body_bytes - consumed < sizeof record || + !read_exact(file, record, sizeof record)) + goto done; + consumed += sizeof record; + sum = checksum(sum, record, sizeof record); + uint32_t asset = record[0], kind = record[1], size = record[2]; + uint32_t padding = (0u - size) & 3u; + if (kind >= RVT_KINDS || size > pack->body_bytes - consumed || + padding > pack->body_bytes - consumed - size || + !record_valid(asset, kind, size, i, previous, &b)) + goto done; + previous = asset; + bit_set(written, asset); + uint8_t *data = main_module->catalog_data(asset) + b.start; + uint32_t bytes = main_module->catalog_size(asset) - b.start; + if (kind == RVT_KIND_PIXELS || kind == RVT_KIND_PIXELS_LZ) { + /* A resident bitmap must never index past its palette. */ + int whole; + if (kind == RVT_KIND_PIXELS) { + whole = read_exact(file, data, size); + sum = checksum(sum, data, size); + } else { + whole = main_module->lz_decode(file, size, data, bytes, &sum); + } + if (!whole || !indices_valid(&b, data)) { + memset(data, 0, bytes); + goto done; + } + pending[asset / 32] &= ~(1u << (asset % 32)); + } else { + if (bit_test(pending, asset) || + (!scratch && !(scratch = api->alloc(self, RVT_SCRATCH_BYTES)))) + goto done; + uint8_t *table = (uint8_t *)payload; + uint32_t pairs = 0; + if (kind == RVT_KIND_RECOLOR) { + /* The count, then the pairs into the scratch block, which holds + * RVT_RECOLOR_MAX of them and nothing else. */ + if (!read_exact(file, &pairs, 4) || pairs != (size - 4) / 8) + goto done; + sum = checksum(sum, &pairs, 4); + table = scratch; + size -= 4; + } + if (!read_exact(file, table, size)) + goto done; + sum = checksum(sum, table, size); + if (kind == RVT_KIND_RECOLOR) + size += 4; + if (kind == RVT_KIND_ALIAS) { + uint32_t source = payload[0]; + struct layout s; + if (naliases == RVT_ALIASES_MAX || source == asset || + !main_module->catalog_layout(source, &s) || + tint_bytes(pack)[source] || b.mask || s.mask || + b.width != s.width || b.height != s.height) + goto done; + aliases[naliases].asset = (uint16_t)asset; + aliases[naliases++].source = (uint16_t)source; + } else { + if (!stock_ready(asset, &b, current)) + goto done; + int derived = + kind == RVT_KIND_RECOLOR ? derive_recolor(asset, &b, scratch, pairs) + : kind == RVT_KIND_INVERT + ? derive_invert(asset, &b) + : derive_relight(asset, &b, (const int32_t *)payload, scratch); + if (!derived) + goto done; + } + } + uint32_t zero = 0; + if (padding && (!read_exact(file, &zero, padding) || zero)) + goto done; + sum = checksum(sum, &zero, padding); + consumed += size + padding; + } + if (!bitmaps_index(pack, &consumed, &sum) || consumed != pack->body_bytes || + ~sum != pack->crc) + goto done; + /* Aliases last, so every source is final; a source that is itself listed + * is a chain. A source the pack left alone must be stock, and the target + * starts from stock too, so its row padding is the same whatever the + * previous look left there. */ + for (uint32_t a = 0; a < naliases; a++) { + struct layout b, s; + for (uint32_t c = 0; c < naliases; c++) + if (aliases[c].asset == aliases[a].source) + goto done; + if (!main_module->catalog_layout(aliases[a].asset, &b) || + !main_module->catalog_layout(aliases[a].source, &s)) + goto done; + if (!bit_test(written, aliases[a].source) && + !stock_ready(aliases[a].source, &s, current)) + goto done; + if (!stock_ready(aliases[a].asset, &b, current) || + !derive_alias(aliases[a].asset, &b, aliases[a].source)) + goto done; + } + /* Tinted paletted and ARGB bitmaps without a record are tinted stock art: + * their coverage is prepared here. Masks are coloured while drawing and + * keep their stock levels unless the coverage is solid. */ + for (uint32_t i = 0; i < RVT_CATALOG_MAX; i++) { + struct layout b; + uint8_t tint = tint_bytes(pack)[i]; + if (!bit_test(pending, i)) + continue; + if (!main_module->catalog_layout(i, &b)) + goto done; + if (b.mask && !(tint & RVT_TINT_SOLID)) + continue; + bit_set(written, i); + if (!stock_ready(i, &b, current) || + !derive_coverage(i, &b, (tint & RVT_TINT_DARKNESS) != 0, + (tint & RVT_TINT_SOLID) != 0)) + goto done; + } + ok = 1; +done: + if (scratch) + api->free(self, scratch); + return ok; +} diff --git a/extensions/appearance/pack.h b/extensions/appearance/pack.h new file mode 100644 index 0000000..3ab106d --- /dev/null +++ b/extensions/appearance/pack.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Reading one appearance pack of a theme file (rvt.h), streamed straight into + * the resident bitmaps. The file is an rv_file from content_open or + * asset_open whose header main has checked and placed the pack by. */ + +#ifndef PACK_H +#define PACK_H +#include "catalog.h" +#include "look.h" +#include "rv_api.h" +#include + +/* An open pack positioned at its first record, with its style prefix read; + * `body` is the file offset of its body, `extension_bitmaps` the count of + * the bitmaps for extensions after its records. */ +struct pack { + struct rv_file *file; + uint32_t body, body_bytes, count, crc, extension_bitmaps; + uint32_t style[RVT_STYLE_BYTES / 4]; +}; + +/* Opens the pack at `place`: the header's checksum word must still be + * `header_crc` (the file may have changed since main read it), then the pack + * header and the style prefix, which must be opaque and tint catalog bitmaps + * only. Nothing is written yet, so a failure leaves the look unchanged. */ +int pack_open(struct rv_file *file, uint32_t header_crc, const struct pack_place *place, + struct pack *pack); +/* Whether the pack's style asks for nothing but colours: no tints, no flags. */ +int pack_plain(const struct pack *pack); +/* Streams the records into the resident bitmaps: pixel records are read or + * decoded in place, derived records are computed from the stock bytes + * (fetched from the firmware file first when `current` says the active look + * changed the bitmap), aliases after every other record, and a tinted + * paletted or ARGB bitmap without a record gets its coverage prepared for + * tint_refresh. Each record's layout, payload and padding are checked, then + * the extension bitmaps go into the index main reserves for them (committed + * or dropped by the caller), then the body checksum. Every catalog bitmap it + * wrote is set in `written`, also on failure, when a half-written bitmap + * holds zeros or stock bytes. The caller has stock_open and the bitmaps are + * live, so this runs on the UI task and the caller redraws. */ +int pack_apply(struct pack *pack, uint32_t *written, const uint32_t *current); + +#endif diff --git a/extensions/appearance/pixel.h b/extensions/appearance/pixel.h new file mode 100644 index 0000000..e6f14be --- /dev/null +++ b/extensions/appearance/pixel.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Little-endian words, clamping and RGB565 packing, shared by the file + * reader, the derivations and the draw hooks. */ + +#ifndef PIXEL_H +#define PIXEL_H +#include + +static inline uint32_t le16(const uint8_t *p) +{ + return p[0] | (uint32_t)p[1] << 8; +} + +static inline uint32_t le32(const uint8_t *p) +{ + return le16(p) | le16(p + 2) << 16; +} + +static inline int32_t clamp(int32_t value, int32_t low, int32_t high) +{ + return value < low ? low : value > high ? high : value; +} + +/* value / 255 exactly for value up to 65534, without a division. */ +static inline uint32_t div255(uint32_t value) +{ + return (value + 1 + (value >> 8)) >> 8; +} + +/* x / d for x below 2^24 and 0 < d below 2^16 as one multiply by the + * reciprocal, exact over that range (the divisor's 16 bits plus the + * dividend's 24 fit a 40-bit shift). Division by a constant folds at compile + * time; the relight rule computes its reciprocal once per bitmap. */ +static inline uint64_t reciprocal(uint32_t d) +{ + /* 2^40 / d from 2^32 = 0xffffffff + 1, in 32-bit steps. */ + uint32_t quotient = 0xffffffffu / d, remainder = 0xffffffffu % d + 1; + if (remainder == d) { + quotient++; + remainder = 0; + } + return ((uint64_t)quotient << 8) + (remainder << 8) / d + 1; +} + +static inline uint32_t divide(uint32_t x, uint64_t reciprocal_of_d) +{ + return (uint32_t)((x * reciprocal_of_d) >> 40); +} + +/* RGB565 words from and to RGB bytes. Unpacking widens by shifting, so a + * colour that is exactly 5-6-5 comes back unchanged. */ +static inline uint32_t rgb565_pack(const uint8_t *rgb) +{ + return (uint32_t)(rgb[0] >> 3) << 11 | (uint32_t)(rgb[1] >> 2) << 5 | rgb[2] >> 3; +} + +static inline void rgb565_unpack(uint32_t word, uint8_t rgb[3]) +{ + rgb[0] = (uint8_t)((word >> 11) << 3); + rgb[1] = (uint8_t)((word >> 5 & 63) << 2); + rgb[2] = (uint8_t)((word & 31) << 3); +} + +#endif diff --git a/extensions/appearance/render.c b/extensions/appearance/render.c new file mode 100644 index 0000000..ac0b8a7 --- /dev/null +++ b/extensions/appearance/render.c @@ -0,0 +1,395 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The stock screens draw in fixed colours, the light look's. Each draw passes + * one of the core's colour sites, where the colour says what is being drawn: + * light greys are surfaces, dark greys text, the stock blues accents, the + * white palette entry highlighted text. The handlers map each to its role and + * let the draw go on. The mapping is in functions of the colour and the + * view's id, which the hooks wrap. + * + * Derives from the core's former payload/dark_mode.c (01c89f6) by lgreitis and + * Alex Ball (alexballvideos-netizen). */ + +#include "render.h" +#include "catalog.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "pixel.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "style.h" +#include "tint.h" +#include + +/* Set while a view that keeps its light artwork fills its background, so + * the fill underneath stays stock too. */ +static int stock_fill; + +enum { + SURFACE_LIGHT_MIN = 0xb0, /* greys from here up are surfaces */ + TEXT_DARK_MAX = 0x80, /* greys to here are text */ + TEXT_WHITE_MIN = 0xf0, + TEXT_LIGHT_REFERENCE = + 0x20, /* the light look's text role; native black lies below it */ +}; + +/* Which of a bar view's own label colours a draw passes. */ +enum bar_slot { BAR_OTHER, BAR_LABEL, BAR_SELECTED }; + +static uint32_t view_id(uint32_t view) +{ + return RV_FIELD(view, View_id, uint32_t); +} + +static int same_rgb(const uint8_t *color, const uint8_t *other) +{ + return color[0] == other[0] && color[1] == other[1] && color[2] == other[2]; +} + +static int grey(const uint8_t *color) +{ + return color[0] == color[1] && color[1] == color[2]; +} + +static const uint8_t *recolor(const uint8_t *color, const uint8_t *target, uint8_t *out) +{ + out[0] = target[0]; + out[1] = target[1]; + out[2] = target[2]; + out[3] = color[3]; + return out; +} + +/* The role offset by the stock shade, so the stock gradations stay. */ +static const uint8_t *shade(const uint8_t *color, const uint8_t *target, int offset, + uint8_t *out) +{ + for (unsigned i = 0; i < 3; i++) + out[i] = (uint8_t)clamp(target[i] + offset, 0, 255); + out[3] = color[3]; + return out; +} + +/* Views whose labels keep their stock colour: they sit on their own art. */ +static int native_text(uint32_t view) +{ + switch (view) { + case RES_Alarms_PickDate_Preivew_NumericDay: + case RES_Settings_DateTime_NumericDay: + case RES_Settings_DateTime_Preivew_NumericDay: + return 1; + case RES_Search_Input_Text: + return !style_from_theme(); + default: + return 0; + } +} + +/* A label's colour in view `view`. White text on the stock blue-grey pane + * and on dark art takes the text role under a custom light background. */ +static const uint8_t *map_text(const uint8_t *color, uint32_t view, uint8_t *mapped) +{ + if (native_text(view)) + return color; + const uint8_t *text = style_color(RVT_ROLE_TEXT); + const uint8_t *field = + view == RES_Search_Input_Text ? tint_field_text_color() : NULL; + const uint8_t *art = tint_contrast_text_color(view); + if (art) + return recolor(color, art, mapped); + if (field && grey(color) && color[0] <= TEXT_DARK_MAX) + return recolor(color, field, mapped); + if (color == Palette_White) + return recolor(color, style_color(RVT_ROLE_ON_ACCENT), mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_ACCENT_FILL))) + return recolor(color, style_color(RVT_ROLE_ACCENT_FILL), mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_ACCENT_TEXT))) + return recolor(color, style_color(RVT_ROLE_ACCENT_TEXT), mapped); + if (grey(color) && color[0] <= TEXT_DARK_MAX) + return shade(color, text, + color_dark(text) ? color[0] - TEXT_LIGHT_REFERENCE + : -(color[0] / 2), + mapped); + if (grey(color) && color[0] >= TEXT_WHITE_MIN && style_from_theme() && + !color_dark(style_color(RVT_ROLE_BACKGROUND))) + return recolor(color, text, mapped); + return color; +} + +/* A fill's or clear's colour. */ +static const uint8_t *map_fill(const uint8_t *color, uint8_t *mapped) +{ + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + if (stock_fill) + return color; + if (grey(color) && color[0] >= SURFACE_LIGHT_MIN) + /* Lighter stock greys become darker surfaces; a dark role inverts that. */ + return shade(color, background, + color_dark(background) ? (255 - color[0]) / 4 : color[0] - 255, + mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_COVER_BORDER))) + return recolor(color, style_color(RVT_ROLE_COVER_BORDER), mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_ACCENT_FILL))) + return recolor(color, style_color(RVT_ROLE_ACCENT_FILL), mapped); + return color; +} + +/* Views that keep their light artwork in every look, so their background + * fill must stay stock too. */ +static int stock_background(uint32_t view) +{ + switch (view) { + case RES_NowPlaying_White_Background_View: + case RES_NowPlaying_Idle_Template: + case RES_NowPlaying_ChapterArt_BackgroundImage_View: + case RES_RentalInfo_White_Background_View: + return 1; + default: + return 0; + } +} + +/* Accents alone keep the stock clears and blends. */ +static int background_themed(void) +{ + return style_dark() || style_from_theme(); +} + +/* A bar's label: the highlighted one sits on the selection-tinted thumb, so + * it takes the on-accent colour; the others follow whatever contrasts with + * the well art. The Now Playing thumb follows no accent, so without a theme + * its label keeps the stock colour. */ +static const uint8_t *map_bar_label(const uint8_t *color, enum bar_slot slot, + unsigned well, uint8_t *mapped) +{ + const uint8_t *derived; + if (slot == BAR_SELECTED && well == WELL_NOW_PLAYING && !style_from_theme()) + return color; + if (slot == BAR_SELECTED) + return recolor(color, style_color(RVT_ROLE_ON_ACCENT), mapped); + if (slot == BAR_LABEL && (derived = tint_well_letter_color(well))) + return recolor(color, derived, mapped); + return color; +} + +/* A calendar day number: the shown month's in black on the active cell, a + * neighbouring month's in grey, the selected day's in white. */ +static const uint8_t *map_calendar_day(const uint8_t *color, uint8_t *mapped) +{ + const uint8_t *themed; + uint8_t mixed[4]; + if (color[0] == 255 && grey(color)) + themed = style_from_theme() ? style_color(RVT_ROLE_ON_ACCENT) : NULL; + else + themed = tint_calendar_text_color( + color[0] ? CALENDAR_INACTIVE : CALENDAR_ACTIVE, mixed); + return themed ? recolor(color, themed, mapped) : color; +} + +/* (context, rgba, view): every label. */ +static uint32_t text_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + uint8_t mapped[4]; + const uint8_t *color = map_text((const uint8_t *)rgba, view_id(view), mapped); + return api->hook_next(next, context, (uint32_t)color, view, 0, 0, 0); +} + +/* The colour a fill or clear onto `surface` uses. On a coverage mask the + * colour becomes coverage (255 minus its luminance): the white that clears a + * text bitmap must stay white, or the whole rectangle reads as covered. */ +static const uint8_t *fill_color(const void *surface, const uint8_t *color, + uint8_t *mapped) +{ + if ((RV_FIELD(surface, Surface_format, uint16_t) & ~BMapFormat_ByteSwapped) <= + BMapFormat_Mask8) + return color; + return map_fill(color, mapped); +} + +/* (surface, rect, rgba, mode, clip): every fill and clear. */ +static uint32_t fill_rect(uint32_t surface, uint32_t rect, uint32_t rgba, uint32_t mode, + const void *next, uint32_t clip) +{ + uint8_t mapped[4]; + const uint8_t *color = + fill_color((const void *)surface, (const uint8_t *)rgba, mapped); + return api->hook_next(next, surface, rect, (uint32_t)color, mode, clip, 0); +} + +/* The fill rule for the background of view `id`, returning the rule it + * replaces: a view drawn inside another's background gives it back. */ +static int enter_background(uint32_t id) +{ + int outer = stock_fill; + stock_fill = stock_background(id); + return outer; +} + +/* (context, rect, view): a view's background. */ +static uint32_t background_fill(uint32_t context, uint32_t rect, uint32_t view, + const void *next) +{ + int outer = enter_background(view_id(view)); + uint32_t result = api->hook_next(next, context, rect, view, 0, 0, 0); + stock_fill = outer; + return result; +} + +/* A channel as a 16.16 fraction of 255: c * 65536 / 255 is c * 257 plus one + * for c = 255. */ +static uint32_t fraction(uint8_t channel) +{ + return channel * 257u + ((channel + 1u) >> 8); +} + +/* (red, green, blue, alpha) in 16.16: the GLES clear behind Cover Flow and album art. */ +static uint32_t clear_color(uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha, + const void *next) +{ + if (background_themed()) { + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + red = fraction(background[0]); + green = fraction(background[1]); + blue = fraction(background[2]); + } + return api->hook_next(next, red, green, blue, alpha, 0, 0); +} + +/* (pixel, background, weight): the album art reflection fading to the background. */ +static uint32_t reflection_blend(uint32_t pixel, uint32_t background, uint32_t weight, + const void *next) +{ + if (background_themed()) + background = rgb565_pack(style_color(RVT_ROLE_BACKGROUND)); + return api->hook_next(next, pixel, background, weight, 0, 0, 0); +} + +/* (context, rgba, view): a bitmap view's mask colour. Tinted masks take their + * tint, or the on-accent colour while highlighted. */ +static uint32_t bitmap_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + const uint8_t *tinted = tint_mask_color((const void *)view); + return api->hook_next(next, context, tinted ? (uint32_t)tinted : rgba, view, 0, 0, + 0); +} + +/* Which of the view's two label colour fields `color` is, by address. */ +static enum bar_slot bar_slot(uint32_t rgba, uint32_t view, uint32_t label, + uint32_t selected) +{ + return rgba == view + selected ? BAR_SELECTED + : rgba == view + label ? BAR_LABEL + : BAR_OTHER; +} + +/* (context, rgba, view): the keyboard's key letters, on black well slices. */ +static uint32_t keyboard_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + uint8_t mapped[4]; + enum bar_slot slot = bar_slot(rgba, view, KeyboardView_letter_color, + KeyboardView_selected_letter_color); + const uint8_t *color = + map_bar_label((const uint8_t *)rgba, slot, WELL_BLACK, mapped); + return api->hook_next(next, context, (uint32_t)color, view, 0, 0, 0); +} + +/* (context, rgba, view): an option bar's segment labels. */ +static uint32_t option_bar_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + uint8_t mapped[4]; + const uint8_t *color = (const uint8_t *)rgba; + unsigned well = RV_FIELD(view, OptionBarView_style, uint8_t); + if (well < WELLS) + color = map_bar_label(color, + bar_slot(rgba, view, OptionBarView_label_color, + OptionBarView_selected_label_color), + well, mapped); + return api->hook_next(next, context, (uint32_t)color, view, 0, 0, 0); +} + +/* (context, rgba): a calendar day number. */ +static uint32_t calendar_day_color(uint32_t context, uint32_t rgba, const void *next) +{ + uint8_t mapped[4]; + const uint8_t *color = map_calendar_day((const uint8_t *)rgba, mapped); + return api->hook_next(next, context, (uint32_t)color, 0, 0, 0, 0); +} + +/* (context, rgba): the calendar's weekday names. */ +static uint32_t calendar_header_color(uint32_t context, uint32_t rgba, const void *next) +{ + uint8_t mapped[4], mixed[4]; + const uint8_t *color = (const uint8_t *)rgba; + const uint8_t *themed = tint_calendar_text_color(CALENDAR_HEADER, mixed); + if (themed) + color = recolor(color, themed, mapped); + return api->hook_next(next, context, (uint32_t)color, 0, 0, 0, 0); +} + +/* (context, source, source_rect, rect, alpha, flags, view): a bitmap view's or + * a menu row icon's blit, with the view the site pushes. */ +static uint32_t view_blit(uint32_t context, uint32_t source, uint32_t source_rect, + uint32_t rect, const void *next, uint32_t alpha, + uint32_t flags, uint32_t view) +{ + tint_highlight_begin((const void *)view, (const void *)source); + uint32_t result = + api->hook_next7(next, context, source, source_rect, rect, alpha, flags, view); + tint_highlight_end(); + return result; +} + +/* The same for a calendar day cell's marker, with the cell pushed. */ +static uint32_t marker_blit(uint32_t context, uint32_t source, uint32_t source_rect, + uint32_t rect, const void *next, uint32_t alpha, + uint32_t flags, uint32_t cell) +{ + tint_marker_highlight_begin((const void *)cell, (const void *)source); + uint32_t result = + api->hook_next7(next, context, source, source_rect, rect, alpha, flags, cell); + tint_highlight_end(); + return result; +} + +static const struct rv_hook themed_hooks[] = { + RV_HOOK_FILTER(RV_SITE_TextView_DrawColor_call, text_color), + RV_HOOK_FILTER(RV_SITE_MarqueeTextView_DrawColor_call, text_color), + RV_HOOK_FILTER(RV_SITE_GraphicsContext_FillRect_call, fill_rect), + RV_HOOK_FILTER(RV_SITE_GraphicsContext_ClearRect_call, fill_rect), + RV_HOOK_FILTER(RV_SITE_View_BackgroundFill_call, background_fill), + RV_HOOK_FILTER(RV_SITE_CoverFlow_ClearColor_call, clear_color), + RV_HOOK_FILTER(RV_SITE_AlbumArt_ClearColor_call, clear_color), + RV_HOOK_FILTER(RV_SITE_ArtworkReflection_Blend_call, reflection_blend), + RV_HOOK_FILTER(RV_SITE_BitmapView_DrawColor_call, bitmap_color), + RV_HOOK_FILTER(RV_SITE_KeyboardView_DrawColor_call, keyboard_color), + RV_HOOK_FILTER(RV_SITE_OptionBarView_DrawColor_call, option_bar_color), + RV_HOOK_FILTER(RV_SITE_CalendarDayCell_DrawColor_call, calendar_day_color), + RV_HOOK_FILTER(RV_SITE_CalendarView_DrawColor_call, calendar_header_color), + RV_HOOK_FILTER(RV_SITE_BitmapView_Blit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_BitmapView_TileBlit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_MenuRowBitmapView_Blit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_MenuRowBitmapView_TileBlit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_CalendarDayCell_TopMarkerBlit_call, marker_blit), + RV_HOOK_FILTER(RV_SITE_CalendarDayCell_BottomMarkerBlit_call, marker_blit), +}; +#define THEMED_HOOKS RV_COUNT(themed_hooks) + +static unsigned bound; /* how many of themed_hooks are bound, from the first */ + +int render_bind(int on) +{ + if (on) { + while (bound < THEMED_HOOKS && + api->hook_bind(self, &themed_hooks[bound]) == RV_OK) + bound++; + if (bound == THEMED_HOOKS) + return 1; + } + while (bound) + api->hook_unbind(self, &themed_hooks[--bound]); + return !on; +} diff --git a/extensions/appearance/render.h b/extensions/appearance/render.h new file mode 100644 index 0000000..de7ff79 --- /dev/null +++ b/extensions/appearance/render.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef RENDER_H +#define RENDER_H + +/* The draw hooks: the colour sites that map the stock colours to the roles in + * force, the blits that colour highlighted tinted art and the flat cover. + * Bound while a look other than stock light is on, unbound otherwise, so + * the stock look draws without them; 1 when the hooks are as asked. */ +int render_bind(int on); + +#endif diff --git a/extensions/appearance/screenshots/appearance.png b/extensions/appearance/screenshots/appearance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(i_h5{StwiQZu%ZfJH79Cgr7dCRj(@@VubD&qcYN$Tpr5Ma8(7f^ hg;-=-&-V?3EP_+$1j&pSc*7Owv$T>FRKh6W{{a*rmRSG* literal 0 HcmV?d00001 diff --git a/extensions/appearance/screenshots/dark-mode.png b/extensions/appearance/screenshots/dark-mode.png new file mode 100644 index 0000000000000000000000000000000000000000..6ff74da55372200a5a99a9a9c6a59acbedf785c6 GIT binary patch literal 25590 zcmXtAe*e^7>+G}7Q|EbZ ze6H(`_^u#{1dk67005G-l$bIAfC+=HuVBGJKR*=d_yK?vkQNhB^~gHw^p7Uc$f159 za+ugz2-{R8S_SAWVaj8YRPNgn$ymXQ5!P^A!P-KXrCL@*ii z{0dQ8<&EYh>4U3YpKm{y1s$|OkAz%&>n>~p#>d6mj(E?Nr#UxAGQ1EN&C0!J!Y0~Z z&K&J@Z?tfUxM9|wgMRZp1ZbY%LqH9#4gIA;X`HM9&$>F54R2CmBQ$LF8$}cOH)rkI z?-F@Si|4(ccd)e%UvU3s{Vi0n3W;BwA8j5hFMrURfE<12F0s;nwr}0?M!`fCz2TYp zB&;i70U!eUUe-=ZtPQ>K2WI<$(z!n@O@zN=L4UTvZWL47|1j^0xLo zlsKdr;B9yKi+@RLSJ6!Fe7ajiK*R^AC9p01(!YS=FsFi1iEOTXUC7~vL< zn9OzOE%f9#7WhgE8&rMTvf%eH|BJSr(wm^Uc5~KE&pmlc-VxX2RUZ(Bz2>j6$~cut z67I7B-5O@}0zHp{0L@0`U~HBUX^dF zbR@-WNNUZ4&05@!yC%-g67G(a$JhxN4zk{zrzpB{eWU%+%~Yhww{@7Bge(gfHjSU9 zGuRt>O6a#X1o3^#2~|OOe!TSw8piH&d7MnH(1;XbOfbG!@0zpaJU=f&NzoigfTo5O zJ;o_IQCCBSJT47k)NNCu`>2Ek(i7A7QBu%EPgK<2C6X=n-uOJ#)NU^iT`ZjU9!}I7 zuav;zY?trXXDpw!xY9zg6S!Au@2J#`U`PW45$@>dhq3M>PQEVZ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kg&1Y|?l`a@}zpo2^3{JfsRc_7W6SKmDP1==0 zD)h1sLY!-hKpK*n znXU%dd>6PCKI-N&bUtyRYJXI&(ni!%o9a!HFvmqS1-}vSlkP~s+Dre(kV+2YKzl}= zPwNDKfNXktX&$P%afhcl{as))v6%9xFz84z=0eN1gKq|j{bb`3#)1a4GBn5i9cmP5 xBlbk*m}(jHqdQQ}#^yxT1U^lmGMs()@z&MapFg|J28b_#hook_bind(self, &ram_colors) == RV_OK; + redraw(); + } else { + selection_bar_restore(); + } + redraw_play_state(); +} + +void selection_bar_restore(void) +{ + if (saved) { + memcpy(SelectionBar_RamGradient, stock_gradient, sizeof stock_gradient); + memcpy(SelectionBar_RamHighlight, stock_highlight, sizeof stock_highlight); + } + if (custom) + api->hook_unbind(self, &ram_colors); + custom = 0; + redraw(); +} diff --git a/extensions/appearance/selection_bar.h b/extensions/appearance/selection_bar.h new file mode 100644 index 0000000..8cae45c --- /dev/null +++ b/extensions/appearance/selection_bar.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef SELECTION_BAR_H +#define SELECTION_BAR_H + +/* Gives the selection bar the look's colours while they differ from stock and + * has the cached drawings, the bar and the Now Playing status icons, drawn + * again; after every switch and accent change. Restore puts the stock colours + * back. */ +void selection_bar_apply(void); +void selection_bar_restore(void); + +#endif diff --git a/extensions/appearance/services.h b/extensions/appearance/services.h new file mode 100644 index 0000000..20634b3 --- /dev/null +++ b/extensions/appearance/services.h @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The tables the two modules call each other through (modules share no + * symbols). `main` publishes main_service for as long as the extension is + * loaded; `switch` publishes switch_service between main's module_load and + * module_unload of it. */ + +#ifndef SERVICES_H +#define SERVICES_H +#include "catalog.h" +#include "assets.h" +#include "look.h" +#include "rv_api.h" +#include "rvt.h" +#include + +struct main_service { + struct look_state *state; + uint32_t (*crc32_update)(uint32_t crc, const void *data, uint32_t size); + uint32_t (*catalog_count)(void); + const uint8_t *(*catalog_fingerprint)(void); + uint8_t *(*catalog_data)(uint32_t index); + uint32_t (*catalog_size)(uint32_t index); + uint32_t (*catalog_crc)(uint32_t index); + uint32_t (*catalog_file_offset)(uint32_t index); + int (*catalog_layout)(uint32_t index, struct layout *b); + void (*style_set)(const uint8_t *prefix); + void (*style_reset)(void); + void (*style_set_dark)(int dark); + void (*style_set_accent)(unsigned accent); + void (*tint_refresh)(void); + void (*tint_accent_art)(const uint32_t *skip, uint32_t *touched); + int (*lz_decode)(struct rv_file *file, uint32_t stream_bytes, uint8_t *out, + uint32_t bytes, uint32_t *crc); + struct asset_entry *(*assets_reserve)(uint32_t count); + void (*assets_commit)(void); + void (*assets_drop)(void); +}; + +struct switch_service { + /* Streams the pack at `pack` out of `file` (a theme file or the classic + * asset, its header checked by main and summed in look->header_crc; NULL + * for the stock light look) into the resident bitmaps, restores what the + * previous look changed and this one leaves alone, applies the colours + * and tints the stock accent art. A failure after the first write + * restores everything and returns to the stock light look. */ + enum switch_result (*apply)(struct rv_file *file, const struct look *look, + const struct pack_place *pack); + /* Another accent for the current look: the accent art is restored and + * tinted again; no pack is read. */ + enum switch_result (*accent)(unsigned accent); + /* Puts every bitmap back and forgets the look. */ + void (*restore_all)(void); +}; + +#endif diff --git a/extensions/appearance/stock.c b/extensions/appearance/stock.c new file mode 100644 index 0000000..8a5f3b0 --- /dev/null +++ b/extensions/appearance/stock.c @@ -0,0 +1,104 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "stock.h" +#include "ext.h" +#include "rv_libc.h" +#include "switch.h" +#include + +static struct rv_file *kept; /* the file while a switch holds it open */ + +static struct rv_file *open_firmware(void) +{ + struct rv_file *file; + return api->firmware_open(self, &file) == RV_OK ? file : NULL; +} + +static int read_at(struct rv_file *file, uint32_t offset, void *out, uint32_t bytes) +{ + return api->file_seek(self, file, offset) == RV_OK && read_exact(file, out, bytes); +} + +static int crc_matches(uint32_t crc, uint32_t index) +{ + return (uint16_t)~crc == main_module->catalog_crc(index); +} + +/* Read in pieces through the stack. */ +int stock_file_matches(void) +{ + struct rv_file *file = open_firmware(); + uint8_t piece[256]; + if (!file) + return 0; + uint32_t last = main_module->catalog_count() - 1, + left = main_module->catalog_size(last); + uint32_t crc = 0xffffffffu; + int ok = + api->file_seek(self, file, main_module->catalog_file_offset(last)) == RV_OK; + while (ok && left) { + uint32_t n = left < sizeof piece ? left : sizeof piece; + ok = read_exact(file, piece, n); + crc = main_module->crc32_update(crc, piece, n); + left -= n; + } + api->file_close(self, file); + return ok && crc_matches(crc, last); +} + +int stock_open(void) +{ + if (!kept) + kept = open_firmware(); + return kept != NULL; +} + +void stock_close(void) +{ + if (kept) + api->file_close(self, kept); + kept = NULL; +} + +static int fetch(struct rv_file *file, uint32_t index, uint8_t *dest) +{ + struct layout b; + if (!main_module->catalog_layout(index, &b)) + return 0; + const uint8_t *bitmap = main_module->catalog_data(index); + uint32_t size = main_module->catalog_size(index) - b.start; + uint32_t crc = main_module->crc32_update(0xffffffffu, bitmap, b.start); + if (!read_at(file, main_module->catalog_file_offset(index) + b.start, dest, size) || + !crc_matches(main_module->crc32_update(crc, dest, size), index)) { + memset(dest, 0, size); + return 0; + } + return 1; +} + +int stock_fetch(uint32_t index, uint8_t *dest) +{ + if (kept) + return fetch(kept, index, dest); + struct rv_file *file = open_firmware(); + if (!file) + return 0; + int ok = fetch(file, index, dest); + api->file_close(self, file); + return ok; +} + +int stock_restore(const uint32_t *bitmaps) +{ + int opened = !kept && stock_open(), ok = kept != NULL; + for (uint32_t i = 0; ok && i < main_module->catalog_count(); i++) + if (bit_test(bitmaps, i)) { + struct layout b; + if (!main_module->catalog_layout(i, &b) || + !fetch(kept, i, main_module->catalog_data(i) + b.start)) + ok = 0; + } + if (opened) + stock_close(); + return ok; +} diff --git a/extensions/appearance/stock.h b/extensions/appearance/stock.h new file mode 100644 index 0000000..a7baf5c --- /dev/null +++ b/extensions/appearance/stock.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Stock artwork comes back from the firmware file: /osos-cfw.bin + * is Apple's image with the core appended, so every bitmap lies there at its + * catalog offset, unchanged. The file must be the image the iPod booted: it + * is checked once per session before a switch writes anything, so recovery + * is possible afterwards, and again after USB disk mode, which may have + * replaced it. */ + +#ifndef STOCK_H +#define STOCK_H +#include + +/* The file opens and its last bitmap carries the catalog's checksum, so it is + * the booted image. */ +int stock_file_matches(void); +/* Keeps the file open across one switch, so each fetch is a seek and a read; + * stock_fetch and stock_restore open it for themselves when it is not. */ +int stock_open(void); +void stock_close(void); +/* Reads one bitmap's bytes after its header into `dest` and checks them, with + * the resident header, against the stock checksum. 0 when they do not match; + * `dest` is then zero. */ +int stock_fetch(uint32_t index, uint8_t *dest); +/* stock_fetch of every bitmap set in `bitmaps` into its resident bitmap; 0 + * when one fails. */ +int stock_restore(const uint32_t *bitmaps); + +#endif diff --git a/extensions/appearance/style.c b/extensions/appearance/style.c new file mode 100644 index 0000000..9fb667b --- /dev/null +++ b/extensions/appearance/style.c @@ -0,0 +1,189 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "style.h" +#include "pixel.h" +#include "rv_libc.h" + +#define RGB(r, g, b) {r, g, b, 255} + +/* The stock look's roles, light then dark, in rvt_role order. The dark row's + * background, text, accent and border are the colours of the core's former Dark + * Mode, payload/dark_mode.c (147a6fb, 7ec554b), by lgreitis and Alex Ball + * (alexballvideos-netizen); the light row is Apple's. */ +static const uint8_t classic[2][RVT_ROLES][4] = { + {RGB(255, 255, 255), RGB(32, 32, 32), RGB(35, 108, 197), RGB(49, 133, 208), + RGB(255, 255, 255), RGB(35, 108, 197), RGB(126, 129, 131), RGB(49, 133, 208)}, + {RGB(24, 24, 24), RGB(232, 232, 232), RGB(0, 161, 255), RGB(0, 161, 255), + RGB(255, 255, 255), RGB(0, 161, 255), RGB(56, 56, 56), RGB(0, 161, 255)}, +}; + +/* The stock look's accents: fill and text, light then dark. Light colours keep + * 5:1 against white; dark fills keep 4.5:1 under white text and dark text 6:1 + * on the background. Blue is the stock colour itself. */ +static const uint8_t accents[RVT_ACCENTS][2][2][4] = { + {{RGB(35, 108, 197), RGB(49, 133, 208)}, {RGB(0, 161, 255), RGB(0, 161, 255)}}, + {{RGB(137, 68, 171), RGB(137, 68, 171)}, {RGB(150, 78, 188), RGB(218, 143, 255)}}, + {{RGB(196, 30, 86), RGB(196, 30, 86)}, {RGB(206, 38, 96), RGB(255, 100, 145)}}, + {{RGB(208, 32, 40), RGB(208, 32, 40)}, {RGB(212, 40, 48), RGB(255, 105, 97)}}, + {{RGB(184, 72, 0), RGB(184, 72, 0)}, {RGB(190, 76, 0), RGB(255, 159, 10)}}, + {{RGB(30, 128, 58), RGB(30, 128, 58)}, {RGB(32, 134, 62), RGB(48, 209, 88)}}, + {{RGB(0, 115, 120), RGB(0, 115, 120)}, {RGB(0, 120, 125), RGB(64, 210, 215)}}, + {{RGB(130, 101, 0), RGB(130, 101, 0)}, {RGB(132, 103, 0), RGB(255, 214, 10)}}, + {{RGB(92, 96, 102), RGB(92, 96, 102)}, {RGB(100, 104, 110), RGB(190, 194, 200)}}, +}; +#undef RGB + +const char *const accent_labels[ACCENTS] = { + "Theme", "Blue", "Teal", "Green", "Yellow", + "Orange", "Red", "Pink", "Purple", "Graphite", +}; + +/* The palette each listed accent is, in rvt_accent order. */ +static const uint8_t palette_of[ACCENTS - ACCENT_FIRST] = { + RVT_ACCENT_BLUE, RVT_ACCENT_TEAL, RVT_ACCENT_GREEN, + RVT_ACCENT_YELLOW, RVT_ACCENT_ORANGE, RVT_ACCENT_RED, + RVT_ACCENT_PINK, RVT_ACCENT_PURPLE, RVT_ACCENT_GRAPHITE, +}; + +/* Which palette slot of an accent replaces a role, plus one; 0 keeps the role. */ +static const uint8_t accent_slot[RVT_ROLES] = { + [RVT_ROLE_ACCENT_FILL] = RVT_SLOT_ACCENT_FILL + 1, + [RVT_ROLE_ACCENT_TEXT] = RVT_SLOT_ACCENT_TEXT + 1, + [RVT_ROLE_SELECTION] = RVT_SLOT_SELECTION + 1, + [RVT_ROLE_ON_ACCENT] = RVT_SLOT_ON_ACCENT + 1, + [RVT_ROLE_ICON_TINT] = RVT_SLOT_ICON_TINT + 1, +}; + +/* The pack's style prefix, tint roles packed two per byte. */ +static struct { + uint8_t colors[RVT_ROLES][4]; + uint32_t flags; + uint8_t accents[RVT_ACCENTS][RVT_ACCENT_SLOTS][4]; + uint8_t tint[RVT_CATALOG_MAX / 2]; +} pack; + +static int from_theme, dark; /* a pack's colours are in force; the dark appearance is */ +static unsigned accent; /* enum accent */ + +static unsigned palette(void) +{ + return palette_of[accent - ACCENT_FIRST]; +} + +void color_mix(uint8_t out[4], const uint8_t *from, const uint8_t *to, unsigned weight) +{ + for (unsigned i = 0; i < 3; i++) + out[i] = (uint8_t)div255(from[i] * (255 - weight) + to[i] * weight + 127); + out[3] = 255; +} + +const uint8_t *style_color(enum rvt_role role) +{ + if ((unsigned)role >= RVT_ROLES) + role = RVT_ROLE_TEXT; + if (from_theme) { + unsigned slot = accent_slot[role]; + return accent && slot ? pack.accents[palette()][slot - 1] : pack.colors[role]; + } + if (accent) { + const uint8_t (*preset)[4] = accents[palette()][dark]; + if (role == RVT_ROLE_ACCENT_FILL || role == RVT_ROLE_SELECTION) + return preset[0]; + if (role == RVT_ROLE_ACCENT_TEXT || role == RVT_ROLE_ICON_TINT) + return preset[1]; + } + return classic[dark][role]; +} + +const uint8_t *style_stock_color(enum rvt_role role) +{ + return classic[0][(unsigned)role < RVT_ROLES ? role : RVT_ROLE_TEXT]; +} + +void style_set(const uint8_t *prefix) +{ + const uint8_t *tint = prefix + RVT_STYLE_TINTS; + memcpy(pack.colors, prefix + RVT_STYLE_COLORS, sizeof pack.colors); + memcpy(&pack.flags, prefix + RVT_STYLE_FLAGS, sizeof pack.flags); + memcpy(pack.accents, prefix + RVT_STYLE_PALETTES, sizeof pack.accents); + for (unsigned i = 0; i < RVT_CATALOG_MAX; i += 2) + pack.tint[i / 2] = (uint8_t)((tint[i] & 15) | (tint[i + 1] << 4)); + from_theme = 1; +} + +void style_reset(void) +{ + from_theme = 0; +} + +int style_from_theme(void) +{ + return from_theme; +} + +void style_set_dark(int value) +{ + dark = !!value; +} + +int style_dark(void) +{ + return dark; +} + +void style_set_accent(unsigned value) +{ + accent = value < ACCENTS ? value : ACCENT_DEFAULT; +} + +unsigned style_accent(void) +{ + return accent; +} + +int style_not_stock(void) +{ + return dark || from_theme || style_accent_art_active(); +} + +unsigned style_flags(void) +{ + return from_theme ? pack.flags : 0; +} + +static unsigned tint_role(unsigned asset) +{ + if (!from_theme || asset >= RVT_CATALOG_MAX) + return RVT_TINT_NONE; + return (pack.tint[asset / 2] >> (asset % 2 * 4)) & 15; +} + +int style_tinted(unsigned asset) +{ + return tint_role(asset) != RVT_TINT_NONE; +} + +const uint8_t *style_tint_color(unsigned asset) +{ + return style_color((enum rvt_role)(tint_role(asset) - RVT_TINT_ROLE)); +} + +int style_accent_art_active(void) +{ + return from_theme || (accent && palette() != RVT_ACCENT_BLUE); +} + +/* The stock gradient's stops, lightened toward white by these / 255. */ +static const uint8_t bar_lift[3] = {64, 0, 140}; + +int style_selection_bar(uint8_t out[3][4]) +{ + static const uint8_t white[4] = {255, 255, 255, 255}; + int flat = style_flags() & RVT_FLAG_FLAT_SELECTION; + if (!flat && !style_accent_art_active()) + return 0; + const uint8_t *base = style_color(RVT_ROLE_SELECTION); + for (unsigned stop = 0; stop < 3; stop++) + color_mix(out[stop], base, white, flat ? 0 : bar_lift[stop]); + return 1; +} diff --git a/extensions/appearance/style.h b/extensions/appearance/style.h new file mode 100644 index 0000000..6aae069 --- /dev/null +++ b/extensions/appearance/style.h @@ -0,0 +1,62 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The colours in force: the roles of the stock look in light or dark, + * of a theme pack's style prefix, and of the accent chosen on top of either. + * Every colour is RGBA bytes, alpha 255. */ + +#ifndef STYLE_H +#define STYLE_H +#include "rvt.h" +#include + +/* The accent setting, in the order the list shows: Theme keeps the look's own + * accent colours, then the named accents. */ +enum accent { ACCENT_DEFAULT, ACCENT_FIRST, ACCENTS = ACCENT_FIRST + RVT_ACCENTS }; + +extern const char *const accent_labels[ACCENTS]; + +/* A role's colour under the current appearance and accent. */ +const uint8_t *style_color(enum rvt_role role); +/* A role's colour in the stock light look, which is what the stock screens + * draw in and the draw hooks recognise. */ +const uint8_t *style_stock_color(enum rvt_role role); +/* The style prefix of a theme pack (RVT_STYLE_BYTES) replaces the stock + * colours; reset returns to them. */ +void style_set(const uint8_t *prefix); +void style_reset(void); +int style_from_theme(void); +void style_set_dark(int dark); +int style_dark(void); +void style_set_accent(unsigned accent); +unsigned style_accent(void); +/* Anything but the stock light look with its own accent. */ +int style_not_stock(void); +/* RVT_FLAG_* of the pack, 0 for the stock look. */ +unsigned style_flags(void); +/* Whether a catalog bitmap is tinted, and the colour of the role it is + * tinted with; ask only for tinted ones. */ +int style_tinted(unsigned asset); +const uint8_t *style_tint_color(unsigned asset); +/* Whether stock accent artwork and the selection bar follow the colours: + * under a pack always, under the stock look for accents other than Blue. */ +int style_accent_art_active(void); +/* Gradient start, gradient end and top line of the selection bar; 0 keeps + * the stock bar. */ +int style_selection_bar(uint8_t out[3][4]); + +/* Weighted brightness scaled by 256 (black 0, white 255 * 256), and whether a + * colour reads as a dark surface. */ +static inline int color_brightness(const uint8_t *color) +{ + return 54 * color[0] + 183 * color[1] + 19 * color[2]; +} + +static inline int color_dark(const uint8_t *color) +{ + return color_brightness(color) < 128 * 256; +} + +/* Each channel of `from` moved toward `to` by weight / 255; `out` is opaque. */ +void color_mix(uint8_t out[4], const uint8_t *from, const uint8_t *to, unsigned weight); + +#endif diff --git a/extensions/appearance/switch.c b/extensions/appearance/switch.c new file mode 100644 index 0000000..481f21b --- /dev/null +++ b/extensions/appearance/switch.c @@ -0,0 +1,155 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The switch module: reads a theme file, derives artwork and restores stock + * bitmaps from the firmware file. Loaded for a switch, an accent change or + * unload. */ + +#include "switch.h" +#include "ext.h" +#include "pack.h" +#include "rv_libc.h" +#include "stock.h" +#include "style.h" + +const struct rv_api *api; +rv_extension_handle self; +const struct main_service *main_module; + +static int empty(const uint32_t *bits) +{ + for (unsigned i = 0; i < BITMAP_WORDS; i++) + if (bits[i]) + return 0; + return 1; +} + +static void accent_art_tint(struct look_state *s) +{ + memset(s->accented, 0, sizeof s->accented); + main_module->tint_accent_art(s->assets, s->accented); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + s->assets[i] |= s->accented[i]; +} + +/* The firmware file is checked against the resident bank once per session. */ +static int stock_usable(struct look_state *s) +{ + if (!s->stock_checked) + s->stock_checked = stock_file_matches(); + return s->stock_checked; +} + +/* Artwork is half changed: restore every bitmap either look touched and go + * back to the stock light look. When that fails every bitmap of the attempt + * stays marked, restored or not, so the next switch reads them all again, + * and the firmware file is checked again before it. */ +static enum switch_result recover(struct look_state *s, const uint32_t *touched) +{ + uint32_t restore[BITMAP_WORDS]; + for (unsigned i = 0; i < BITMAP_WORDS; i++) + restore[i] = s->assets[i] | touched[i]; + int restored = stock_restore(restore); + memset(&s->active, 0, sizeof s->active); + if (restored) { + memset(s->assets, 0, sizeof s->assets); + memset(s->accented, 0, sizeof s->accented); + } else { + memcpy(s->assets, restore, sizeof s->assets); + s->stock_checked = 0; + } + main_module->assets_drop(); + main_module->style_reset(); + main_module->style_set_dark(0); + main_module->style_set_accent(ACCENT_DEFAULT); + main_module->tint_refresh(); + return restored ? SWITCH_RECOVERED : SWITCH_RESTORE_FAILED; +} + +static enum switch_result switch_apply(struct rv_file *file, const struct look *look, + const struct pack_place *place) +{ + struct look_state *s = main_module->state; + uint32_t target[BITMAP_WORDS], restore[BITMAP_WORDS]; + struct pack pack; + enum switch_result result; + memset(target, 0, sizeof target); + if (!stock_usable(s) || (file && !pack_open(file, look->header_crc, place, &pack))) + return SWITCH_LOAD_FAILED; + /* The Classic dark art carries colours the stock look already has. */ + if (file && !look->id[0] && !pack_plain(&pack)) + return SWITCH_LOAD_FAILED; + if (!stock_open()) + return SWITCH_LOAD_FAILED; + int applied = !file || pack_apply(&pack, target, s->assets); + if (!applied && empty(target)) { + /* Nothing changed: the look on the screen keeps its bitmaps. */ + main_module->assets_reserve(0); + stock_close(); + return SWITCH_LOAD_FAILED; + } + for (unsigned i = 0; i < BITMAP_WORDS; i++) + restore[i] = s->assets[i] & ~target[i]; + if (!applied || !stock_restore(restore)) { + result = recover(s, target); + stock_close(); + return result; + } + s->active = *look; + memcpy(s->assets, target, sizeof s->assets); + if (file) + main_module->assets_commit(); + else + main_module->assets_drop(); + if (look->id[0]) + main_module->style_set((const uint8_t *)pack.style); + else + main_module->style_reset(); + main_module->style_set_dark(look->dark); + main_module->style_set_accent(look->accent); + main_module->tint_refresh(); + accent_art_tint(s); + stock_close(); + return SWITCH_OK; +} + +static enum switch_result switch_accent(unsigned accent) +{ + struct look_state *s = main_module->state; + if (!stock_usable(s)) + return SWITCH_LOAD_FAILED; + s->active.accent = accent; + main_module->style_set_accent(accent); + main_module->tint_refresh(); + if (!stock_restore(s->accented)) + return recover(s, s->assets); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + s->assets[i] &= ~s->accented[i]; + accent_art_tint(s); + return SWITCH_OK; +} + +static void switch_restore_all(void) +{ + struct look_state *s = main_module->state; + if (!empty(s->assets)) + stock_restore(s->assets); + memset(s->assets, 0, sizeof s->assets); + memset(s->accented, 0, sizeof s->accented); + memset(&s->active, 0, sizeof s->active); + main_module->assets_drop(); + main_module->style_reset(); +} + +static const struct switch_service service = {switch_apply, switch_accent, + switch_restore_all}; + +static const struct rv_descriptor module = {.size = sizeof module, .service = &service}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + main_module = api->module_service(self, 0); + return &module; +} diff --git a/extensions/appearance/switch.h b/extensions/appearance/switch.h new file mode 100644 index 0000000..8e3291a --- /dev/null +++ b/extensions/appearance/switch.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The switch module: loaded by main for one switch, accent change or unload, + * it streams a pack into the resident bitmaps and restores stock artwork from + * the firmware file. Its files reach main's catalog, checksum, style and + * tint code through main's service table. + * + * A switch streams the pack's artwork straight into the firmware's resident + * bitmaps and restores what the previous look changed from the firmware + * file, reading only the bitmaps that need it and checking each against its + * stock checksum, so nothing is staged in memory. A failure part way through + * restores every bitmap either look touched and brings back the stock light + * look; when that restore fails too, theming is off for the session. */ + +#ifndef SWITCH_H +#define SWITCH_H +#include "services.h" + +/* main's table, fetched by the module's entry. */ +extern const struct main_service *main_module; + +#endif diff --git a/extensions/appearance/tests/catalog.inc b/extensions/appearance/tests/catalog.inc new file mode 100644 index 0000000..019627b --- /dev/null +++ b/extensions/appearance/tests/catalog.inc @@ -0,0 +1,23 @@ +/* Hand-written for the host tests, in the shape tools/catalog_inc.py writes: + * a six-bitmap catalog over a host array: a mask, two paletted bitmaps of one + * layout, an RGB565 one with padding after it, an ARGB one and a paletted one + * with a wider palette. The checksums are filled in once the bank is built. */ +#define CATALOG_COUNT 6 +#define CATALOG_BASE ((uintptr_t)host_bank) +#define CATALOG_FILE_OFFSET 0x1000u +#define CATALOG_BANK_BYTES sizeof host_bank +static const uint8_t fingerprint[RVT_FINGERPRINT_BYTES] = {1, 2, 3, 4, 5, 6, 7, 8}; +static const uint32_t catalog_offsets[CATALOG_COUNT + 1] = { + AT_MASK | PAD(MASK_BYTES), AT_PALETTED | PAD(PALETTED_BYTES), AT_RGB | PAD(RGB_BYTES), + AT_SECOND | PAD(PALETTED_BYTES), AT_ARGB | PAD(ARGB_BYTES), AT_WIDE | PAD(WIDE_BYTES), + BANK_END, +}; +static uint16_t catalog_crcs[CATALOG_COUNT]; +static const uint16_t well_centers[3] = {1, 1, 1}; +static const uint16_t field_center = 1; +static const uint16_t calendar_cells[3] = {1, 1, 1}; +static const struct contrast_text contrast_text[] = { + {RES_NowPlaying_StatusBar_Text_View, 1, 1}, {0x0dad0101u, 4, 1}, {0x0dad0201u, 4, 1}, + {0x0dad0301u, 3, 1}, {0x0dad0401u, 2, 1}, +}; +static const struct accent_art accent_art[] = {{5, RVT_ROLE_ACCENT_FILL}}; diff --git a/extensions/appearance/tests/contracts.c b/extensions/appearance/tests/contracts.c new file mode 100644 index 0000000..a829a26 --- /dev/null +++ b/extensions/appearance/tests/contracts.c @@ -0,0 +1,2846 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The extension's logic against a bitmap bank and a firmware file in host + * memory: what a theme file must look like to be accepted, that no record + * writes outside the bitmap it names, what each derived record kind computes, + * how a switch recovers, how the folder is listed, and which colour each + * stock draw is mapped to. */ + +#include +#include +#include +#include +#include + +/* A BMap: format, stride, depth half-words, zeros, height and width words, the + * data length, then the bytes. */ +#define HEADER 28 +#define MASK_BYTES (HEADER + 4 * 2) /* 4 wide, 2 high, 8-bit mask, stride 4 */ +#define PALETTED_BYTES (HEADER + 4 + 2 * 4 + 4 * 2) /* 2 colours, 4 by 2 at 8 bits */ +#define RGB_BYTES (HEADER + 2 * 3) /* 1 by 3 RGB565, stride 2: padded in the bank */ +#define ARGB_BYTES (HEADER + 16 * 2) /* 4 by 2 BGRA, stride 16 */ +#define WIDE_BYTES (HEADER + 4 + 4 * 4 + 4 * 2) /* 4 colours, 4 by 2 at 8 bits */ +#define ALIGNED(n) (((n) + 3) & ~3u) +#define PAD(n) (ALIGNED(n) - (n)) + +enum { + AT_MASK = 0, + AT_PALETTED = AT_MASK + ALIGNED(MASK_BYTES), + AT_RGB = AT_PALETTED + ALIGNED(PALETTED_BYTES), + AT_SECOND = AT_RGB + ALIGNED(RGB_BYTES), + AT_ARGB = AT_SECOND + ALIGNED(PALETTED_BYTES), + AT_WIDE = AT_ARGB + ALIGNED(ARGB_BYTES), + BANK_END = AT_WIDE + WIDE_BYTES, +}; + +enum { MASK = 0, PALETTED = 1, RGB = 2, SECOND = 3, ARGB = 4, WIDE = 5 }; + +static uint8_t host_bank[BANK_END]; +static uint8_t stock_bank[sizeof host_bank]; + +uint8_t Palette_White[4] = {255, 255, 255, 255}; + +/* The main module's sources, then the switch module's; switch.c defines + * `api`, `self` and `main_module`. */ +#include "../catalog.c" +#include "../crc.c" +#include "../flat_cover.c" +#include "../assets.c" +#include "../latch.c" +#include "../look.c" +#include "../lz.c" +#include "../render.c" +#include "../selection_bar.c" +#include "../style.c" +#include "../theme.c" +#include "../theme_picker.c" +#include "../tint.c" +#include "../derive.c" +#include "../pack.c" +#include "../stock.c" +#include "../switch.c" + +/* The schedule's Apple side: a clock and one time zone. */ +static uint8_t clock_now[DateTime_bytes]; +static int16_t clock_zone; +static uint8_t clock_dst; + +int RTC_ReadDateTime(struct DateTime *out) +{ + memcpy(out, clock_now, sizeof clock_now); + return 1; +} + +void RTC_GetZoneOffsets(int16_t *zone_minutes, uint8_t *dst_minutes) +{ + *zone_minutes = clock_zone; + *dst_minutes = clock_dst; +} + +static uint8_t host_zones[TimeZone_Count * TimeZone_bytes]; +#define TimeZones host_zones +static uint8_t host_preferences[PreferencesFile_time_zone_id + 4]; +static uint8_t host_browser[MediaBrowser_preferences + sizeof(void *)]; +static uint8_t host_app[App_browser + sizeof(void *)]; +void *App = host_app; +#include "../../shared/sun.c" +#include "../../shared/schedule.c" +#include "../dark_mode.c" + +/* The file under test: an rv_file is a cursor into a byte buffer. */ +struct rv_file { + const uint8_t *data; + uint32_t size, at; +}; + +/* The firmware file: the bank as built, at CATALOG_FILE_OFFSET, copied when + * it is opened. */ +static uint8_t firmware_image[CATALOG_FILE_OFFSET + BANK_END]; +static struct rv_file firmware_file; +static int firmware_open_now, firmware_missing, opens, closes; +static int corrupt_asset = -1; /* this asset's last byte reads back wrong */ + +static int firmware_open(rv_extension_handle s, struct rv_file **file) +{ + (void)s; + if (firmware_missing) + return RV_NOT_FOUND; + assert(!firmware_open_now); + memcpy(firmware_image + CATALOG_FILE_OFFSET, stock_bank, sizeof stock_bank); + if (corrupt_asset >= 0) + firmware_image[CATALOG_FILE_OFFSET + offset_of((uint32_t)corrupt_asset) + + catalog_size((uint32_t)corrupt_asset) - 1] ^= 1; + firmware_file = (struct rv_file){firmware_image, sizeof firmware_image, 0}; + firmware_open_now = 1; + opens++; + *file = &firmware_file; + return RV_OK; +} + +/* The selection bar's RAM words and cached bitmap, and the Now Playing + * service lookup, which finds nothing here. */ +uint8_t SelectionBar_RamGradient[2][4], SelectionBar_RamHighlight[4], + SelectionGradient_Bitmap[0xa8]; + +void *UI_FindServiceById(uint32_t service_id) +{ + (void)service_id; + return NULL; +} + +void Model_Notify(void *model, uint32_t type, uint32_t property) +{ + (void)model; + (void)type; + (void)property; + assert(0); +} + +/* The album art view and the GLES buffer behind the flat cover. */ +static uint8_t cover_image[0x100]; +static uint16_t render_target[320 * 240]; +static int cover_view; + +void *GLAlbumArtView_GetImage(void *view) +{ + assert(view == &cover_view); + return cover_image; +} + +void GameGraphics_GetCurrentPixelBuffer(void **out_pixels) +{ + *out_pixels = render_target; +} + +static int file_read(rv_extension_handle s, struct rv_file *f, void *out, + uint32_t bytes, uint32_t *got) +{ + (void)s; + uint32_t n = f->at >= f->size ? 0 + : f->at + bytes > f->size ? f->size - f->at + : bytes; + memcpy(out, f->data + f->at, n); + f->at += n; + *got = n; + return RV_OK; +} + +static int file_seek(rv_extension_handle s, struct rv_file *f, uint32_t offset) +{ + (void)s; + f->at = offset; + return RV_OK; +} + +static int allocations, alloc_fails; /* blocks out; the next alloc returns NULL */ + +static void *alloc(rv_extension_handle s, uint32_t bytes) +{ + (void)s; + if (alloc_fails) { + alloc_fails = 0; + return NULL; + } + allocations++; + return calloc(1, bytes); +} + +static void release(rv_extension_handle s, void *block) +{ + (void)s; + allocations--; + free(block); +} + +/* hook_next records what a handler passed on and returns `next_result`. */ +static uint32_t passed[7], next_result = 0x600d; + +static uint32_t hook_next(const void *next, uint32_t a, uint32_t b, uint32_t c, + uint32_t d, uint32_t e, uint32_t f) +{ + (void)next; + passed[0] = a, passed[1] = b, passed[2] = c, passed[3] = d, passed[4] = e, + passed[5] = f; + return next_result; +} + +static int binds, + bind_failures_at; /* hooks bound now; the bind that fails (1-based), 0 for none */ + +static int hook_bind(rv_extension_handle s, const struct rv_hook *hook) +{ + (void)s; + (void)hook; + if (bind_failures_at && binds + 1 == bind_failures_at) + return RV_NO_MEMORY; + binds++; + return RV_OK; +} + +static int hook_unbind(rv_extension_handle s, const struct rv_hook *hook) +{ + (void)s; + (void)hook; + assert(binds > 0); + binds--; + return RV_OK; +} + +/* A record to build into a pack: `payload` bytes of `kind`. */ +struct rec { + uint32_t asset, kind, size; + const uint8_t *payload; +}; + +/* The Themes folder: names the listing returns, and files opened by id. */ +static const char *const *folder; +static unsigned folder_count; +static const char *unreadable; /* an id whose file does not open */ + +struct built { + uint8_t bytes[32768]; + uint32_t size; +}; +static struct built opened_theme, classic_asset; +static struct rv_file opened_file, classic_file; +static int open_files; +static const struct built *provided; /* the file content_open returns for PROVIDED_ID */ +#define PROVIDED_ID "test" +static void build_theme(struct built *b, const char *id, const char *name); +static void build_file_at(struct built *b, const char *id, const char *name, + uint32_t header_bytes, const struct rec *light, + uint32_t nlight, const struct rec *dark, uint32_t ndark, + const uint8_t *tint, const uint8_t *prefix); + +static int content_open(rv_extension_handle s, const char *name, struct rv_file **file) +{ + (void)s; + char id[RVT_ID_BYTES] = {0}; + assert(!strncmp(name, "Themes/", 7)); + size_t n = strlen(name + 7); + assert(n > 4 && n - 4 < sizeof id && !strcmp(name + 7 + n - 4, ".rvt")); + memcpy(id, name + 7, n - 4); + if (unreadable && !strcmp(id, unreadable)) + return RV_NOT_FOUND; + assert(!open_files); + if (provided && !strcmp(id, PROVIDED_ID)) { + opened_file = (struct rv_file){provided->bytes, provided->size, 0}; + } else { + build_theme(&opened_theme, id, "Named"); + opened_file = (struct rv_file){opened_theme.bytes, opened_theme.size, 0}; + } + *file = &opened_file; + open_files++; + return RV_OK; +} + +static void file_close(rv_extension_handle s, struct rv_file *file) +{ + (void)s; + if (file == &firmware_file) { + assert(firmware_open_now); + firmware_open_now = 0; + closes++; + return; + } + assert((file == &opened_file || file == &classic_file) && open_files == 1); + open_files--; +} + +static int content_list(rv_extension_handle s, const char *name, + void (*each)(const char *entry, int is_folder, void *arg), + void *arg) +{ + (void)s; + assert(!strcmp(name, "Themes")); + each("Sub", 1, arg); + for (unsigned i = 0; i < folder_count; i++) + each(folder[i], 0, arg); + return RV_OK; +} + +/* The settings store: ints by key, and the theme id string. */ +static int32_t setting_ints[8]; +static char theme_id_setting[RVT_ID_BYTES]; + +static int32_t setting_get_int(rv_extension_handle s, uint16_t key) +{ + (void)s; + return setting_ints[key]; +} + +static int setting_set_int(rv_extension_handle s, uint16_t key, int32_t value) +{ + (void)s; + setting_ints[key] = value; + if (key == KEY_DARK) + dark_mode_set(value); + return RV_OK; +} + +static uint32_t setting_read(rv_extension_handle s, uint16_t key, void *out, + uint32_t capacity) +{ + (void)s; + assert(key == KEY_THEME); + uint32_t n = (uint32_t)strlen(theme_id_setting); + memcpy(out, theme_id_setting, n < capacity ? n : capacity); + return n; +} + +static int setting_write(rv_extension_handle s, uint16_t key, uint8_t type, + const void *data, uint32_t bytes) +{ + (void)s; + assert(key == KEY_THEME && type == RV_SETTING_TYPE_STRING && + bytes < sizeof theme_id_setting); + memset(theme_id_setting, 0, sizeof theme_id_setting); + memcpy(theme_id_setting, data, bytes); + return RV_OK; +} + +/* The switch module loads on request; the classic asset is a plain dark pack. */ +static int module_loaded, module_load_fails; + +static int module_load(rv_extension_handle s, uint32_t module) +{ + (void)s; + assert(module == SWITCH_MODULE); + if (module_load_fails) + return RV_NO_MEMORY; + module_loaded = 1; + return RV_OK; +} + +static void module_unload(rv_extension_handle s, uint32_t module) +{ + (void)s; + assert(module == SWITCH_MODULE); + module_loaded = 0; +} + +static int asset_open(rv_extension_handle s, const char *name, struct rv_file **file) +{ + (void)s; + assert(!strcmp(name, "classic")); + build_file_at(&classic_asset, "classic", "Classic", RVT_HEADER_BYTES, NULL, 0, NULL, + 0, NULL, NULL); + classic_file = (struct rv_file){classic_asset.bytes, classic_asset.size, 0}; + *file = &classic_file; + open_files++; + return RV_OK; +} + +static const rv_color *canvas_colors; +static int redraws; + +static int ui_set_colors(rv_extension_handle s, const rv_color *colors) +{ + (void)s; + canvas_colors = colors; + return RV_OK; +} + +static void ui_refresh(rv_extension_handle s, const char *screen) +{ + (void)s; + assert(!strcmp(screen, "theme")); +} + +static void ui_redraw(rv_extension_handle s) +{ + (void)s; + redraws++; +} +static const struct rv_asset_provider *core_provider; +static int provider_held; /* another extension has it */ + +static int asset_set_provider(rv_extension_handle s, const struct rv_asset_provider *p) +{ + (void)s; + if (provider_held) + return RV_ALREADY_BOUND; + core_provider = p; + return RV_OK; +} + +static const struct main_service host_service = { + .state = &look_state, + .crc32_update = crc32_update, + .catalog_count = catalog_count, + .catalog_fingerprint = catalog_fingerprint, + .catalog_data = catalog_data, + .catalog_size = catalog_size, + .catalog_crc = catalog_crc, + .catalog_file_offset = catalog_file_offset, + .catalog_layout = catalog_layout, + .style_set = style_set, + .style_reset = style_reset, + .style_set_dark = style_set_dark, + .style_set_accent = style_set_accent, + .tint_refresh = tint_refresh, + .tint_accent_art = tint_accent_art, + .lz_decode = lz_decode, + .assets_reserve = assets_reserve, + .assets_commit = assets_commit, + .assets_drop = assets_drop, +}; + +static const void *module_service(rv_extension_handle s, uint32_t module) +{ + (void)s; + if (module == SWITCH_MODULE) + return module_loaded ? (const void *)&service : NULL; + assert(module == 0); + return &host_service; +} + +static int timers; + +static struct rv_timer *timer_start(rv_extension_handle s, uint32_t ms, int repeat, + void (*callback)(void *arg), void *arg) +{ + (void)s, (void)ms, (void)repeat, (void)callback, (void)arg; + timers++; + return (struct rv_timer *)&timers; +} + +static void timer_stop(rv_extension_handle s, struct rv_timer *timer) +{ + (void)s, (void)timer; + timers--; +} + +static void ui_pane_refresh(rv_extension_handle s) +{ + (void)s; +} +static struct rv_api fake = { + .hook_bind = hook_bind, + .hook_unbind = hook_unbind, + .hook_next = hook_next, + .file_read = file_read, + .file_seek = file_seek, + .file_close = file_close, + .alloc = alloc, + .free = release, + .content_open = content_open, + .content_list = content_list, + .module_service = module_service, + .setting_get_int = setting_get_int, + .setting_set_int = setting_set_int, + .setting_read = setting_read, + .setting_write = setting_write, + .module_load = module_load, + .module_unload = module_unload, + .asset_open = asset_open, + .ui_set_colors = ui_set_colors, + .ui_refresh = ui_refresh, + .ui_redraw = ui_redraw, + .asset_set_provider = asset_set_provider, + .firmware_open = firmware_open, + .timer_start = timer_start, + .timer_stop = timer_stop, + .ui_pane_refresh = ui_pane_refresh, +}; + +static void put16(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); +} + +static void put32(uint8_t *p, uint32_t v) +{ + put16(p, v); + put16(p + 2, v >> 16); +} + +static void bmap(uint8_t *p, uint32_t format, uint32_t stride, uint32_t depth, + uint32_t width, uint32_t height, uint32_t total) +{ + memset(p, 0, total); + put16(p, format); + put16(p + 4, stride); + put16(p + 6, depth); + put32(p + 16, height); + put32(p + 20, width); + put32(p + 24, total - HEADER); +} + +/* Palette entries are BGRA. Bitmap 1 is a light square with a darker icon + * pixel, as a relight expects; bitmap 3 is black and white; bitmap 5 holds + * the stock accent blue. */ +static const uint8_t LIGHT[4] = {247, 244, 240, 255}, ICON[4] = {216, 208, 200, 255}; +static const uint8_t BLACK[4] = {0, 0, 0, 255}, WHITE[4] = {255, 255, 255, 255}; +static const uint8_t BLUE[4] = {197, 108, 35, 255}, GREY[4] = {128, 128, 128, 255}; + +static void build_bank(void) +{ + uint8_t *p = host_bank; + bmap(p, 8, 4, 8, 4, 2, MASK_BYTES); + memcpy(p + HEADER, (uint8_t[]){0, 149, 150, 255, 1, 2, 3, 4}, 8); + p = host_bank + AT_PALETTED; + bmap(p, 0x64, 4, 8, 4, 2, PALETTED_BYTES); + put32(p + HEADER, 2); + memcpy(p + HEADER + 4, LIGHT, 4); + memcpy(p + HEADER + 8, ICON, 4); + memcpy(p + HEADER + 12, (uint8_t[]){0, 0, 1, 0, 0, 1, 1, 0}, 8); + p = host_bank + AT_RGB; + bmap(p, 0x565, 2, 16, 1, 3, RGB_BYTES); + p = host_bank + AT_SECOND; + bmap(p, 0x64, 4, 8, 4, 2, PALETTED_BYTES); + put32(p + HEADER, 2); + memcpy(p + HEADER + 4, BLACK, 4); + memcpy(p + HEADER + 8, WHITE, 4); + memcpy(p + HEADER + 12, (uint8_t[]){0, 1, 0, 1, 1, 0, 1, 0}, 8); + p = host_bank + AT_ARGB; + bmap(p, 0x1888, 16, 32, 4, 2, ARGB_BYTES); + for (unsigned i = 0; i < 8; i++) + memcpy(p + HEADER + i * 4, i % 3 ? WHITE : BLUE, 4); + p[HEADER + 7 * 4 + 3] = 0; /* one clear pixel */ + p = host_bank + AT_WIDE; + bmap(p, 0x64, 4, 8, 4, 2, WIDE_BYTES); + put32(p + HEADER, 4); + memcpy(p + HEADER + 4, BLUE, 4); + memcpy(p + HEADER + 8, GREY, 4); + memcpy(p + HEADER + 12, BLACK, 4); + memcpy(p + HEADER + 16, WHITE, 4); + memcpy(p + HEADER + 20, (uint8_t[]){0, 1, 2, 3, 3, 2, 1, 0}, 8); + memcpy(stock_bank, host_bank, sizeof host_bank); + for (uint32_t i = 0; i < CATALOG_COUNT; i++) + catalog_crcs[i] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(i), catalog_size(i)); +} + +static void reset_bank(void) +{ + memcpy(host_bank, stock_bank, sizeof host_bank); +} + +static int bank_is_stock(void) +{ + return !memcmp(host_bank, stock_bank, sizeof host_bank); +} + +static uint32_t crc(const void *data, uint32_t size) +{ + return ~crc32_update(0xffffffffu, data, size); +} + +/* An opaque style prefix with the stock light roles and no tints. */ +static void prefix_plain(uint8_t *p) +{ + memset(p, 0, RVT_STYLE_BYTES); + for (unsigned i = 0; i < RVT_ROLES; i++) + memcpy(p + RVT_STYLE_COLORS + i * 4, style_stock_color((enum rvt_role)i), 4); + for (unsigned i = 0; i < RVT_ACCENTS * RVT_ACCENT_SLOTS; i++) + p[RVT_STYLE_PALETTES + i * 4 + 3] = 255; +} + +/* Extension bitmaps appended to every pack written while `asset_table` is set. */ +struct asset_payload { + uint32_t owner, asset, kind, size, decoded; + const uint8_t *payload; + uint32_t tint; +}; +static const struct asset_payload *asset_table; +static uint32_t asset_table_count; + +/* Writes one pack at `pack`; returns the bytes written (header and body). */ +static uint32_t write_pack(uint8_t *pack, const struct rec *recs, uint32_t count, + const uint8_t *tint, const uint8_t *prefix) +{ + uint8_t *body = pack + RVT_PACK_HEADER_BYTES, *p = body; + if (prefix) + memcpy(p, prefix, RVT_STYLE_BYTES); + else + prefix_plain(p); + if (tint) + memcpy(p + RVT_STYLE_TINTS, tint, RVT_CATALOG_MAX); + p += RVT_STYLE_BYTES; + for (uint32_t i = 0; i < count; i++) { + put32(p, recs[i].asset); + put32(p + 4, recs[i].kind); + put32(p + 8, recs[i].size); + p += 12; + memcpy(p, recs[i].payload, recs[i].size); + memset(p + recs[i].size, 0, ALIGNED(recs[i].size) - recs[i].size); + p += ALIGNED(recs[i].size); + } + for (uint32_t i = 0; i < asset_table_count; i++) { + const struct asset_payload *a = asset_table + i; + put32(p, a->owner); + put32(p + 4, a->asset); + put32(p + 8, a->kind); + put32(p + 12, a->size); + put32(p + 16, a->decoded); + put32(p + 20, a->tint); + p += RVT_EXTENSION_BITMAP_BYTES; + memcpy(p, a->payload, a->size); + memset(p + a->size, 0, PAD(a->size)); + p += ALIGNED(a->size); + } + uint32_t body_bytes = (uint32_t)(p - body); + put32(pack + RVT_PACK_BODY_BYTES, body_bytes); + put32(pack + RVT_PACK_RECORDS, count); + put32(pack + RVT_PACK_CRC, crc(body, body_bytes)); + put32(pack + RVT_PACK_EXTENSION_BITMAPS, asset_table_count); + return RVT_PACK_HEADER_BYTES + body_bytes; +} + +/* Recomputes the dark pack's body checksum of a file built without a light + * pack, after a test edited the body. */ +static void resign_dark_pack(struct built *b) +{ + uint8_t *pack = b->bytes + RVT_HEADER_BYTES; + put32(pack + RVT_PACK_CRC, + crc(pack + RVT_PACK_HEADER_BYTES, le32(pack + RVT_PACK_BODY_BYTES))); +} + +static void sign_header(struct built *b) +{ + put32(b->bytes + RVT_HEADER_CRC, 0); + put32(b->bytes + RVT_HEADER_CRC, crc(b->bytes, RVT_HEADER_BYTES)); +} + +/* A theme file: a light pack when `light` is given, then the dark pack, with + * the packs starting at `header_bytes`. */ +static void build_file_at(struct built *b, const char *id, const char *name, + uint32_t header_bytes, const struct rec *light, + uint32_t nlight, const struct rec *dark, uint32_t ndark, + const uint8_t *tint, const uint8_t *prefix) +{ + uint8_t *h = b->bytes; + memset(b, 0, sizeof *b); + memcpy(h + RVT_HEADER_MAGIC, "RVT0", 4); + put16(h + RVT_HEADER_VERSION, RVT_VERSION); + put16(h + RVT_HEADER_HEADER_BYTES, header_bytes); + memcpy(h + RVT_HEADER_FINGERPRINT, fingerprint, RVT_FINGERPRINT_BYTES); + put32(h + RVT_HEADER_APPEARANCES, + RVT_APPEARANCE_DARK | (light ? RVT_APPEARANCE_LIGHT : 0)); + strcpy((char *)h + RVT_HEADER_ID, id); + strcpy((char *)h + RVT_HEADER_NAME, name); + uint32_t at = header_bytes; + if (light) { + uint32_t size = write_pack(h + at, light, nlight, NULL, prefix); + put32(h + RVT_HEADER_LIGHT_OFFSET, at); + put32(h + RVT_HEADER_LIGHT_BYTES, size); + at += size; + } + uint32_t size = write_pack(h + at, dark, ndark, tint, prefix); + put32(h + RVT_HEADER_DARK_OFFSET, at); + put32(h + RVT_HEADER_DARK_BYTES, size); + sign_header(b); + b->size = at + size; +} + +/* A theme file with the light pack only. */ +static void build_light_only(struct built *b, const char *id, const char *name) +{ + uint8_t *h = b->bytes; + memset(b, 0, sizeof *b); + memcpy(h + RVT_HEADER_MAGIC, "RVT0", 4); + put16(h + RVT_HEADER_VERSION, RVT_VERSION); + put16(h + RVT_HEADER_HEADER_BYTES, RVT_HEADER_BYTES); + memcpy(h + RVT_HEADER_FINGERPRINT, fingerprint, RVT_FINGERPRINT_BYTES); + put32(h + RVT_HEADER_APPEARANCES, RVT_APPEARANCE_LIGHT); + strcpy((char *)h + RVT_HEADER_ID, id); + strcpy((char *)h + RVT_HEADER_NAME, name); + uint32_t size = write_pack(h + RVT_HEADER_BYTES, NULL, 0, NULL, NULL); + put32(h + RVT_HEADER_LIGHT_OFFSET, RVT_HEADER_BYTES); + put32(h + RVT_HEADER_LIGHT_BYTES, size); + sign_header(b); + b->size = RVT_HEADER_BYTES + size; +} + +static void build_file(struct built *b, const struct rec *light, uint32_t nlight, + const struct rec *dark, uint32_t ndark, const uint8_t *tint) +{ + build_file_at(b, "test", "Test", RVT_HEADER_BYTES, light, nlight, dark, ndark, tint, + NULL); +} + +static void build(struct built *b, const struct rec *dark, uint32_t ndark, + const uint8_t *tint) +{ + build_file(b, NULL, 0, dark, ndark, tint); +} + +static void build_theme(struct built *b, const char *id, const char *name) +{ + build_file_at(b, id, name, RVT_HEADER_BYTES, NULL, 0, NULL, 0, NULL, NULL); +} + +static uint32_t record_at(uint32_t i) +{ + return RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + RVT_STYLE_BYTES + i; +} + +static const uint32_t none[BITMAP_WORDS]; +static const struct look TEST_LOOK = {.id = "test", .dark = 1}; + +/* As main and the switch read a file: the header checked and the dark pack + * placed by main, opened and applied by the switch. */ +static int apply_from(struct built *b, uint32_t *assets, const uint32_t *current) +{ + struct rv_file file = {b->bytes, b->size, 0}; + struct look look = TEST_LOOK; + struct pack_place place; + struct pack pack; + memset(assets, 0, BITMAP_WORDS * 4); + stock_open(); + int ok = look_pack_place(&file, &look, &place) && + pack_open(&file, look.header_crc, &place, &pack) && + pack_apply(&pack, assets, current ? current : none); + stock_close(); + /* As the switch does with the index the pack filled. */ + if (ok) + assets_commit(); + else + assets_reserve(0); + assert(allocations == (live_count ? 1 : 0)); + return ok; +} + +/* A switch of `look` to the file `b`, placed as main places it. */ +static enum switch_result switch_to(struct built *b, struct look *look) +{ + struct rv_file file = {b->bytes, b->size, 0}; + struct pack_place place; + if (!look_pack_place(&file, look, &place)) + return SWITCH_LOAD_FAILED; + return switch_apply(&file, look, &place); +} + +static int apply(struct built *b, uint32_t *assets) +{ + return apply_from(b, assets, NULL); +} + +static struct rec pixels(uint32_t asset, const uint8_t *payload) +{ + struct layout l; + assert(catalog_layout(asset, &l)); + return (struct rec){asset, RVT_KIND_PIXELS, catalog_size(asset) - l.start, payload}; +} + +static uint32_t at_data(uint32_t asset) +{ + struct layout l; + assert(catalog_layout(asset, &l)); + return l.start; +} + +/* Relight vectors from the themes compiler's reference arithmetic + * (rvt/derive.py), pinned: a bitmap's bytes after the header in the WIDE or + * PALETTED layout, the rule, and what the iPod must produce. */ +static const uint8_t wide_plain_in[] = {4, 0, 0, 0, 230, 236, 240, 255, 70, 80, + 90, 255, 150, 160, 170, 255, 255, 255, 255, 255, + 0, 1, 2, 1, 0, 2, 3, 0}; +static const int32_t wide_plain_rule[RVT_RELIGHT_WORDS] = { + 768, 15360, 25600, 60416, 256, 25600, 25856, 26112, 0, 128, 26112, 26368}; +static const uint8_t wide_plain_out[] = { + 4, 0, 0, 0, 100, 100, 100, 255, 101, 101, 101, 255, 102, 102, + 102, 255, 103, 103, 103, 255, 0, 2, 2, 2, 0, 3, 1, 0}; +/* A partly covered pixel without a fully covered neighbour is pruned. */ +static const uint8_t wide_shadow_in[] = {4, 0, 0, 0, 250, 250, 250, 255, 0, 0, + 0, 255, 242, 242, 242, 255, 200, 200, 200, 255, + 0, 2, 0, 0, 0, 0, 0, 1}; +static const int32_t wide_shadow_rule[RVT_RELIGHT_WORDS] = { + 512, 10240, 40960, 64000, 256, 38400, 38656, 35840, 40, -256, 38912, 39168}; +static const uint8_t wide_shadow_out[] = {4, 0, 0, 0, 151, 151, 151, 255, 152, 152, + 152, 255, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1}; +static const uint8_t paletted_two_in[] = {2, 0, 0, 0, 240, 244, 247, 255, 200, 208, + 216, 255, 0, 0, 1, 0, 0, 1, 1, 0}; +static const int32_t paletted_two_rule[RVT_RELIGHT_WORDS] = { + 768, 3584, 6400, 55296, 91, 6144, 6144, 101018, -300, -453, 6400, 6400}; +static const uint8_t paletted_two_out[] = {2, 0, 0, 0, 24, 24, 24, 255, 25, 25, + 25, 255, 0, 0, 1, 0, 0, 1, 1, 0}; + +static void expect_relight(uint32_t asset, const uint8_t *in, const int32_t *rule, + const uint8_t *out) +{ + struct built b; + uint32_t assets[BITMAP_WORDS], + at = (uint32_t)(catalog_data(asset) - host_bank) + HEADER; + uint32_t size = catalog_size(asset) - HEADER; + uint8_t kept[WIDE_BYTES]; + memcpy(kept, stock_bank + at, size); + memcpy(stock_bank + at, in, size); + reset_bank(); + catalog_crcs[asset] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(asset), catalog_size(asset)); + struct rec relight = {asset, RVT_KIND_RELIGHT, RVT_RELIGHT_BYTES, + (const uint8_t *)rule}; + build(&b, &relight, 1, NULL); + assert(apply(&b, assets) && !memcmp(catalog_data(asset) + HEADER, out, size)); + memcpy(stock_bank + at, kept, size); + reset_bank(); + catalog_crcs[asset] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(asset), catalog_size(asset)); +} + +static void reader_contracts(void) +{ + uint32_t assets[BITMAP_WORDS]; + struct built b; + struct look look; + struct pack_place place; + struct rv_file file, *opened; + char provided_id[RVT_ID_BYTES] = PROVIDED_ID; + + /* An empty pack is a valid theme, and the header reader sees its name. */ + build(&b, NULL, 0, NULL); + provided = &b; + assert(theme_open(provided_id, 1, &opened, &look, &place) == THEME_OK && + !strcmp(look.name, "Test") && look.appearances == RVT_APPEARANCE_DARK && + place.offset == RVT_HEADER_BYTES && + place.bytes == b.size - RVT_HEADER_BYTES); + file_close(NULL, opened); + provided = NULL; + assert(apply(&b, assets)); + + /* A record replaces exactly the bytes after the header, and after the + * colour count of a paletted bitmap; palette indices are checked. */ + uint8_t mask[4 * 2] = {1, 2, 3, 4, 5, 6, 7, 8}; + uint8_t paletted[2 * 4 + 4 * 2] = {9, 9, 9, 255, 8, 8, 8, 255, + 0, 1, 0, 1, 1, 0, 1, 0}; + struct rec two[2] = {pixels(MASK, mask), pixels(PALETTED, paletted)}; + build(&b, two, 2, NULL); + assert(apply(&b, assets) && bit_test(assets, 0) && bit_test(assets, 1) && + !bit_test(assets, 2)); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + assert(!memcmp(catalog_data(PALETTED) + HEADER + 4, paletted, sizeof paletted)); + paletted[8] = 2; /* an index past the two colours */ + build(&b, two, 2, NULL); + assert(!apply(&b, assets)); + assert(catalog_data(PALETTED)[HEADER + 4 + 8] == + 0); /* zeroed, never left half written */ + paletted[8] = 0; + reset_bank(); + + /* Records out of order, repeated, naming a size that is not the bitmap's + * or an unknown kind are refused. */ + struct rec reversed[2] = {pixels(PALETTED, paletted), pixels(MASK, mask)}; + build(&b, reversed, 2, NULL); + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + put32(b.bytes + record_at(8), sizeof mask + 4); + assert(!apply(&b, assets)); + struct rec unknown = {MASK, RVT_KINDS, sizeof mask, mask}; + build(&b, &unknown, 1, NULL); + assert(!apply(&b, assets)); + + /* The body checksum, the header checksum, the fingerprint and the magic + * each guard the file. */ + build(&b, two, 2, NULL); + b.bytes[b.size - 1] ^= 1; + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + b.bytes[RVT_HEADER_NAME] = 'U'; + file = (struct rv_file){b.bytes, b.size, 0}; + look = TEST_LOOK; + assert(!look_pack_place(&file, &look, &place)); + build(&b, two, 2, NULL); + b.bytes[RVT_HEADER_FINGERPRINT] ^= 1; + sign_header(&b); + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + b.bytes[RVT_HEADER_MAGIC] = 'X'; + sign_header(&b); + assert(!apply(&b, assets)); + /* Exactly the format version; another id than the file name's. */ + build(&b, two, 2, NULL); + put16(b.bytes + RVT_HEADER_VERSION, RVT_VERSION + 1); + sign_header(&b); + assert(!apply(&b, assets)); + put16(b.bytes + RVT_HEADER_VERSION, RVT_VERSION - 1); + sign_header(&b); + assert(!apply(&b, assets)); + build_file_at(&b, "other", "Test", RVT_HEADER_BYTES, NULL, 0, two, 2, NULL, NULL); + assert(!apply(&b, assets)); + reset_bank(); + + /* The packs start at the header's own size, a whole number of words: a + * pack before it is refused, one after a larger header is read; the + * switch sees the file main checked by its header checksum. */ + build(&b, two, 2, NULL); + put16(b.bytes + RVT_HEADER_HEADER_BYTES, RVT_HEADER_BYTES + 4); + sign_header(&b); + assert(!apply(&b, assets)); + build_file_at(&b, "test", "Test", RVT_HEADER_BYTES + 8, NULL, 0, two, 2, NULL, + NULL); + assert(apply(&b, assets) && + !memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + build_file_at(&b, "test", "Test", RVT_HEADER_BYTES - 4, NULL, 0, two, 2, NULL, + NULL); + assert(!apply(&b, assets)); + build_file_at(&b, "test", "Test", RVT_HEADER_BYTES + 2, NULL, 0, two, 2, NULL, + NULL); + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + file = (struct rv_file){b.bytes, b.size, 0}; + look = TEST_LOOK; + assert(look_pack_place(&file, &look, &place)); + { + struct pack pack; + assert(!pack_open(&file, look.header_crc ^ 1, &place, &pack)); + assert(pack_open(&file, look.header_crc, &place, &pack) && pack.count == 2); + } + reset_bank(); + + /* Ids and names: lower-case ASCII ids that are not the built-in's, + * printable UTF-8 names. */ + static const char *const good_ids[] = {"a", "example", "a-b_c9", + "0123456789012345678901234567890"}; + static const char *const bad_ids[] = { + "", "Example", "-a", "a b", "classic", "01234567890123456789012345678901"}; + char id[RVT_ID_BYTES]; + for (unsigned i = 0; i < sizeof good_ids / sizeof *good_ids; i++) { + memset(id, 0, sizeof id); + strcpy(id, good_ids[i]); + assert(id_valid(id)); + } + for (unsigned i = 0; i < sizeof bad_ids / sizeof *bad_ids; i++) { + memset(id, 0, sizeof id); + memcpy(id, bad_ids[i], + strlen(bad_ids[i]) < sizeof id ? strlen(bad_ids[i]) : sizeof id); + assert(!id_valid(id)); + } + uint8_t name[RVT_NAME_BYTES] = "Caf\xc3\xa9"; + assert(name_valid(name, sizeof name)); + name[5] = 1; /* a control character after the NUL is not zero padding */ + assert(!name_valid(name, sizeof name)); + name[5] = 0; + name[0] = 0x7f; + assert(!name_valid(name, sizeof name)); + name[0] = 0; + assert(!name_valid(name, sizeof name)); + memset(name, 'a', sizeof name); /* no NUL inside the field */ + assert(!name_valid(name, sizeof name)); + memcpy(name, "\xed\xa0\x80\0", 4); /* a surrogate */ + assert(!name_valid(name, sizeof name)); + + /* A style with a tint byte outside the roles or on a bitmap past the + * catalog, or a clear colour, is refused before anything is written. */ + uint8_t tint[RVT_CATALOG_MAX] = {0}; + tint[MASK] = RVT_TINT_ROLE + RVT_ROLES; + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[MASK] = 0; + tint[CATALOG_COUNT] = RVT_TINT_ROLE + RVT_ROLE_TEXT; + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[CATALOG_COUNT] = 0; + build(&b, NULL, 0, NULL); + b.bytes[RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + RVT_STYLE_COLORS + 3] = 0; + assert(!apply(&b, assets)); + + /* A tinted mask needs no record. A tinted paletted asset without one is + * tinted stock art: with darkness coverage its alpha follows its luma. */ + tint[MASK] = RVT_TINT_ROLE + RVT_ROLE_TEXT; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && !bit_test(assets, MASK)); + tint[MASK] = 0; + tint[SECOND] = (RVT_TINT_ROLE + RVT_ROLE_ICON_TINT) | RVT_TINT_DARKNESS; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && bit_test(assets, SECOND)); + assert(catalog_data(SECOND)[at_data(SECOND) + 3] == 255 && + catalog_data(SECOND)[at_data(SECOND) + 7] == 0); + reset_bank(); + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && + !memcmp(catalog_data(SECOND) + at_data(SECOND), BLACK, 4)); + tint[SECOND] = RVT_TINT_DARKNESS; /* darkness without a tint */ + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[SECOND] = 0; + + /* Solid coverage rewrites a mask's stock levels: full from the floor up, + * the rest kept; on a palette it rounds the alpha the same way. Both + * coverage bits together are invalid. */ + tint[MASK] = (RVT_TINT_ROLE + RVT_ROLE_TEXT) | RVT_TINT_SOLID; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && bit_test(assets, MASK)); + assert(!memcmp(catalog_data(MASK) + HEADER, + (uint8_t[]){0, 149, 255, 255, 1, 2, 3, 4}, 8)); + reset_bank(); + tint[MASK] = (RVT_TINT_ROLE + RVT_ROLE_TEXT) | RVT_TINT_SOLID | RVT_TINT_DARKNESS; + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[MASK] = 0; + tint[PALETTED] = (RVT_TINT_ROLE + RVT_ROLE_TEXT) | RVT_TINT_SOLID; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && bit_test(assets, PALETTED)); + assert(catalog_data(PALETTED)[at_data(PALETTED) + 3] == 255 && + catalog_data(PALETTED)[at_data(PALETTED) + 7] == 255); + reset_bank(); + tint[PALETTED] = 0; + + /* Recolour: a swap is two lookups against the stock colours, not a chain; + * RGB565 colours must be exact; ARGB pixels are keyed like palette + * entries, clear ones included; the count must match the payload and stay + * within RVT_RECOLOR_MAX. */ + uint8_t swap[4 + 16] = {2, 0, 0, 0, 0, 0, 0, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 0, 0, 0, 255}; + struct rec recolor = {SECOND, RVT_KIND_RECOLOR, sizeof swap, swap}; + build(&b, &recolor, 1, NULL); + assert(apply(&b, assets) && bit_test(assets, SECOND)); + assert(!memcmp(catalog_data(SECOND) + at_data(SECOND), WHITE, 4) && + !memcmp(catalog_data(SECOND) + at_data(SECOND) + 4, BLACK, 4)); + reset_bank(); + uint8_t unsorted[4 + 16]; + memcpy(unsorted, swap, sizeof swap); + memcpy(unsorted + 4, swap + 12, 8); + memcpy(unsorted + 12, swap + 4, 8); + recolor.payload = unsorted; + build(&b, &recolor, 1, NULL); + assert(!apply(&b, assets)); + uint8_t rgb_pair[4 + 8] = {1, 0, 0, 0, 0, 0, 0, 255, 0x18, 0x20, 0x29, 255}; + struct rec rgb = {RGB, RVT_KIND_RECOLOR, sizeof rgb_pair, rgb_pair}; + build(&b, &rgb, 1, NULL); + assert(!apply(&b, assets)); + rgb_pair[8] = 0xf8, rgb_pair[9] = 0, rgb_pair[10] = 0; + build(&b, &rgb, 1, NULL); + assert(apply(&b, assets) && catalog_data(RGB)[HEADER] == 0 && + catalog_data(RGB)[HEADER + 1] == 0xf8 && + catalog_data(RGB)[HEADER + 5] == 0xf8); + reset_bank(); + struct rec recolor_mask = {MASK, RVT_KIND_RECOLOR, sizeof swap, swap}; + build(&b, &recolor_mask, 1, NULL); + assert(!apply(&b, assets)); + uint8_t blue_to_red[4 + 8] = {1, 0, 0, 0, 35, 108, 197, 255, 200, 0, 0, 255}; + struct rec recolor_argb = {ARGB, RVT_KIND_RECOLOR, sizeof blue_to_red, blue_to_red}; + build(&b, &recolor_argb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(ARGB) + HEADER, (uint8_t[]){0, 0, 200, 255}, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 4, WHITE, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 12, (uint8_t[]){0, 0, 200, 255}, 4)); + reset_bank(); + static uint8_t many[4 + (RVT_RECOLOR_MAX + 1) * 8]; + put32(many, RVT_RECOLOR_MAX + 1); + for (uint32_t i = 0; i <= RVT_RECOLOR_MAX; i++) { + put32(many + 4 + i * 8, i); + put32(many + 8 + i * 8, i + 0x1000000u); + } + struct rec too_many = {ARGB, RVT_KIND_RECOLOR, sizeof many, many}; + build(&b, &too_many, 1, NULL); + assert(!apply(&b, assets)); + put32(many, RVT_RECOLOR_MAX); + struct rec miscounted = {ARGB, RVT_KIND_RECOLOR, sizeof many, many}; + build(&b, &miscounted, 1, NULL); + assert(!apply(&b, assets)); /* pairs != (size - 4) / 8 */ + uint8_t wrapped[4 + 16]; + memcpy(wrapped, swap, sizeof swap); + put32(wrapped, + 2 + (1u << 29)); /* a count whose times eight wraps to the payload size */ + struct rec wrapped_count = {SECOND, RVT_KIND_RECOLOR, sizeof wrapped, wrapped}; + build(&b, &wrapped_count, 1, NULL); + assert(!apply(&b, assets)); + struct rec max_pairs = {ARGB, RVT_KIND_RECOLOR, sizeof many - 8, many}; + build(&b, &max_pairs, 1, NULL); + assert(apply(&b, assets)); /* a shared map may name colours the bitmap lacks */ + reset_bank(); + + /* Invert keeps alpha, also on ARGB and RGB565; a mask cannot be inverted. */ + struct rec invert = {SECOND, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert, 1, NULL); + assert(apply(&b, assets) && + !memcmp(catalog_data(SECOND) + at_data(SECOND), WHITE, 4)); + reset_bank(); + struct rec invert_argb = {ARGB, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert_argb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(ARGB) + HEADER, (uint8_t[]){58, 147, 220, 255}, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 4, (uint8_t[]){0, 0, 0, 255}, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 28, (uint8_t[]){255, 255, 255, 0}, 4)); + reset_bank(); + uint8_t rgb_stock[6]; + memcpy(rgb_stock, stock_bank + AT_RGB + HEADER, 6); + memcpy(catalog_data(RGB) + HEADER, (uint8_t[]){0x00, 0xf8, 0xe0, 0x07, 0x1f, 0x00}, + 6); + memcpy(stock_bank + AT_RGB + HEADER, catalog_data(RGB) + HEADER, 6); + catalog_crcs[RGB] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(RGB), catalog_size(RGB)); + struct rec invert_rgb = {RGB, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert_rgb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(RGB) + HEADER, + (uint8_t[]){0xff, 0x07, 0x1f, 0xf8, 0xe0, 0xff}, 6)); + memcpy(stock_bank + AT_RGB + HEADER, rgb_stock, 6); + reset_bank(); + catalog_crcs[RGB] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(RGB), catalog_size(RGB)); + struct rec invert_mask = {MASK, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert_mask, 1, NULL); + assert(!apply(&b, assets)); + + /* Relight: the background rows take bg gray, the icon pixel icon gray, and + * the palette is rebuilt in ascending order; a rule the palette cannot + * hold, or with words outside their bounds, is refused. */ + int32_t rule[RVT_RELIGHT_WORDS] = { + 3 * 256, 14 * 256, 25 * 256, 216 * 256, 91, 24 * 256, + 24 * 256, 101018, -300, -453, 25 * 256, 25 * 256, + }; + struct rec relight = {PALETTED, RVT_KIND_RELIGHT, sizeof rule, + (const uint8_t *)rule}; + build(&b, &relight, 1, NULL); + assert(apply(&b, assets) && bit_test(assets, PALETTED)); + assert(catalog_data(PALETTED)[at_data(PALETTED)] == 24 && + catalog_data(PALETTED)[at_data(PALETTED) + 4] == 25); + assert(!memcmp(catalog_data(PALETTED) + HEADER + 12, + (uint8_t[]){0, 0, 1, 0, 0, 1, 1, 0}, 8)); + reset_bank(); + rule[RVT_RELIGHT_ICON_HI] = 26 * 256; + build(&b, &relight, 1, NULL); + assert(!apply(&b, assets)); + rule[RVT_RELIGHT_ICON_HI] = 25 * 256; + + static const struct { + unsigned word; + int32_t value; + } out_of_bounds[] = { + {RVT_RELIGHT_T_ZERO, -1}, {RVT_RELIGHT_T_FULL, 256 * 256}, + {RVT_RELIGHT_BG_BASE, 1025 * 256}, {RVT_RELIGHT_BG_REF, -256 * 256}, + {RVT_RELIGHT_BG_SLOPE, 17 * 256}, {RVT_RELIGHT_ICON_BASE, -1025 * 256}, + {RVT_RELIGHT_ICON_LUMA, 256 * 256}, {RVT_RELIGHT_ICON_ROW, -256 * 256}, + }; + + for (unsigned i = 0; i < sizeof out_of_bounds / sizeof *out_of_bounds; i++) { + int32_t kept = rule[out_of_bounds[i].word]; + rule[out_of_bounds[i].word] = out_of_bounds[i].value; + build(&b, &relight, 1, NULL); + assert(!apply(&b, assets)); + rule[out_of_bounds[i].word] = kept; + } + struct rec relight_rgb = {RGB, RVT_KIND_RELIGHT, sizeof rule, + (const uint8_t *)rule}; + build(&b, &relight_rgb, 1, NULL); + assert(!apply(&b, assets)); + expect_relight(WIDE, wide_plain_in, wide_plain_rule, wide_plain_out); + expect_relight(WIDE, wide_shadow_in, wide_shadow_rule, wide_shadow_out); + expect_relight(PALETTED, paletted_two_in, paletted_two_rule, paletted_two_out); + /* Shadow pruning: a partly covered pixel with no fully covered neighbour + * becomes background. Bitmap 5's third colour is black, far past k; the + * shade at (1, 0), offset 8 from the row's background, has no full + * neighbour and is dropped; the same shade at (3, 0) touches the black + * pixel at (3, 1) and stays a mid gray. */ + uint8_t *wide = catalog_data(WIDE) + at_data(WIDE), wide_stock[24]; + memcpy(wide_stock, wide, 24); + memcpy(wide, LIGHT, 4); + memcpy(wide + 4, (uint8_t[]){239, 236, 232, 255}, 4); + memcpy(wide + 8, BLACK, 4); + memcpy(wide + 12, LIGHT, 4); + memcpy(wide + 16, (uint8_t[]){0, 1, 0, 1, 0, 0, 0, 2}, 8); + memcpy(stock_bank + AT_WIDE + at_data(WIDE), wide, 24); + catalog_crcs[WIDE] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(WIDE), catalog_size(WIDE)); + int32_t wide_rule[RVT_RELIGHT_WORDS] = { + 3 * 256, 14 * 256, 25 * 256, 216 * 256, 91, 24 * 256, + 24 * 256, 27 * 256, 0, 0, 27 * 256, 27 * 256, + }; + struct rec relight_wide = {WIDE, RVT_KIND_RELIGHT, sizeof wide_rule, + (const uint8_t *)wide_rule}; + build(&b, &relight_wide, 1, NULL); + assert(apply(&b, assets)); + { + const uint8_t *rows = catalog_data(WIDE) + at_data(WIDE) + 16; + const uint8_t *palette = catalog_data(WIDE) + at_data(WIDE); + assert(palette[rows[1] * 4] == 24); /* pruned to the background gray */ + assert(palette[rows[7] * 4] == 27); /* the black pixel, fully covered */ + assert(palette[rows[3] * 4] == 25); /* kept and blended */ + assert(!memcmp( + palette, + (uint8_t[]){24, 24, 24, 255, 25, 25, 25, 255, 27, 27, 27, 255, 0, 0, 0, 0}, + 16)); + } + memcpy(stock_bank + AT_WIDE + at_data(WIDE), wide_stock, 24); + reset_bank(); + catalog_crcs[WIDE] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(WIDE), catalog_size(WIDE)); + + /* Alias: applied after the other records, so a source with a higher index + * is final; a chain, a self alias, a different size and a tinted source + * are refused; a source of another layout is re-encoded when the palette + * has room. */ + uint32_t three = SECOND; + struct rec alias_up[2] = {{PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&three}, + invert}; + build(&b, alias_up, 2, NULL); + assert(apply(&b, assets) && !memcmp(catalog_data(PALETTED) + at_data(PALETTED), + catalog_data(SECOND) + at_data(SECOND), + PALETTED_BYTES - HEADER - 4)); + assert(!memcmp(catalog_data(PALETTED) + at_data(PALETTED), WHITE, 4)); + reset_bank(); + uint32_t one = PALETTED; + struct rec chain[2] = {{PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&three}, + {SECOND, RVT_KIND_ALIAS, 4, (const uint8_t *)&one}}; + build(&b, chain, 2, NULL); + assert(!apply(&b, assets)); + struct rec self_alias = {PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&one}; + build(&b, &self_alias, 1, NULL); + assert(!apply(&b, assets)); + uint32_t two_ = RGB; + struct rec wrong_size = {PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&two_}; + build(&b, &wrong_size, 1, NULL); + assert(!apply(&b, assets)); + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, alias_up, 1, tint); + assert(!apply(&b, assets)); + tint[SECOND] = 0; + uint32_t four = ARGB, five = WIDE; + struct rec argb_into_wide = {WIDE, RVT_KIND_ALIAS, 4, (const uint8_t *)&four}; + build(&b, &argb_into_wide, 1, NULL); + assert(apply(&b, assets)); /* blue, white and clear white: three of four entries */ + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), BLUE, 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 4, WHITE, 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 8, (uint8_t[]){255, 255, 255, 0}, + 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 12, (uint8_t[]){0, 0, 0, 0}, 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 16, + (uint8_t[]){0, 1, 1, 0, 1, 1, 0, 2}, 8)); + reset_bank(); + struct rec wide_into_argb = {ARGB, RVT_KIND_ALIAS, 4, (const uint8_t *)&five}; + build(&b, &wide_into_argb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(ARGB) + HEADER, BLUE, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 4, GREY, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 28, BLUE, 4)); + reset_bank(); + struct rec wide_into_paletted = {PALETTED, RVT_KIND_ALIAS, 4, + (const uint8_t *)&five}; + build(&b, &wide_into_paletted, 1, NULL); + assert(!apply(&b, assets)); /* four colours into two entries */ + assert(catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + + /* A derived record on a bitmap the active look changed fetches stock first; + * one the look left alone is derived in place. */ + uint32_t current[BITMAP_WORDS] = {0}; + bit_set(current, SECOND); + memset(catalog_data(SECOND) + at_data(SECOND), 0x55, 8); + opens = 0; + build(&b, &invert, 1, NULL); + assert(apply_from(&b, assets, current) && opens == 1); + assert(!memcmp(catalog_data(SECOND) + at_data(SECOND), WHITE, 4)); + reset_bank(); + memset(current, 0, sizeof current); + + /* A tint on a derived record is refused. */ + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, &invert, 1, tint); + assert(!apply(&b, assets)); + tint[SECOND] = 0; + + /* Compressed pixels decode straight into the bitmap: a literal group, + * then a match; a long match extends its length; the stream must end + * where the bitmap is full and must not end before. */ + static const uint8_t lz_paletted[14] = {0x00, 9, 9, 9, 255, 8, 8, + 8, 255, 0x04, 0, 1, 0x30, 0x01}; + struct rec lz = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_paletted, lz_paletted}; + build(&b, &lz, 1, NULL); + assert(apply(&b, assets) && bit_test(assets, PALETTED)); + assert(!memcmp(catalog_data(PALETTED) + at_data(PALETTED), + (uint8_t[]){9, 9, 9, 255, 8, 8, 8, 255, 0, 1, 0, 1, 0, 1, 0, 1}, + 16)); + reset_bank(); + static const uint8_t lz_zeros[5] = {0x02, 0, 0xf0, 0x00, 0x0d}; + struct rec lz_argb = {ARGB, RVT_KIND_PIXELS_LZ, sizeof lz_zeros, lz_zeros}; + build(&b, &lz_argb, 1, NULL); + assert(apply(&b, assets)); + for (unsigned i = 0; i < 32; i++) + assert(catalog_data(ARGB)[HEADER + i] == 0); + reset_bank(); + struct rec lz_short = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_paletted - 1, + lz_paletted}; + build(&b, &lz_short, 1, NULL); + assert(!apply(&b, assets) && catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + static uint8_t lz_long[15]; + memcpy(lz_long, lz_paletted, 14); + struct rec lz_trailing = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_long, lz_long}; + build(&b, &lz_trailing, 1, NULL); + assert(!apply(&b, assets) && catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + static const uint8_t lz_backwards[3] = {0x01, 0x00, 0x05}; + struct rec lz_before = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_backwards, + lz_backwards}; + build(&b, &lz_before, 1, NULL); + assert(!apply(&b, assets)); + static const uint8_t lz_overrun[4] = {0x02, 0, 0xf0, + 0x00}; /* 18 more bytes than the 16 */ + struct rec lz_over = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_overrun, lz_overrun}; + build(&b, &lz_over, 1, NULL); + assert(!apply(&b, assets)); + struct rec lz_empty = {PALETTED, RVT_KIND_PIXELS_LZ, 0, lz_paletted}; + build(&b, &lz_empty, 1, NULL); + assert(!apply(&b, assets)); + reset_bank(); + /* A paletted record's indices are checked after decoding. */ + static const uint8_t lz_bad_index[14] = {0x00, 9, 9, 9, 255, 8, 8, + 8, 255, 0x04, 0, 2, 0x30, 0x01}; + struct rec lz_bad = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_bad_index, + lz_bad_index}; + build(&b, &lz_bad, 1, NULL); + assert(!apply(&b, assets) && catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + + /* A truncated file fails on the record it cuts; what it wrote before + * stays marked for the switch to restore. */ + build(&b, two, 2, NULL); + b.size -= 8; + assert(!apply(&b, assets) && bit_test(assets, MASK) && bit_test(assets, PALETTED)); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + assert(catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + + /* The CRC-32 vector. */ + assert(crc("123456789", 9) == 0xcbf43926u); +} + +/* The switch module over the host firmware file: what a switch leaves in the + * bank, in the state and in the style, and how it comes back from damage. */ +static void switch_contracts(void) +{ + struct built b; + struct look theme = { + .id = "test", .name = "Test", .appearances = RVT_APPEARANCE_DARK, .dark = 1}; + struct look stock = {0}; + uint8_t mask[4 * 2] = {1, 2, 3, 4, 5, 6, 7, 8}; + uint8_t paletted[2 * 4 + 4 * 2] = {9, 9, 9, 255, 8, 8, 8, 255, + 0, 1, 0, 1, 1, 0, 1, 0}; + struct rec two[2] = {pixels(MASK, mask), pixels(PALETTED, paletted)}; + memset(&look_state, 0, sizeof look_state); + style_reset(); + style_set_dark(0); + style_set_accent(ACCENT_DEFAULT); + + /* A theme goes on and comes off; the firmware file is checked once. */ + build(&b, two, 2, NULL); + opens = closes = 0; + assert(switch_to(&b, &theme) == SWITCH_OK); + assert(opens == 2 && closes == 2 && + look_state.stock_checked); /* the check, then the switch */ + assert(!strcmp(look_state.active.id, "test") && look_state.active.dark && + style_from_theme() && style_dark()); + assert(bit_test(look_state.assets, MASK) && bit_test(look_state.assets, PALETTED)); + /* Under a theme the stock accent art follows the theme's accent fill. */ + assert(bit_test(look_state.assets, WIDE) && bit_test(look_state.accented, WIDE)); + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), (uint8_t[]){197, 108, 35, 255}, 4)); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && opens == 3); + assert(bank_is_stock() && !look_state.active.id[0] && !style_from_theme() && + !style_dark()); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + assert(!look_state.assets[i] && !look_state.accented[i]); + + /* Without the firmware file nothing changes. */ + firmware_missing = 1; + look_state.stock_checked = 0; + assert(switch_to(&b, &theme) == SWITCH_LOAD_FAILED && bank_is_stock() && + !look_state.stock_checked); + firmware_missing = 0; + assert(switch_to(&b, &theme) == SWITCH_OK); + + /* A pack that fails part way: the stock light look comes back and every + * touched bitmap is restored. */ + paletted[8] = 2; + memcpy(mask, (uint8_t[]){8, 7, 6, 5, 4, 3, 2, 1}, 8); + two[0] = pixels(MASK, mask); + build(&b, two, 2, NULL); + assert(switch_to(&b, &theme) == SWITCH_RECOVERED); + assert(bank_is_stock() && !look_state.active.id[0] && !style_from_theme() && + !style_dark() && style_accent() == ACCENT_DEFAULT && !firmware_open_now); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + assert(!look_state.assets[i]); + paletted[8] = 0; + + /* When the firmware file cannot restore a bitmap, theming is off: the + * attempt's bitmaps stay marked and the file is checked again next time. */ + build(&b, two, 2, NULL); + assert(switch_to(&b, &theme) == SWITCH_OK); + corrupt_asset = MASK; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_RESTORE_FAILED); + assert(bit_test(look_state.assets, MASK) && bit_test(look_state.assets, PALETTED) && + !look_state.stock_checked && !look_state.active.id[0] && + !style_from_theme()); + assert(catalog_data(MASK)[HEADER] == 0); /* zeroed by the failed fetch */ + corrupt_asset = -1; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock() && + look_state.stock_checked); + + /* Theme to theme: the second pack applies, then a bitmap only the first + * touched cannot be restored; the recovery cannot restore it either, so + * theming is off with both packs' bitmaps marked. */ + struct built second; + build(&b, two, 2, NULL); + assert(switch_to(&b, &theme) == SWITCH_OK); + build(&second, two + 1, 1, NULL); + corrupt_asset = MASK; + assert(switch_to(&second, &theme) == SWITCH_RESTORE_FAILED); + assert(bit_test(look_state.assets, MASK) && bit_test(look_state.assets, PALETTED) && + !look_state.stock_checked && !look_state.active.id[0] && + !style_from_theme()); + corrupt_asset = -1; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock() && + look_state.stock_checked); + + /* Classic dark: a pack with colours only; one with a tint or a flag is refused. */ + struct look dark = {.dark = 1}; + build(&b, two, 2, NULL); + assert(switch_to(&b, &dark) == SWITCH_OK && !style_from_theme() && style_dark()); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + uint8_t tint[RVT_CATALOG_MAX] = {0}; + tint[MASK] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, NULL, 0, tint); + assert(switch_to(&b, &dark) == SWITCH_LOAD_FAILED); + build(&b, NULL, 0, NULL); + put32(b.bytes + RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + RVT_STYLE_FLAGS, + RVT_FLAG_FLAT_SELECTION); + resign_dark_pack(&b); + assert(switch_to(&b, &dark) == SWITCH_LOAD_FAILED); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, + sizeof mask)); /* the dark look stays */ + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock()); + + /* An accent on Classic recolours the stock accent art from stock pixels + * and restores it exactly; Blue and Theme Default leave it alone. */ + struct look pink = {.accent = ACCENT_FIRST + 6}; + assert(!strcmp(accent_labels[pink.accent], "Pink")); + assert(switch_apply(NULL, &pink, NULL) == SWITCH_OK && + bit_test(look_state.assets, WIDE) && bit_test(look_state.accented, WIDE)); + const uint8_t *fill = style_color(RVT_ROLE_ACCENT_FILL); + assert(fill[0] == 196 && fill[1] == 30 && fill[2] == 86); + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), (uint8_t[]){86, 30, 196, 255}, 4)); + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 4, GREY, 4)); /* grey stays grey */ + assert(switch_accent(ACCENT_FIRST + 2) == SWITCH_OK); /* Green, from stock again */ + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), (uint8_t[]){58, 128, 30, 255}, 4)); + assert(switch_accent(ACCENT_FIRST) == SWITCH_OK && bank_is_stock() && + !bit_test(look_state.assets, WIDE)); + assert(switch_accent(ACCENT_DEFAULT) == SWITCH_OK && bank_is_stock()); + /* A failed restore during an accent change recovers like a switch. */ + assert(switch_accent(pink.accent) == SWITCH_OK); + corrupt_asset = WIDE; + assert(switch_accent(ACCENT_FIRST + 2) == SWITCH_RESTORE_FAILED && + !look_state.stock_checked && style_accent() == ACCENT_DEFAULT && + bit_test(look_state.assets, WIDE)); + corrupt_asset = -1; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock()); + + /* A pack that replaces the accent art keeps its own art under any accent. */ + uint8_t wide_art[4 * 4 + 8] = {1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255, + 4, 4, 4, 255, 0, 1, 2, 3, 0, 1, 2, 3}; + struct rec own = pixels(WIDE, wide_art); + build(&b, &own, 1, NULL); + theme.accent = pink.accent; + assert(switch_to(&b, &theme) == SWITCH_OK && !bit_test(look_state.accented, WIDE)); + assert(!memcmp(catalog_data(WIDE) + at_data(WIDE), wide_art, sizeof wide_art)); + assert(switch_accent(ACCENT_FIRST + 2) == SWITCH_OK && + !memcmp(catalog_data(WIDE) + at_data(WIDE), wide_art, sizeof wide_art)); + theme.accent = 0; + + /* Unload puts everything back. */ + switch_restore_all(); + assert(bank_is_stock() && !look_state.active.id[0] && !style_from_theme()); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + assert(!look_state.assets[i]); + assert(!firmware_open_now && !allocations); +} + +/* A theme's bitmaps for extensions: the table after a pack's records goes + * into the index, checked entry by entry; the provider serves the core from + * the index and the theme file; the index goes when the look does. */ +#define OWNER_A 0x1000u +#define OWNER_B 0x2000u +/* A Settings icon: 78 by 121 Mask8, stride 80. */ +#define MENU_STRIDE 80 +#define MENU_ROWS (MENU_STRIDE * 121) +#define MENU_BMAP_BYTES (HEADER + MENU_ROWS) +#define LZ_BOUND(n) ((n) + ((n) + 7) / 8) +static uint8_t menu_a[MENU_BMAP_BYTES], menu_b[MENU_BMAP_BYTES]; +/* menu_lz: the header and a 0xab as 29 literals (four flag bytes), then one + * match of 9,679 bytes from one byte back: 15 + 3, extended by 37 bytes of + * 255 and one of 226. */ +static uint8_t menu_lz[4 + HEADER + 1 + 2 + 38]; +/* A canvas bitmap: 4 by 2 Indexed8 with two colours, raw and as literals. */ +static uint8_t small[PALETTED_BYTES], small_lz[LZ_BOUND(PALETTED_BYTES)]; + +/* `n` bytes as an lz stream of literals: a flag byte per eight. */ +static uint32_t lz_literals(uint8_t *out, const uint8_t *in, uint32_t n) +{ + uint32_t written = 0; + for (uint32_t i = 0; i < n; i++) { + if (i % 8 == 0) + out[written++] = 0; + out[written++] = in[i]; + } + return written; +} + +static void asset_payloads(void) +{ + bmap(menu_a, BMapFormat_Mask8, MENU_STRIDE, 8, 78, 121, sizeof menu_a); + bmap(menu_b, BMapFormat_Mask8, MENU_STRIDE, 8, 78, 121, sizeof menu_b); + for (uint32_t i = HEADER; i < sizeof menu_a; i++) { + menu_a[i] = (uint8_t)(i * 7); + menu_b[i] = (uint8_t)(i * 3 + 1); + } + uint8_t *lz = menu_lz; + for (uint32_t group = 0; group < 3; group++) { + *lz++ = 0; + memcpy(lz, menu_a + 8 * group, 8); + lz += 8; + } + *lz++ = 0x20; /* four header literals, the 0xab, then the match */ + memcpy(lz, menu_a + 24, 4); + lz += 4; + *lz++ = 0xab; + *lz++ = 0xf0; + *lz++ = 0x00; + memset(lz, 255, 37); + lz[37] = 226; + assert(lz + 38 == menu_lz + sizeof menu_lz); + bmap(small, BMapFormat_Indexed8, 4, 8, 4, 2, sizeof small); + put32(small + HEADER, 2); + memcpy(small + HEADER + 4, LIGHT, 4); + memcpy(small + HEADER + 8, ICON, 4); + for (uint32_t i = 0; i < 8; i++) + small[HEADER + 12 + i] = (uint8_t)(i & 1); + assert(lz_literals(small_lz, small, sizeof small) == sizeof small_lz); +} + +static void with_assets(const struct asset_payload *table, uint32_t count, + struct built *b) +{ + asset_table = table; + asset_table_count = count; + build(b, NULL, 0, NULL); + asset_table = NULL; + asset_table_count = 0; +} + +static void prefix_custom(uint8_t *p, const uint8_t roles[RVT_ROLES][3], uint32_t flags, + unsigned palette, const uint8_t accent[RVT_ACCENT_SLOTS][3]); + +/* 1 when the probe answers the asset with exactly this stream. */ +static int probe(uint32_t owner, uint32_t asset, uint8_t codec, uint32_t stored, + uint32_t bytes) +{ + struct rv_asset_stream stream = {0xff, 0, 0}; + return replacement(owner, asset, &stream) && stream.codec == codec && + stream.stored == stored && stream.bytes == bytes; +} + +/* The core's read of a probed stream: 1 when the provider copied `stored` + * bytes of the asset into `block`; the block is the caller's. */ +static int read_stored(uint32_t owner, uint32_t asset, uint8_t *block, uint32_t stored) +{ + memset(block, 0x5a, stored); + return replacement_read(owner, asset, block, stored); +} + +static void assets_contracts(void) +{ + static uint8_t block[MENU_BMAP_BYTES], zeros[MENU_BMAP_BYTES]; + uint32_t assets[BITMAP_WORDS]; + struct built b; + asset_payloads(); + const struct asset_payload four[4] = { + {OWNER_A, 5, RVT_EXTENSION_BITMAP, sizeof menu_a, MENU_BMAP_BYTES, menu_a, 0}, + {OWNER_A, 9, RVT_EXTENSION_BITMAP_LZ, sizeof menu_lz, MENU_BMAP_BYTES, menu_lz, + 0}, + {OWNER_B, 1, RVT_EXTENSION_BITMAP, sizeof small, PALETTED_BYTES, small, 0}, + {OWNER_B, 2, RVT_EXTENSION_BITMAP_LZ, sizeof small_lz, PALETTED_BYTES, small_lz, + 0}, + }; + + /* A good table: one entry per asset, in order, each payload's offset in + * the file, the stored bytes, the decoded bytes and the kind. */ + with_assets(four, 4, &b); + assert(apply(&b, assets) && live_count == 4 && allocations == 1); + for (unsigned i = 0; i < 4; i++) { + assert(live[i].owner == four[i].owner && live[i].asset == four[i].asset); + assert(live[i].kind == four[i].kind && live[i].bytes == four[i].size); + assert(live[i].decoded == four[i].decoded); + assert(!memcmp(b.bytes + live[i].offset, four[i].payload, four[i].size)); + } + assert(live[0].offset == RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + + RVT_STYLE_BYTES + RVT_EXTENSION_BITMAP_BYTES); + + /* Refused, the index that was on staying: out of order or repeated keys; + * a kind that is not a bitmap; a decoded size that is no more than a + * header or over the cap; a raw payload of another size than decoded; an + * empty lz stream or one over the literal bound; padding that is not + * zero; a count the body does not hold, one that leaves a table unread, + * and a table past the limit. The bitmap itself is the core's to check + * once decoded. */ + struct asset_payload bad[4]; + memcpy(bad, four, sizeof bad); + bad[0] = four[1], bad[1] = four[0]; + with_assets(bad, 4, &b); + assert(!apply(&b, assets) && live_count == 4); + memcpy(bad, four, sizeof bad); + bad[1].asset = 5; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[2].owner = OWNER_A, bad[2].asset = 2; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[0].kind = RVT_EXTENSION_KINDS; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[0].kind = 0; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[2].size = bad[2].decoded = HEADER; /* a header without rows */ + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[2].size = sizeof small - 1; /* a raw payload of another size */ + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[2].size = sizeof small, bad[2].decoded = PALETTED_BYTES + 4; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[1].decoded = RVT_EXTENSION_BITMAP_MAX_BYTES + 1; /* over the cap */ + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[1].decoded = RVT_EXTENSION_BITMAP_MAX_BYTES; /* at it: the core decides */ + with_assets(bad, 4, &b); + assert(apply(&b, assets) && live_count == 4); + /* A tint word names a role without coverage bits; the index keeps it. */ + memcpy(bad, four, sizeof bad); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT; + with_assets(bad, 4, &b); + assert(apply(&b, assets) && live[2].tint == RVT_TINT_ROLE + RVT_ROLE_TEXT && + !live[3].tint); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLES; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT | RVT_TINT_DARKNESS; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT | RVT_TINT_SOLID; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[1].size = 0; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + static uint8_t overlong[LZ_BOUND(MENU_BMAP_BYTES) + 1]; + bad[1].size = sizeof overlong, bad[1].payload = overlong; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[1].size = sizeof overlong - 1; + with_assets(bad, 4, &b); + assert(apply(&b, assets) && live_count == 4); /* parsed; the core decides */ + memcpy(bad, four, sizeof bad); + static uint8_t small_overlong[sizeof small_lz + 1]; + memcpy(small_overlong, small_lz, sizeof small_lz); + bad[3].size = sizeof small_overlong, bad[3].payload = small_overlong; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + with_assets(four, 4, &b); + b.bytes[b.size - 1] ^= 1; + assert(!apply(&b, assets)); /* the checksum covers the table */ + with_assets(four, 4, &b); + b.bytes[live[1].offset + sizeof menu_lz] = 1; /* padding after the lz stream */ + resign_dark_pack(&b); + assert(!apply(&b, assets)); + with_assets(four, 4, &b); + put32(b.bytes + RVT_HEADER_BYTES + RVT_PACK_EXTENSION_BITMAPS, 5); + assert(!apply(&b, assets)); + put32(b.bytes + RVT_HEADER_BYTES + RVT_PACK_EXTENSION_BITMAPS, 3); + assert(!apply(&b, assets)); + static struct asset_payload many[RVT_EXTENSION_BITMAPS_MAX + 1]; + for (uint32_t i = 0; i < RVT_EXTENSION_BITMAPS_MAX + 1; i++) + many[i] = (struct asset_payload){ + OWNER_A, i, RVT_EXTENSION_BITMAP_LZ, sizeof menu_lz, MENU_BMAP_BYTES, + menu_lz, 0}; + with_assets(many, RVT_EXTENSION_BITMAPS_MAX + 1, &b); + assert(!apply(&b, assets)); + with_assets(many, RVT_EXTENSION_BITMAPS_MAX, &b); + assert(apply(&b, assets) && live_count == RVT_EXTENSION_BITMAPS_MAX); + /* A pack without a table leaves no index. */ + build(&b, NULL, 0, NULL); + assert(apply(&b, assets) && !live_count && !allocations); + + /* The probe answers how a listed asset is stored, nothing for any other; + * the read copies exactly the stored bytes and nothing for another size. */ + with_assets(four, 4, &b); + assert(apply(&b, assets)); + provided = &b; + memcpy(look_state.active.id, PROVIDED_ID, sizeof PROVIDED_ID); + assert(probe(OWNER_A, 5, RV_ASSET_RAW, sizeof menu_a, MENU_BMAP_BYTES)); + assert(probe(OWNER_A, 9, RV_ASSET_LZ, sizeof menu_lz, MENU_BMAP_BYTES)); + assert(probe(OWNER_B, 1, RV_ASSET_RAW, sizeof small, PALETTED_BYTES)); + assert(probe(OWNER_B, 2, RV_ASSET_LZ, sizeof small_lz, PALETTED_BYTES)); + struct rv_asset_stream none; + assert(!replacement(OWNER_A, 7, &none) && !replacement(OWNER_A, 4, &none)); + assert(!replacement(OWNER_B, 3, &none) && !replacement(0, 5, &none)); + assert(read_stored(OWNER_A, 5, block, sizeof menu_a) && + !memcmp(block, menu_a, sizeof menu_a)); + assert(read_stored(OWNER_A, 9, block, sizeof menu_lz) && + !memcmp(block, menu_lz, sizeof menu_lz)); + assert(read_stored(OWNER_B, 1, block, sizeof small) && + !memcmp(block, small, sizeof small)); + assert(read_stored(OWNER_B, 2, block, sizeof small_lz) && + !memcmp(block, small_lz, sizeof small_lz)); + assert(!read_stored(OWNER_A, 7, block, MENU_BMAP_BYTES)); + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a - 1)); + assert(!read_stored(OWNER_B, 1, block, sizeof menu_a)); + assert(!open_files && allocations == 1); + /* A file that no longer holds the bytes: cut inside a raw payload or an + * lz stream. The read says 0 and holds nothing. */ + b.size = live[0].offset + 100; + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a)); + b.size = live[1].offset + 10; + assert(!read_stored(OWNER_A, 9, block, sizeof menu_lz)); + assert(!open_files && allocations == 1); + with_assets(four, 4, &b); + assert(apply(&b, assets)); + /* A theme file that is gone. */ + provided = NULL; + unreadable = PROVIDED_ID; + assert(probe(OWNER_A, 5, RV_ASSET_RAW, sizeof menu_a, MENU_BMAP_BYTES)); + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a) && !open_files); + unreadable = NULL; + provided = &b; + /* Classic dark serves its bitmaps from the classic asset; Classic light + * has no file. */ + memset(look_state.active.id, 0, sizeof look_state.active.id); + look_state.active.dark = 1; + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a) && + !open_files); /* the asset here holds none */ + look_state.active.dark = 0; + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a) && !open_files); + memcpy(look_state.active.id, PROVIDED_ID, sizeof PROVIDED_ID); + + /* The extension's own bitmap is left alone, until a flat-icon look: then + * a Settings icon loses the rows under its art, and nothing else changes. */ + memcpy(block, menu_a, sizeof block); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES) && + !memcmp(block, menu_a, sizeof block)); + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t roles[RVT_ROLES][3] = {{0}}; + prefix_custom(prefix, roles, RVT_FLAG_FLAT_ICONS, 0, NULL); + style_set(prefix); + assert(adjust(OWNER_A, 7, block, MENU_BMAP_BYTES)); + assert(!memcmp(block, menu_a, HEADER + 79 * MENU_STRIDE) && + !memcmp(block + HEADER + 79 * MENU_STRIDE, zeros, (121 - 79) * MENU_STRIDE)); + memcpy(block, small, sizeof small); + assert(!adjust(OWNER_B, 1, block, PALETTED_BYTES) && + !memcmp(block, small, sizeof small)); + memcpy(block, menu_a, sizeof block); + put16(block, BMapFormat_Indexed8); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES)); + put16(block, BMapFormat_Mask8); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES - 1)); + put32(block + 20, 80); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES)); + assert(!memcmp(block + HEADER, menu_a + HEADER, MENU_ROWS)); + style_reset(); + + /* A tinted replacement: the decoded picture's palette entries take the + * role's colour and keep their alpha; a Settings icon under a tint word + * is left to the core, which draws it in the icon tint anyway. */ + struct asset_payload tinted[4]; + memcpy(tinted, four, sizeof tinted); + tinted[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT; + tinted[0].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT; + with_assets(tinted, 4, &b); + assert(apply(&b, assets)); + static const uint8_t text_role[RVT_ROLES][3] = { + [RVT_ROLE_TEXT] = {0x12, 0x34, 0x56}}; + prefix_custom(prefix, text_role, 0, 0, NULL); + style_set(prefix); + memcpy(block, small, sizeof small); + assert(adjust(OWNER_B, 1, block, PALETTED_BYTES)); + static const uint8_t painted_light[4] = {0x56, 0x34, 0x12, 255}; + assert(!memcmp(block + HEADER + 4, painted_light, 4) && + block[HEADER + 11] == ICON[3] && + !memcmp(block + HEADER + 8, "\x56\x34\x12", 3) && + !memcmp(block + HEADER + 12, small + HEADER + 12, 8)); + memcpy(block, small, sizeof small); + assert(!adjust(OWNER_B, 2, block, PALETTED_BYTES) && + !memcmp(block, small, sizeof small)); + memcpy(block, menu_a, sizeof block); + assert(!adjust(OWNER_A, 5, block, MENU_BMAP_BYTES) && + !memcmp(block, menu_a, sizeof block)); + /* BGRA rows: covered pixels are painted, clear ones stay. */ + static uint8_t argb[HEADER + 16 * 2]; + bmap(argb, BMapFormat_BGRA8888, 16, 32, 4, 2, sizeof argb); + for (uint32_t i = 0; i < 8; i++) + memcpy(argb + HEADER + i * 4, i & 1 ? "\x01\x02\x03\x80" : "\x09\x09\x09\x00", + 4); + assert(tint_bmap(argb, sizeof argb, style_color(RVT_ROLE_TEXT))); + for (uint32_t i = 0; i < 8; i++) + assert(!memcmp(argb + HEADER + i * 4, + i & 1 ? "\x56\x34\x12\x80" : "\x09\x09\x09\x00", 4)); + put16(argb, BMapFormat_RGB565); + assert(!tint_bmap(argb, sizeof argb, style_color(RVT_ROLE_TEXT))); + style_reset(); + with_assets(four, 4, &b); + assert(apply(&b, assets)); + + /* The end of disk mode checks the theme file's header: the same file + * keeps the index, another under the id or none ends it. */ + look_state.active.header_crc = le32(b.bytes + RVT_HEADER_CRC); + look_volume_changed(); + assert(probe(OWNER_A, 5, RV_ASSET_RAW, sizeof menu_a, MENU_BMAP_BYTES) && + live_count == 4); + struct built swapped; + asset_table = four, asset_table_count = 4; + build_file_at(&swapped, PROVIDED_ID, "Other", RVT_HEADER_BYTES, NULL, 0, NULL, 0, + NULL, NULL); + asset_table = NULL, asset_table_count = 0; + provided = &swapped; + look_volume_changed(); + assert(!replacement(OWNER_A, 5, &none)); + assert(!live_count && !allocations && !open_files); + assert(apply(&b, assets) && live_count == 4); + unreadable = PROVIDED_ID; + look_volume_changed(); + assert(!live_count && !allocations && !open_files); + unreadable = NULL; + provided = &b; + + /* The switch: a look with bitmaps holds the index; the stock look, a + * recovered switch and unload free it; a switch that fails before it + * changes anything keeps the index of the look that stays. */ + struct look theme = { + .id = "test", .name = "Test", .appearances = RVT_APPEARANCE_DARK, .dark = 1}; + struct look stock = {0}; + with_assets(four, 4, &b); + assert(switch_to(&b, &theme) == SWITCH_OK && live_count == 4 && allocations == 1); + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && !live_count && + !allocations); + assert(switch_to(&b, &theme) == SWITCH_OK && live_count == 4); + struct built failing; + memcpy(bad, four, sizeof bad); + bad[0].kind = RVT_EXTENSION_KINDS; /* no records: a bad table alone */ + with_assets(bad, 4, &failing); + assert(switch_to(&failing, &theme) == SWITCH_LOAD_FAILED && live_count == 4 && + allocations == 1); + uint8_t paletted[2 * 4 + 4 * 2] = {9, 9, 9, 255, 8, 8, 8, 255, + 0, 1, 0, 2, 1, 0, 1, 0}; + struct rec broken = pixels(PALETTED, paletted); + asset_table = four, asset_table_count = 4; + build(&failing, &broken, 1, NULL); + asset_table = NULL, asset_table_count = 0; + assert(switch_to(&failing, &theme) == SWITCH_RECOVERED && !live_count && + !allocations); + assert(switch_to(&b, &theme) == SWITCH_OK && live_count == 4); + switch_restore_all(); + assert(!live_count && !allocations && bank_is_stock()); + provided = NULL; + memset(&look_state.active, 0, sizeof look_state.active); +} + +static void scan_contracts(void) +{ + static const char *const names[] = {"zeta.rvt", "ALPHA.RVT", "Mid.Rvt", + "notes.txt", "BAD~1.RVT", "classic.rvt", + "alpha.rvt", "broken.rvt", "-dash.rvt"}; + struct theme_entry entries[64]; + int overflow = 1; + folder = names; + folder_count = sizeof names / sizeof *names; + unreadable = "broken"; + /* Counted: zeta, ALPHA, Mid, alpha, broken; listed in order without the + * duplicate and the file that does not open. */ + assert(theme_count() == 5); + uint32_t n = theme_scan(entries, 64, &overflow); + assert(n == 3 && !overflow); + assert(!strcmp(entries[0].id, "alpha") && !strcmp(entries[1].id, "mid") && + !strcmp(entries[2].id, "zeta")); + assert(!strcmp(entries[0].name, "Named")); + + /* More files than the list holds: the first in order are kept and the + * overflow reported; a smaller capacity caps the same way. */ + static char many_names[70][16]; + static const char *many[70]; + for (unsigned i = 0; i < 70; i++) { + snprintf(many_names[i], sizeof many_names[i], "t%02u.rvt", 69 - i); + many[i] = many_names[i]; + } + folder = many; + folder_count = 70; + unreadable = NULL; + assert(theme_count() == 70); + n = theme_scan(entries, 64, &overflow); + assert(n == 64 && overflow && !strcmp(entries[0].id, "t00") && + !strcmp(entries[63].id, "t63")); + n = theme_scan(entries, 3, &overflow); + assert(n == 3 && overflow && !strcmp(entries[2].id, "t02")); + + /* Opening a theme: by id, in the appearance asked for or the one it has; + * the reserved id and a missing file are unavailable. */ + struct rv_file *file; + struct look look; + struct pack_place place; + char id[RVT_ID_BYTES] = "t05"; + assert(theme_open(id, 1, &file, &look, &place) == THEME_OK && look.dark && file); + file_close(NULL, file); + assert(theme_open(id, 0, &file, &look, &place) == THEME_NOT_IN_APPEARANCE && + look.dark && file); + assert(!strcmp(look.id, "t05") && look.appearances == RVT_APPEARANCE_DARK); + assert(place.offset == RVT_HEADER_BYTES && + place.bytes == opened_theme.size - RVT_HEADER_BYTES); + file_close(NULL, file); + strcpy(id, "classic"); + assert(theme_open(id, 1, &file, &look, &place) == THEME_UNAVAILABLE && !file); + strcpy(id, "broken"); + unreadable = "broken"; + assert(theme_open(id, 1, &file, &look, &place) == THEME_UNAVAILABLE && !file); + assert(!open_files); +} + +/* A style prefix with the given role colours (RGB), flags and one accent palette. */ +static void prefix_custom(uint8_t *p, const uint8_t roles[RVT_ROLES][3], uint32_t flags, + unsigned palette, const uint8_t accent[RVT_ACCENT_SLOTS][3]) +{ + prefix_plain(p); + for (unsigned i = 0; i < RVT_ROLES; i++) + memcpy(p + RVT_STYLE_COLORS + i * 4, roles[i], 3); + put32(p + RVT_STYLE_FLAGS, flags); + if (accent) + for (unsigned i = 0; i < RVT_ACCENT_SLOTS; i++) + memcpy(p + RVT_STYLE_PALETTES + (palette * RVT_ACCENT_SLOTS + i) * 4, + accent[i], 3); +} + +static void expect_text(const uint8_t *color, uint32_t view, uint8_t r, uint8_t g, + uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_text(color, view, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static void expect_fill(const uint8_t *color, uint8_t r, uint8_t g, uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_fill(color, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static void expect_background(uint32_t r, uint32_t g, uint32_t b, uint32_t rgb565) +{ + assert(clear_color(0x10000, 0x10000, 0x10000, 0x4321, NULL) == 0x600d); + assert(passed[0] == r && passed[1] == g && passed[2] == b && passed[3] == 0x4321); + assert(reflection_blend(0xabcd, 0xffff, 0x8000, NULL) == 0x600d); + assert(passed[0] == 0xabcd && passed[1] == rgb565 && passed[2] == 0x8000); +} + +static void expect_bar(const uint8_t *color, enum bar_slot slot, unsigned well, + uint8_t r, uint8_t g, uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_bar_label(color, slot, well, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static void expect_day(const uint8_t *color, uint8_t r, uint8_t g, uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_calendar_day(color, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static const uint8_t white[] = {255, 255, 255, 173}, + light_gray[] = {0xee, 0xee, 0xee, 9}, + pale_gray[] = {0xb0, 0xb0, 0xb0, 10}, + below_gray[] = {0xaf, 0xaf, 0xaf, 11}, + cover_border[] = {0x7e, 0x81, 0x83, 127}, + accent_fill[] = {0x23, 0x6c, 0xc5, 91}, + accent_text[] = {0x31, 0x85, 0xd0, 77}, black[] = {0, 0, 0, 123}, + dim_text[] = {0x80, 0x80, 0x80, 5}, + light_text[] = {0x81, 0x81, 0x81, 6}, + inactive_day[] = {0x66, 0x66, 0x66, 255}; + +enum { ORDINARY_VIEW = 0x0dad0001 }; + +#define DARK16(c) ((uint32_t)(c) * 0x10000 / 255) + +/* Classic with Theme Default or Blue is exact in both appearances. */ +static void classic_mapping(void) +{ + for (unsigned a = ACCENT_DEFAULT; a <= ACCENT_FIRST; a++) { + style_set_accent(a); + for (int dark = 0; dark < 2; dark++) { + style_set_dark(dark); + for (unsigned c = 0; c < 256; c++) { + const uint8_t native_gray[] = {(uint8_t)c, (uint8_t)c, (uint8_t)c, 33}; + uint8_t fill_shade = + (uint8_t)(dark && c >= 0xb0 ? 0x18 + (255 - c) / 4 : c); + uint8_t text_shade = (uint8_t)(dark && c <= 0x80 ? 0xe8 - c / 2 : c); + expect_fill(native_gray, fill_shade, fill_shade, fill_shade); + expect_text(native_gray, ORDINARY_VIEW, text_shade, text_shade, + text_shade); + } + expect_text(Palette_White, ORDINARY_VIEW, 255, 255, 255); + expect_text(white, ORDINARY_VIEW, 255, 255, 255); + if (dark) { + expect_fill(cover_border, 0x38, 0x38, 0x38); + expect_fill(accent_fill, 0, 161, 255); + expect_text(accent_fill, ORDINARY_VIEW, 0, 161, 255); + expect_text(accent_text, ORDINARY_VIEW, 0, 161, 255); + expect_background(DARK16(0x18), DARK16(0x18), DARK16(0x18), 0x18c3); + } else { + expect_fill(cover_border, 0x7e, 0x81, 0x83); + expect_fill(accent_fill, 0x23, 0x6c, 0xc5); + expect_text(accent_fill, ORDINARY_VIEW, 0x23, 0x6c, 0xc5); + expect_text(accent_text, ORDINARY_VIEW, 0x31, 0x85, 0xd0); + expect_background(0x10000, 0x10000, 0x10000, 0xffff); + } + } + } + style_set_dark(0); + style_set_accent(ACCENT_DEFAULT); +} + +static void accent_mapping(void) +{ + /* Purple recolours accents but leaves Classic light surfaces and text alone. */ + style_set_accent(ACCENT_FIRST + 7); + assert(!strcmp(accent_labels[ACCENT_FIRST + 7], "Purple")); + style_set_dark(0); + expect_fill(white, 255, 255, 255); + expect_fill(light_gray, 0xee, 0xee, 0xee); + expect_fill(cover_border, 0x7e, 0x81, 0x83); + expect_text(black, ORDINARY_VIEW, 0, 0, 0); + expect_text(dim_text, ORDINARY_VIEW, 0x80, 0x80, 0x80); + expect_text(Palette_White, ORDINARY_VIEW, 255, 255, 255); + expect_fill(accent_fill, 137, 68, 171); + expect_text(accent_fill, ORDINARY_VIEW, 137, 68, 171); + expect_text(accent_text, ORDINARY_VIEW, 137, 68, 171); + expect_background(0x10000, 0x10000, 0x10000, 0xffff); + style_set_dark(1); + expect_fill(white, 0x18, 0x18, 0x18); + expect_fill(accent_fill, 150, 78, 188); + expect_text(accent_fill, ORDINARY_VIEW, 150, 78, 188); + expect_text(accent_text, ORDINARY_VIEW, 218, 143, 255); + expect_background(DARK16(0x18), DARK16(0x18), DARK16(0x18), 0x18c3); + /* Native-colour views keep their colours under every accent. */ + expect_text(accent_text, RES_Search_Input_Text, 0x31, 0x85, 0xd0); + expect_text(black, RES_Search_Input_Text, 0, 0, 0); + + /* Pink, Red, Orange, Green: the accent text presets, light and dark. */ + static const struct { + const char *label; + uint8_t light[3], dark[3]; + } presets[] = { + {"Pink", {196, 30, 86}, {255, 100, 145}}, + {"Red", {208, 32, 40}, {255, 105, 97}}, + {"Orange", {184, 72, 0}, {255, 159, 10}}, + {"Green", {30, 128, 58}, {48, 209, 88}}, + }; + + for (unsigned i = 0; i < 4; i++) { + unsigned a = ACCENT_FIRST; + while (strcmp(accent_labels[a], presets[i].label)) + a++; + style_set_accent(a); + style_set_dark(0); + expect_text(accent_text, ORDINARY_VIEW, presets[i].light[0], + presets[i].light[1], presets[i].light[2]); + style_set_dark(1); + expect_text(accent_text, ORDINARY_VIEW, presets[i].dark[0], presets[i].dark[1], + presets[i].dark[2]); + } + /* An accent past the list is Theme Default. */ + style_set_accent(ACCENTS); + assert(style_accent() == ACCENT_DEFAULT); + style_set_dark(0); +} + +static void theme_mapping(void) +{ + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t sepia[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {250, 240, 220}, + [RVT_ROLE_TEXT] = {60, 40, 20}, + [RVT_ROLE_ACCENT_FILL] = {160, 80, 30}, + [RVT_ROLE_ACCENT_TEXT] = {140, 70, 20}, + [RVT_ROLE_ON_ACCENT] = {20, 10, 0}, + [RVT_ROLE_SELECTION] = {160, 80, 30}, + [RVT_ROLE_COVER_BORDER] = {120, 100, 80}, + }; + static const uint8_t orange[RVT_ACCENT_SLOTS][3] = { + [RVT_SLOT_ACCENT_FILL] = {190, 76, 0}, [RVT_SLOT_ACCENT_TEXT] = {255, 159, 10}, + [RVT_SLOT_SELECTION] = {190, 76, 0}, [RVT_SLOT_ON_ACCENT] = {255, 255, 255}, + [RVT_SLOT_ICON_TINT] = {255, 159, 10}, + }; + prefix_custom(prefix, sepia, RVT_FLAG_FLAT_NOW_PLAYING, RVT_ACCENT_ORANGE, orange); + style_set(prefix); + tint_refresh(); + /* A theme's colours hold in both appearances. */ + for (int dark = 0; dark < 2; dark++) { + style_set_dark(dark); + expect_fill(white, 250, 240, 220); + expect_fill(light_gray, 250 - 17, 240 - 17, 220 - 17); + expect_fill(pale_gray, 250 - 79, 240 - 79, 220 - 79); + expect_fill(below_gray, 0xaf, 0xaf, 0xaf); + expect_fill(cover_border, 120, 100, 80); + expect_fill(accent_fill, 160, 80, 30); + expect_text(black, ORDINARY_VIEW, 60 - 32, 40 - 32, 0); + expect_text(dim_text, ORDINARY_VIEW, 60 + 96, 40 + 96, 20 + 96); + expect_text(light_text, ORDINARY_VIEW, 0x81, 0x81, 0x81); + expect_text(accent_fill, ORDINARY_VIEW, 160, 80, 30); + expect_text(accent_text, ORDINARY_VIEW, 140, 70, 20); + /* Selected-row text follows on_accent by pointer; other white text + * takes the text role on this light background. */ + expect_text(Palette_White, ORDINARY_VIEW, 20, 10, 0); + expect_text(white, ORDINARY_VIEW, 60, 40, 20); + expect_text(light_gray, ORDINARY_VIEW, 0xee, 0xee, 0xee); + expect_background(DARK16(250), DARK16(240), DARK16(220), + (31u << 11) | (60u << 5) | 27u); + /* Retained-light views stay unmapped. */ + expect_text(black, RES_Settings_DateTime_NumericDay, 0, 0, 0); + expect_text(Palette_White, RES_Settings_DateTime_NumericDay, 255, 255, 255); + assert(stock_background(RES_NowPlaying_White_Background_View) && + !stock_background(ORDINARY_VIEW)); + /* A view drawn inside another's background fill gives the outer + * rule back. */ + int outer = enter_background(RES_NowPlaying_White_Background_View); + assert(!outer && stock_fill); + int inner = enter_background(ORDINARY_VIEW); + assert(inner && !stock_fill); + stock_fill = inner; + assert(stock_fill); + stock_fill = outer; + assert(!stock_fill); + /* A fill onto a coverage mask keeps its colour: white clears a text + * bitmap; onto a pixel surface it is mapped. */ + static uint8_t surface[0x20]; + uint8_t mapped[4]; + *(uint16_t *)(surface + Surface_format) = + BMapFormat_Mask8 | BMapFormat_ByteSwapped; + assert(fill_color(surface, white, mapped) == white); + *(uint16_t *)(surface + Surface_format) = BMapFormat_Mask4; + assert(fill_color(surface, white, mapped) == white); + *(uint16_t *)(surface + Surface_format) = BMapFormat_RGB565; + assert(fill_color(surface, white, mapped) == mapped && mapped[0] == 250); + *(uint16_t *)(surface + Surface_format) = BMapFormat_Indexed8; + assert(fill_color(surface, white, mapped) == mapped); + } + /* Accents on a theme use its authored palette, icon tint included. */ + unsigned a = ACCENT_FIRST; + while (strcmp(accent_labels[a], "Orange")) + a++; + style_set_accent(a); + expect_fill(accent_fill, 190, 76, 0); + expect_text(accent_text, ORDINARY_VIEW, 255, 159, 10); + expect_fill(white, 250, 240, 220); + assert(style_color(RVT_ROLE_ICON_TINT)[0] == 255 && + style_color(RVT_ROLE_ICON_TINT)[1] == 159); + style_set_accent(ACCENT_DEFAULT); + expect_fill(accent_fill, 160, 80, 30); + assert(!style_color(RVT_ROLE_ICON_TINT)[0]); /* the prefix's own, zero here */ + + /* A dark theme inverts the stock shades and clamps the channels. */ + static const uint8_t night[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {250, 10, 40}, + [RVT_ROLE_TEXT] = {255, 250, 100}, + [RVT_ROLE_ACCENT_FILL] = {160, 80, 30}, + [RVT_ROLE_ACCENT_TEXT] = {140, 70, 20}, + [RVT_ROLE_ON_ACCENT] = {20, 10, 0}, + [RVT_ROLE_SELECTION] = {160, 80, 30}, + [RVT_ROLE_COVER_BORDER] = {120, 100, 80}, + }; + prefix_custom(prefix, night, 0, 0, NULL); + style_set(prefix); + tint_refresh(); + style_set_dark(0); + expect_fill(white, 250, 10, 40); + expect_fill(pale_gray, 255, 10 + 19, 40 + 19); + expect_text(black, ORDINARY_VIEW, 255, 250, 100); + expect_text(dim_text, ORDINARY_VIEW, 255 - 64, 250 - 64, 100 - 64); + expect_text(white, ORDINARY_VIEW, 255, 255, + 255); /* a dark background keeps white */ + expect_background(DARK16(250), DARK16(10), DARK16(40), + (31u << 11) | (2u << 5) | 5u); + style_reset(); + style_set_dark(0); + expect_fill(white, 255, 255, 255); +} + +/* Bar labels: the highlighted one takes on_accent whenever anything is + * themed; the others take the colour derived from the well art under a + * theme. Without a theme the Now Playing bar keeps its highlighted label, + * and its others follow the well under Dark. */ +static void bar_mapping(void) +{ + static const uint8_t native[] = {255, 255, 255, 201}; + static const uint8_t blue[] = {10, 120, 210, 255}, gray[] = {60, 60, 60, 255}; + uint8_t prefix[RVT_STYLE_BYTES]; + style_reset(); + style_set_dark(0); + style_set_accent(ACCENT_FIRST + + 7); /* Purple on Classic: white on_accent, stock wells */ + tint_refresh(); + expect_bar(native, BAR_SELECTED, WELL_BLACK, 255, 255, 255); + expect_bar(native, BAR_LABEL, WELL_BLACK, 255, 255, 255); + expect_bar(native, BAR_OTHER, WELL_WHITE, 255, 255, 255); + assert(!tint_well_letter_color(WELL_BLACK)); + expect_bar(blue, BAR_SELECTED, WELL_NOW_PLAYING, 10, 120, 210); + expect_bar(gray, BAR_LABEL, WELL_NOW_PLAYING, 60, 60, 60); + /* Bitmap 1's centre is light, so the dark background role. */ + style_set_dark(1); + tint_refresh(); + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + expect_bar(gray, BAR_LABEL, WELL_NOW_PLAYING, background[0], background[1], + background[2]); + expect_bar(blue, BAR_SELECTED, WELL_NOW_PLAYING, 10, 120, 210); + assert(!tint_well_letter_color(WELL_WHITE) && !tint_well_letter_color(WELL_BLACK)); + style_set_dark(0); + tint_refresh(); + style_set_accent(ACCENT_DEFAULT); + /* Under a theme the wells' letters contrast with the well art: bitmap 1's + * centre is the light colour, so the dark text role. */ + static const uint8_t sepia[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {250, 240, 220}, + [RVT_ROLE_TEXT] = {60, 40, 20}, + [RVT_ROLE_ACCENT_FILL] = {160, 80, 30}, + [RVT_ROLE_ACCENT_TEXT] = {140, 70, 20}, + [RVT_ROLE_ON_ACCENT] = {20, 10, 0}, + [RVT_ROLE_SELECTION] = {160, 80, 30}, + [RVT_ROLE_COVER_BORDER] = {120, 100, 80}, + }; + prefix_custom(prefix, sepia, 0, 0, NULL); + style_set(prefix); + tint_refresh(); + for (unsigned well = 0; well < WELLS; well++) { + expect_bar(native, BAR_SELECTED, well, 20, 10, 0); + expect_bar(native, BAR_LABEL, well, 60, 40, 20); + expect_bar(native, BAR_OTHER, well, 255, 255, 255); + } + assert(!tint_well_letter_color(WELLS)); + /* The Search field text follows the field art the same way; the caret's + * accent blue takes accent_text like any other text. */ + expect_text(black, RES_Search_Input_Text, 60, 40, 20); + expect_text(dim_text, RES_Search_Input_Text, 60, 40, 20); + expect_text(accent_text, RES_Search_Input_Text, 140, 70, 20); + /* Labels over listed art take the contrast colour, also over the + * white-text mapping; other views do not. */ + static const uint8_t status[] = {0xd3, 0xd3, 0xd3, 255}; + expect_text(status, RES_NowPlaying_StatusBar_Text_View, 60, 40, 20); + expect_text(white, RES_NowPlaying_StatusBar_Text_View, 60, 40, 20); + expect_text(status, ORDINARY_VIEW, 0xd3, 0xd3, 0xd3); + /* Clear art keeps the stock colour. */ + uint8_t *center = catalog_data(PALETTED) + at_data(PALETTED) + 3; + *center = 0; + tint_refresh(); + assert(!tint_field_text_color() && !tint_well_letter_color(WELL_WHITE) && + !tint_contrast_text_color(RES_NowPlaying_StatusBar_Text_View)); + expect_text(status, RES_NowPlaying_StatusBar_Text_View, 0xd3, 0xd3, 0xd3); + expect_text(dim_text, RES_Search_Input_Text, 60 + 96, 40 + 96, 20 + 96); + *center = 255; + tint_refresh(); + /* Calendar days: the shown month's on the active cell's contrast colour, + * a neighbouring month's mixed halfway toward the cell, weekday names + * halfway toward the page, the selected day in on_accent. */ + uint8_t out[4], half[4]; + expect_day(black, 60, 40, 20); + static const uint8_t light_rgba[4] = {240, 244, 247, + 255}; /* LIGHT, read out of BGRA */ + color_mix(half, style_color(RVT_ROLE_TEXT), light_rgba, 128); + expect_day(inactive_day, half[0], half[1], half[2]); + color_mix(half, style_color(RVT_ROLE_TEXT), style_color(RVT_ROLE_BACKGROUND), 128); + assert(tint_calendar_text_color(CALENDAR_HEADER, out) == out && + !memcmp(out, half, 4)); + assert(!tint_calendar_text_color(CALENDAR_HILITE, out)); + expect_day(white, 20, 10, 0); + /* Classic keeps every native colour. */ + style_reset(); + expect_day(black, 0, 0, 0); + expect_day(white, 255, 255, 255); + assert(!tint_calendar_text_color(CALENDAR_HEADER, out) && !tint_field_text_color()); + expect_text(black, RES_Search_Input_Text, 0, 0, 0); +} + +/* Tinted art: a highlighted view draws a tinted paletted bitmap in on_accent + * and puts the tint back; tinted ARGB art keeps its tint; masks are coloured + * while drawing; an unknown bitmap takes the icon tint role under a theme. */ +static void tint_contracts(void) +{ + uint8_t prefix[RVT_STYLE_BYTES], tint[RVT_CATALOG_MAX] = {0}; + static const uint8_t roles[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {1, 2, 3}, [RVT_ROLE_TEXT] = {4, 5, 6}, + [RVT_ROLE_ACCENT_FILL] = {7, 8, 9}, [RVT_ROLE_ACCENT_TEXT] = {40, 50, 60}, + [RVT_ROLE_ON_ACCENT] = {88, 0, 0}, [RVT_ROLE_SELECTION] = {11, 12, 13}, + [RVT_ROLE_COVER_BORDER] = {14, 15, 16}, [RVT_ROLE_ICON_TINT] = {10, 20, 30}, + }; + tint[MASK] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + tint[ARGB] = RVT_TINT_ROLE + RVT_ROLE_SELECTION; + tint[WIDE] = RVT_TINT_ROLE + RVT_ROLE_TEXT; + prefix_custom(prefix, roles, 0, 0, NULL); + memcpy(prefix + RVT_STYLE_TINTS, tint, RVT_CATALOG_MAX); + style_set(prefix); + tint_refresh(); + assert(!memcmp(catalog_data(SECOND) + at_data(SECOND), (uint8_t[]){30, 20, 10, 255}, + 4)); + assert(!memcmp(catalog_data(ARGB) + HEADER, (uint8_t[]){13, 12, 11, 255}, 4) && + catalog_data(ARGB)[HEADER + 31] == 0); + /* Views and contexts as the hooks see them. */ + static uint8_t view[0x200], context[0x40], bitmap[0x20], foreign[0x20], + other_context[0x40]; + const uint8_t *pixels = catalog_data(SECOND) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + uint8_t *bitmap_p = bitmap; + memcpy(context + GraphicsContext_bitmap, &bitmap_p, sizeof bitmap_p); + uint8_t *context_p = context; + memcpy(view + BitmapView_context, &context_p, sizeof context_p); + assert(tint_mask_color(view)[0] == 10); + *(uint32_t *)(view + View_flags) = ViewFlags_Highlighted; + assert(tint_mask_color(view)[0] == 88); + tint_highlight_begin(view, context); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 88 && + catalog_data(SECOND)[at_data(SECOND) + 6] == 88); + tint_highlight_end(); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 10); + /* A blit inside the two halves of another: the first asset stays the + * highlighted one and the second keeps its tint. */ + static uint8_t wide_bitmap[0x20], wide_context[0x40]; + const uint8_t *wide_pixels = catalog_data(WIDE) + HEADER; + memcpy(wide_bitmap + Bitmap_pixels, &wide_pixels, sizeof wide_pixels); + uint8_t *wide_bitmap_p = wide_bitmap; + memcpy(wide_context + GraphicsContext_bitmap, &wide_bitmap_p, sizeof wide_bitmap_p); + uint8_t wide_tinted[4]; + memcpy(wide_tinted, catalog_data(WIDE) + at_data(WIDE), 4); + tint_highlight_begin(view, context); + tint_highlight_begin(view, wide_context); + assert(highlighted == SECOND + 1 && + !memcmp(catalog_data(WIDE) + at_data(WIDE), wide_tinted, 4)); + tint_highlight_end(); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 10 && !highlighted); + tint_highlight_begin(view, wide_context); + assert(highlighted == WIDE + 1 && catalog_data(WIDE)[at_data(WIDE) + 2] == 88); + tint_highlight_end(); + assert(!memcmp(catalog_data(WIDE) + at_data(WIDE), wide_tinted, 4)); + /* A pointer into a bitmap's middle and a bitmap outside the bank are no + * catalog bitmap: an extension's own icon, drawn in the icon tint role. */ + pixels = catalog_data(SECOND) + HEADER + 4; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + assert(tint_mask_color(view)[0] == 88); + pixels = foreign; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + assert(tint_mask_color(view)[0] == 88); + *(uint32_t *)(view + View_flags) = 0; + assert(tint_mask_color(view)[0] == 10); + pixels = catalog_data(PALETTED) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + assert(!tint_mask_color(view)); + /* ARGB art is not rewritten for a highlight. */ + pixels = catalog_data(ARGB) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + *(uint32_t *)(view + View_flags) = ViewFlags_Highlighted; + tint_highlight_begin(view, context); + assert(catalog_data(ARGB)[HEADER + 2] == 11); + tint_highlight_end(); + /* A calendar marker turns on_accent over the selected day's cell art only. */ + static uint8_t cell[0x200]; + pixels = catalog_data(SECOND) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + memcpy(cell + CalendarDayCell_art, &context_p, sizeof context_p); + const uint8_t *hilite = catalog_data(PALETTED) + HEADER; + static uint8_t hilite_bitmap[0x20]; + memcpy(hilite_bitmap + Bitmap_pixels, &hilite, sizeof hilite); + uint8_t *hilite_p = hilite_bitmap; + memcpy(other_context + GraphicsContext_bitmap, &hilite_p, sizeof hilite_p); + uint8_t *other_p = other_context; + memcpy(cell + CalendarDayCell_art, &other_p, sizeof other_p); + tint_marker_highlight_begin(cell, context); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 88); + tint_highlight_end(); + memcpy(cell + CalendarDayCell_art, &context_p, sizeof context_p); + tint_marker_highlight_begin(cell, context); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 10); + tint_highlight_end(); + style_reset(); + assert(!tint_mask_color(view)); + reset_bank(); +} + +/* A flat look copies only a 128 by 128 RGB565 image with packed rows into the + * colour buffer and skips the edge lines; any other image, or a look without + * the flag under Theme, keeps the stock drawing. The copy itself needs the 32-bit Bitmap + * layout (the pixel pointer and the stride overlap on a 64-bit host), so the + * emulator covers it. */ +static void cover_contracts(void) +{ + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t roles[RVT_ROLES][3] = {{0}}; + int32_t bounds[4] = {0, 0, 128, 128}; + memcpy(cover_image + Bitmap_bounds, bounds, sizeof bounds); + *(uint16_t *)(cover_image + Bitmap_format) = BMapFormat_RGB565; + *(uint32_t *)(cover_image + Bitmap_stride) = 256; + assert(copyable(cover_image)); + *(uint32_t *)(cover_image + Bitmap_stride) = 512; + assert(!copyable(cover_image)); + *(uint32_t *)(cover_image + Bitmap_stride) = 256; + *(uint16_t *)(cover_image + Bitmap_format) = BMapFormat_BGRA8888; + assert(!copyable(cover_image)); + *(uint16_t *)(cover_image + Bitmap_format) = BMapFormat_RGB565; + bounds[2] = 100; + memcpy(cover_image + Bitmap_bounds, bounds, sizeof bounds); + assert(!copyable(cover_image)); + prefix_custom(prefix, roles, RVT_FLAG_FLAT_NOW_PLAYING, 0, NULL); + style_set(prefix); + assert(flat_cover_edge_lines(2, NULL) == 0); + drawing_view = + &cover_view; /* inside the view's draw, but the image is not copyable */ + assert(flat_cover_renderer_draw(1, NULL) == 0x600d && passed[0] == 1); + drawing_view = NULL; + assert(flat_cover_renderer_draw(1, NULL) == 0x600d); + style_reset(); + assert(flat_cover_renderer_draw(1, NULL) == 0x600d && + flat_cover_edge_lines(2, NULL) == 0x600d); + /* The setting over the look: Tilted keeps the stock draw under a flat + * theme, Flat copies under stock, Theme follows the flag again. */ + flat_cover_set(NP_COVER_FLAT); + assert(flat_cover_flat() && flat_cover_edge_lines(2, NULL) == 0); + style_set(prefix); + flat_cover_set(NP_COVER_TILTED); + assert(!flat_cover_flat() && flat_cover_edge_lines(2, NULL) == 0x600d); + flat_cover_set(NP_COVER_THEME); + assert(flat_cover_flat()); + style_reset(); + assert(!flat_cover_flat()); +} + +/* The latch: the first action binds the watch and holds presses off until + * the message loop runs dry after the switch, which also ends the watch; a + * watch still bound goes at unload; without memory for the watch the switch + * runs unlatched. */ +static void latch_contracts(void) +{ + int before = binds; + assert(latch_begin() && binds == before + 1 && !latch_begin()); + next_result = 0; + assert(process_message(1, 0, NULL) == 0 && binds == before + 1 && + latched); /* still loading */ + latch_finish(); + next_result = 0x600d; + assert(process_message(1, 0, NULL) == 0x600d && latched); /* a message handled */ + next_result = 0; + assert(process_message(1, 0, NULL) == 0 && !latched && binds == before); + assert(latch_begin() && latched && binds == before + 1); + latch_finish(); + latch_unload(); + assert(binds == before && !latched); + bind_failures_at = binds + 1; + assert(latch_begin() && binds == before && !latched); + bind_failures_at = 0; + latch_finish(); + latch_unload(); + next_result = 0x600d; +} + +/* The Theme list: Classic, the folder's themes in order, the active theme + * kept in order when the list is full, and a last row for the overflow or + * the trouble. */ +static void picker_contracts(void) +{ + static char many_names[70][16]; + static const char *many[70]; + const char *detail = (const char *)1; + for (unsigned i = 0; i < 70; i++) { + snprintf(many_names[i], sizeof many_names[i], "t%02u.rvt", i); + many[i] = many_names[i]; + } + folder = many; + folder_count = 70; + unreadable = NULL; + provided = NULL; + memset(&look_state.active, 0, sizeof look_state.active); + strcpy(look_state.active.id, "t99"); + strcpy(look_state.active.name, "Last"); + assert(theme_picker_rows(NULL) == 1 + 64 + 1 && allocations == 1 && count == 64); + assert(!strcmp(theme_picker_row(NULL, 0, &detail), "Classic") && !detail); + assert(!strcmp(theme_picker_row(NULL, 1, &detail), "Named") && + !strcmp(entries[0].id, "t00")); + assert(!strcmp(entries[62].id, "t62") && !strcmp(entries[63].id, "t99")); + assert(!strcmp(theme_picker_row(NULL, 64, &detail), "Last")); + assert(!strcmp(theme_picker_row(NULL, 65, &detail), "Showing 64 themes")); + assert(theme_picker_initial(NULL) == 64 && !theme_picker_select(NULL, 65) && + !module_loaded); + theme_picker_closed(NULL); + assert(!allocations && !count && !overflow && !scanned); + /* Sorting inside the list: inserted in place, the last entry dropped. */ + strcpy(look_state.active.id, "t005"); + assert(theme_picker_rows(NULL) == 66 && !strcmp(entries[1].id, "t005") && + !strcmp(entries[2].id, "t01")); + assert(!strcmp(entries[63].id, "t62") && theme_picker_initial(NULL) == 2); + theme_picker_closed(NULL); + /* Listed already: nothing moves. */ + strcpy(look_state.active.id, "t10"); + assert(theme_picker_rows(NULL) == 66 && !strcmp(entries[10].id, "t10") && + !strcmp(entries[63].id, "t63")); + assert(theme_picker_initial(NULL) == 11); + theme_picker_closed(NULL); + /* Room for every theme: the active one is among them or it is Classic's turn. */ + folder_count = 5; + strcpy(look_state.active.id, "zzz"); + assert(theme_picker_rows(NULL) == 6 && theme_picker_initial(NULL) == 0); + theme_picker_closed(NULL); + strcpy(look_state.active.id, "t03"); + assert(theme_picker_rows(NULL) == 6 && theme_picker_initial(NULL) == 4); + theme_picker_closed(NULL); + /* An empty folder lists Classic alone; no memory for the list says so. */ + folder_count = 0; + assert(theme_picker_rows(NULL) == 1 && !allocations); + theme_picker_closed(NULL); + folder_count = 5; + alloc_fails = 1; + assert(theme_picker_rows(NULL) == 2 && + !strcmp(theme_picker_row(NULL, 1, &detail), "Not enough memory")); + theme_picker_closed(NULL); + assert(!allocations); + folder_count = 0; + memset(&look_state.active, 0, sizeof look_state.active); +} + +/* The draw hooks bind while a look is on; a bind that fails leaves none bound. */ +static void bind_contracts(void) +{ + assert(render_bind(1) && binds == (int)THEMED_HOOKS); + assert(render_bind(1) && binds == (int)THEMED_HOOKS); + assert(render_bind(0) && binds == 0); + bind_failures_at = 5; + assert(!render_bind(1) && binds == 0); + bind_failures_at = 0; + assert(render_bind(0) && binds == 0); +} + +/* The whole of a switch from main's side: a saved theme whose file is gone + * falls back to Classic in the saved appearance, the settings keep the + * appearance and drop the id, the draw hooks and the latch bind, and unload + * puts everything back. */ +static void look_contracts(void) +{ + char id[RVT_ID_BYTES] = "example"; + memset(&look_state, 0, sizeof look_state); + style_reset(); + style_set_dark(0); + style_set_accent(ACCENT_DEFAULT); + strcpy(theme_id_setting, "example"); + setting_set_int(NULL, KEY_DARK, DARK_ON); + setting_ints[KEY_ACCENT] = ACCENT_DEFAULT; + setting_ints[KEY_AVAILABLE] = 1; + folder_count = 0; + unreadable = "example"; + redraws = 0; + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!look_state.active.id[0] && look_state.active.dark && style_dark() && + !style_from_theme()); + assert(setting_ints[KEY_DARK] == DARK_ON && !strcmp(theme_id_setting, "example") && + setting_ints[KEY_AVAILABLE] == 1); + assert(!strcmp(look_problem(PANE_THEME), "Theme unavailable") && + !look_problem(PANE_DARK)); + assert(look_dark_available() && + binds == (int)THEMED_HOOKS + 1); /* the draw hooks and the latch */ + assert(canvas_colors && redraws == 1 && !module_loaded && !open_files && + !look_theming_off()); + /* A second press while the latch holds changes nothing. */ + look_switch(id, 0, ACCENT_DEFAULT, PANE_DARK); + assert(look_state.active.dark && setting_ints[KEY_DARK] == DARK_ON && redraws == 1); + /* An accent change keeps the stored theme too; choosing Classic drops it. */ + latch_unload(); + look_accent(ACCENT_FIRST); + assert(!strcmp(theme_id_setting, "example") && style_accent() == ACCENT_FIRST); + latch_unload(); + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!theme_id_setting[0] && !look_problem(PANE_THEME)); + latch_unload(); + look_unload(); + assert(bank_is_stock() && binds == 0 && !canvas_colors && !look_state.active.dark); + + /* A theme with one appearance is shown in it whatever Dark Mode asked: + * the row's value and the stored setting say which, the pane says what + * the theme lacks, and a refused toggle leaves them so. */ + struct built light_only, dark_only; + build_light_only(&light_only, PROVIDED_ID, "Day"); + build_file_at(&dark_only, PROVIDED_ID, "Night", RVT_HEADER_BYTES, NULL, 0, NULL, 0, + NULL, NULL); + provided = &light_only; + unreadable = NULL; + memset(id, 0, sizeof id); /* ids are zero-padded */ + strcpy(id, PROVIDED_ID); + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(look_state.active.id, PROVIDED_ID) && !look_state.active.dark && + !style_dark()); + assert(setting_ints[KEY_DARK] == DARK_OFF && !look_dark_available() && + !look_problem(PANE_DARK) && !look_problem(PANE_THEME) && + !strcmp(look_appearance_note(), "Theme only supports light mode")); + latch_unload(); + setting_set_int(NULL, KEY_DARK, + DARK_ON); /* the press, as the store sees it first */ + look_switch(id, 1, ACCENT_DEFAULT, PANE_DARK); + assert(!look_state.active.dark && setting_ints[KEY_DARK] == DARK_OFF && + !look_problem(PANE_DARK) && + !strcmp(look_appearance_note(), "Theme only supports light mode") && + !open_files); + latch_unload(); + provided = &dark_only; + look_switch(id, 0, ACCENT_DEFAULT, PANE_THEME); + assert(look_state.active.dark && style_dark() && + setting_ints[KEY_DARK] == DARK_ON && + !strcmp(look_appearance_note(), "Theme only supports dark mode")); + latch_unload(); + setting_set_int(NULL, KEY_DARK, DARK_OFF); + look_switch(id, 0, ACCENT_DEFAULT, PANE_DARK); + assert(look_state.active.dark && setting_ints[KEY_DARK] == DARK_ON && + !look_problem(PANE_DARK) && + !strcmp(look_appearance_note(), "Theme only supports dark mode")); + latch_unload(); + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!look_appearance_note() && look_dark_available()); + latch_unload(); + look_unload(); + provided = NULL; + + /* A theme with bitmaps for extensions, or one asking for flat icons, + * holds the core's asset provider; Classic and unload release it and free + * the index; the end of disk mode keeps both until another file turns up + * under the id; a provider another extension holds is said under Theme. */ + struct built with, flat, swapped; + const struct asset_payload one = { + OWNER_A, 5, RVT_EXTENSION_BITMAP, sizeof menu_a, MENU_BMAP_BYTES, menu_a, 0}; + with_assets(&one, 1, &with); + provided = &with; + unreadable = NULL; + strcpy(id, PROVIDED_ID); + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(look_state.active.id, PROVIDED_ID) && core_provider == &provider && + live_count == 1); + assert(look_state.active.header_crc == le32(with.bytes + RVT_HEADER_CRC) && + !look_problem(PANE_THEME)); + latch_unload(); /* the message queue empties between presses */ + look_accent(ACCENT_FIRST); + assert(core_provider == &provider && live_count == 1); + latch_unload(); + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!core_provider && !live_count && !allocations); + latch_unload(); + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(core_provider == &provider); + latch_unload(); + look_volume_changed(); + assert(core_provider == &provider && live_count == 1 && !look_state.stock_checked); + build_file_at(&swapped, PROVIDED_ID, "Other", RVT_HEADER_BYTES, NULL, 0, NULL, 0, + NULL, NULL); + provided = &swapped; + look_volume_changed(); + assert(!core_provider && !live_count && !allocations && !open_files); + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t roles[RVT_ROLES][3] = {{0}}; + prefix_custom(prefix, roles, RVT_FLAG_FLAT_ICONS, 0, NULL); + build_file_at(&flat, PROVIDED_ID, "Flat", RVT_HEADER_BYTES, NULL, 0, NULL, 0, NULL, + prefix); + provided = ♭ + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(core_provider == &provider && !live_count); + latch_unload(); + provided = &swapped; /* flat icons stay bound without an index */ + look_volume_changed(); + assert(core_provider == &provider && !live_count); + provided = ♭ + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!core_provider); + latch_unload(); + provider_held = 1; + provided = &with; + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(look_problem(PANE_THEME), "Artwork held by another extension") && + live_count == 1); + assert(!core_provider); + provider_held = 0; + look_unload(); + assert(!core_provider && !live_count && !allocations && bank_is_stock()); + provided = NULL; +} + +/* Sunrise and sunset against NOAA's formula in double precision, in UTC. */ +/* The schedule: night from the sunset minute to the sunrise minute, by the + * clock in the time zone's city; the polar states; no zone is day. */ +static void schedule_contracts(void) +{ + struct schedule s; + /* Without a known zone: day, and the caption asks for one. */ + schedule_read(&s); + assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); + assert(!strcmp(schedule_caption(), "Set a time zone")); + /* Berlin, 21 June: sunset 21:33 CEST, sunrise 04:43 (NOAA, within 3 minutes). */ + put16(host_zones + 90 * TimeZone_bytes + TimeZone_zone_id, 0x1234); + memcpy(host_app + App_browser, &(uint8_t *){host_browser}, sizeof(void *)); + memcpy(host_browser + MediaBrowser_preferences, &(uint8_t *){host_preferences}, + sizeof(void *)); + put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); + clock_now[DateTime_hour] = 21, clock_now[DateTime_minute] = 0; + clock_now[DateTime_day] = 21, clock_now[DateTime_month] = 6; + put16(clock_now + DateTime_year, 2026); + clock_zone = 60, clock_dst = 60; + schedule_read(&s); + assert(s.state == SCHEDULE_RISES && s.now == 21 * 60 && !schedule_night(&s)); + assert(abs(s.set - (21 * 60 + 33)) <= 3 && abs(s.rise - (4 * 60 + 43)) <= 3); + clock_now[DateTime_hour] = (uint8_t)(s.set / 60), + clock_now[DateTime_minute] = (uint8_t)(s.set % 60); + schedule_read(&s); + assert(schedule_night(&s)); /* the sunset minute itself */ + clock_now[DateTime_minute]--; + schedule_read(&s); + assert(!schedule_night(&s)); + clock_now[DateTime_hour] = (uint8_t)(s.rise / 60), + clock_now[DateTime_minute] = (uint8_t)(s.rise % 60); + schedule_read(&s); + assert(!schedule_night(&s)); /* the sunrise minute is day */ + clock_now[DateTime_minute]--; + schedule_read(&s); + assert(schedule_night(&s)); + assert(!strcmp(schedule_caption(), "Sunset to Sunrise")); + /* No city in Apple's zones lies beyond a polar circle, so the polar states + * are checked on their own. */ + s.state = SCHEDULE_NEVER_RISES; + assert(schedule_night(&s)); + s.state = SCHEDULE_NEVER_SETS; + assert(!schedule_night(&s)); + /* No such zone: day, and the caption asks for one. */ + put16(host_preferences + PreferencesFile_time_zone_id, 0x7777); + schedule_read(&s); + assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); + assert(!strcmp(schedule_caption(), "Set a time zone")); + put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); + clock_now[DateTime_hour] = 23, clock_now[DateTime_minute] = 0; +} + +/* Dark Mode: On and Off ask for themselves, Auto asks for the schedule's + * night; a switch that shows what Auto asked for keeps Auto, one that cannot + * writes the appearance on the screen. */ +static void dark_mode_contracts(void) +{ + struct built light_only; + char id[RVT_ID_BYTES]; + setting_set_int(NULL, KEY_DARK, DARK_ON); + assert(dark_mode_wanted() && !dark_mode_auto()); + setting_set_int(NULL, KEY_DARK, DARK_OFF); + assert(!dark_mode_wanted()); + setting_set_int(NULL, KEY_DARK, DARK_AUTO); + assert(dark_mode_auto() && dark_mode_wanted()); /* Berlin, 23:00 */ + clock_now[DateTime_hour] = 13; + assert(!dark_mode_wanted()); + clock_now[DateTime_hour] = 23; + + memset(&look_state, 0, sizeof look_state); + style_reset(); + style_set_dark(0); + theme_id_setting[0] = 0; + unreadable = NULL; + redraws = 0; + look_switch("", dark_mode_wanted(), ACCENT_DEFAULT, PANE_DARK); + assert(look_state.active.dark && setting_ints[KEY_DARK] == DARK_AUTO); + assert(!strcmp(dark_mode_caption(), "Sunset to Sunrise")); + latch_unload(); + /* A light-only theme at night: the screen stays light and the setting says Off. */ + build_light_only(&light_only, PROVIDED_ID, "Day"); + provided = &light_only; + memset(id, 0, sizeof id); + strcpy(id, PROVIDED_ID); + look_switch(id, dark_mode_wanted(), ACCENT_DEFAULT, PANE_THEME); + assert(!look_state.active.dark && setting_ints[KEY_DARK] == DARK_OFF && + !dark_mode_auto()); + assert(!strcmp(dark_mode_caption(), "Theme only supports light mode")); + latch_unload(); + look_switch("", 0, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(dark_mode_caption(), "Off")); + latch_unload(); + look_unload(); + provided = NULL; +} + +int main(void) +{ + rv_module_entry(&fake, NULL); + assert(main_module == &host_service); + build_bank(); + + reader_contracts(); + puts("PASS: theme file reader"); + switch_contracts(); + puts("PASS: switch and recovery"); + assets_contracts(); + puts("PASS: bitmaps for extensions"); + scan_contracts(); + puts("PASS: theme folder"); + classic_mapping(); + accent_mapping(); + theme_mapping(); + bar_mapping(); + puts("PASS: colour mapping"); + tint_contracts(); + cover_contracts(); + latch_contracts(); + picker_contracts(); + bind_contracts(); + puts("PASS: tinted art, flat cover, latch, theme list, hook binding"); + look_contracts(); + puts("PASS: look fallback and unload"); + schedule_contracts(); + dark_mode_contracts(); + puts("PASS: schedule, Dark Mode"); + return 0; +} diff --git a/extensions/appearance/tests/run.py b/extensions/appearance/tests/run.py new file mode 100755 index 0000000..b0f63c1 --- /dev/null +++ b/extensions/appearance/tests/run.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the appearance contracts with a staged SDK: python3 tests/run.py SDK. + +The extension's logic is built natively, both modules in one program, over a +bitmap bank and a firmware file in host memory. Hook handlers carry pointers in +uint32_t by the ARM convention, so the host build allows the narrowing casts and +reads Apple's struct fields unaligned.""" + +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="appearance-tests-") as name: + work = Path(name) + for header in ("rv_api.h", "rv_libc.h", "rv_ui.h", "rv_theme.h", "rv_sites.h", "osos-2.0.5.h"): + (work / header).write_text((sdk / header).read_text()) + executable = work / "contracts" + subprocess.run( + [ + "cc", + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-Wno-int-to-pointer-cast", + "-Wno-pointer-to-int-cast", + "-g", + "-fsanitize=address,undefined", + "-fno-sanitize=alignment", + "-I", + str(root), + "-I", + str(work), + "-I", + str(root.parent), + "-I", + str(root.parents[1] / "shared"), + "-I", + str(root.parents[2] / "themes" / "rvt" / "data"), + str(root / "contracts.c"), + "-o", + str(executable), + ], + check=True, + ) + subprocess.run([str(executable)], check=True) +print("Appearance contracts passed") diff --git a/extensions/appearance/theme.c b/extensions/appearance/theme.c new file mode 100644 index 0000000..2d6d704 --- /dev/null +++ b/extensions/appearance/theme.c @@ -0,0 +1,279 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "theme.h" +#include "crc.h" +#include "ext.h" +#include "pixel.h" +#include "rv_libc.h" +#include + +#define FOLDER "Themes" +#define SUFFIX ".rvt" +/* The id of the built-in theme, which is the asset's name; a file of that + * name in the folder is ignored. */ +#define RESERVED_ID "classic" + +static int id_valid(const char *id) +{ + uint32_t n = 0; + for (; n < RVT_ID_BYTES && id[n]; n++) { + char c = id[n]; + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + (n && (c == '_' || c == '-')))) + return 0; + } + if (!n || n > RVT_ID_BYTES - 1) + return 0; + for (; n < RVT_ID_BYTES; n++) + if (id[n]) + return 0; + return !!memcmp(id, RESERVED_ID, sizeof RESERVED_ID); +} + +/* Printable UTF-8 up to the first NUL, zeros after it. */ +static int name_valid(const uint8_t *text, uint32_t size) +{ + uint32_t at = 0; + if (!text[0]) + return 0; + while (at < size && text[at]) { + uint32_t cp = text[at++], tails = 0, minimum = 0; + if (cp >= 0xc2 && cp <= 0xdf) + cp &= 31, tails = 1, minimum = 0x80; + else if (cp >= 0xe0 && cp <= 0xef) + cp &= 15, tails = 2, minimum = 0x800; + else if (cp >= 0xf0 && cp <= 0xf4) + cp &= 7, tails = 3, minimum = 0x10000; + else if (cp >= 0x80) + return 0; + if (tails > size - at) + return 0; + while (tails--) { + uint32_t c = text[at++]; + if ((c & 0xc0) != 0x80) + return 0; + cp = cp << 6 | (c & 63); + } + if (cp < minimum || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff) || + cp < 32 || cp == 127) + return 0; + } + if (at == size) + return 0; + for (; at < size; at++) + if (text[at]) + return 0; + return 1; +} + +/* The header (RVT_HEADER_BYTES) with its fields checked: magic, version, + * header size, checksum, fingerprint, appearances and name. The id is the + * caller's to compare. */ +static int header_read(struct rv_file *file, uint8_t *header) +{ + uint32_t got = 0; + if (api->file_seek(self, file, 0) != RV_OK || + api->file_read(self, file, header, RVT_HEADER_BYTES, &got) != RV_OK || + got != RVT_HEADER_BYTES) + return 0; + uint8_t zero[4] = {0}; + uint32_t computed = crc32_update(0xffffffffu, header, RVT_HEADER_CRC); + computed = crc32_update(computed, zero, 4); + computed = ~crc32_update(computed, header + RVT_HEADER_ID, + RVT_HEADER_BYTES - RVT_HEADER_ID); + uint32_t mask = le32(header + RVT_HEADER_APPEARANCES); + uint32_t header_bytes = le16(header + RVT_HEADER_HEADER_BYTES); + return le32(header + RVT_HEADER_MAGIC) == RVT_MAGIC && + le16(header + RVT_HEADER_VERSION) == RVT_VERSION && + header_bytes >= RVT_HEADER_BYTES && header_bytes % 4 == 0 && + computed == le32(header + RVT_HEADER_CRC) && + !memcmp(header + RVT_HEADER_FINGERPRINT, catalog_fingerprint(), + RVT_FINGERPRINT_BYTES) && + mask && !(mask & ~(uint32_t)(RVT_APPEARANCE_LIGHT | RVT_APPEARANCE_DARK)) && + name_valid(header + RVT_HEADER_NAME, RVT_NAME_BYTES); +} + +/* The light or dark pack's place from a checked header: 0 when the header + * has no such pack, puts it before its own end or off a word, or sizes it + * below a pack header and style prefix. */ +static int pack_place(const uint8_t *header, int dark, struct pack_place *pack) +{ + uint32_t at = dark ? RVT_HEADER_DARK_OFFSET : RVT_HEADER_LIGHT_OFFSET; + uint32_t offset = le32(header + at), bytes = le32(header + at + 4); + if (!offset || bytes < RVT_PACK_HEADER_BYTES + RVT_STYLE_BYTES || offset % 4 || + offset < le16(header + RVT_HEADER_HEADER_BYTES) || bytes > 0xffffffffu - offset) + return 0; + pack->offset = offset; + pack->bytes = bytes; + return 1; +} + +/* A checked header of theme `id` into `look`, or 0 for another id. */ +static int header_look(const uint8_t *header, const char *id, struct look *look) +{ + if (memcmp(header + RVT_HEADER_ID, id, RVT_ID_BYTES)) + return 0; + memset(look, 0, sizeof *look); + memcpy(look->id, header + RVT_HEADER_ID, RVT_ID_BYTES); + memcpy(look->name, header + RVT_HEADER_NAME, RVT_NAME_BYTES); + look->appearances = le32(header + RVT_HEADER_APPEARANCES); + look->header_crc = le32(header + RVT_HEADER_CRC); + return 1; +} + +static char lower(char c) +{ + return c >= 'A' && c <= 'Z' ? (char)(c + ('a' - 'A')) : c; +} + +/* The id a file name stands for: its stem in lower case, since FAT may return + * short names in capitals; 0 for another suffix or a stem that is no id. */ +static int stem_id(const char *entry, char id[RVT_ID_BYTES]) +{ + uint32_t n = 0; + while (entry[n]) + n++; + if (n < sizeof SUFFIX || n - (sizeof SUFFIX - 1) > RVT_ID_BYTES - 1) + return 0; + for (uint32_t i = 0; i < sizeof SUFFIX - 1; i++) + if (lower(entry[n - (sizeof SUFFIX - 1) + i]) != SUFFIX[i]) + return 0; + n -= sizeof SUFFIX - 1; + memset(id, 0, RVT_ID_BYTES); + for (uint32_t i = 0; i < n; i++) + id[i] = lower(entry[i]); + return id_valid(id); +} + +static void path_of(const char *id, char *path) +{ + memcpy(path, FOLDER "/", sizeof FOLDER); + uint32_t n = sizeof FOLDER; + while (*id) + path[n++] = *id++; + memcpy(path + n, SUFFIX, sizeof SUFFIX); +} + +static int theme_file_open(const char *id, struct rv_file **file) +{ + char path[sizeof FOLDER + RVT_ID_BYTES + sizeof SUFFIX]; + path_of(id, path); + return api->content_open(self, path, file) == RV_OK; +} + +int look_file_open(const struct look *look, struct rv_file **file) +{ + if (look->id[0]) + return theme_file_open(look->id, file); + return look->dark && api->asset_open(self, RESERVED_ID, file) == RV_OK; +} + +int look_pack_place(struct rv_file *file, struct look *look, struct pack_place *pack) +{ + uint8_t header[RVT_HEADER_BYTES]; + if (!header_read(file, header) || + (look->id[0] && memcmp(header + RVT_HEADER_ID, look->id, RVT_ID_BYTES))) + return 0; + look->header_crc = le32(header + RVT_HEADER_CRC); + return pack_place(header, look->dark, pack); +} + +int theme_file_matches(const char *id, uint32_t crc) +{ + uint8_t header[RVT_HEADER_BYTES]; + struct rv_file *file; + if (!theme_file_open(id, &file)) + return 0; + int same = header_read(file, header) && le32(header + RVT_HEADER_CRC) == crc; + api->file_close(self, file); + return same; +} + +static void count_entry(const char *entry, int is_folder, void *arg) +{ + char id[RVT_ID_BYTES]; + if (!is_folder && stem_id(entry, id)) + ++*(uint32_t *)arg; +} + +uint32_t theme_count(void) +{ + uint32_t n = 0; + api->content_list(self, FOLDER, count_entry, &n); + return n; +} + +struct scan { + struct theme_entry *out; + uint32_t capacity, count; + int overflow; +}; + +/* Collects ids in order while the folder is listed; files are opened after. */ +static void collect(const char *entry, int is_folder, void *arg) +{ + struct scan *s = arg; + char id[RVT_ID_BYTES]; + if (is_folder || !stem_id(entry, id)) + return; + uint32_t at = s->count; + while (at && memcmp(s->out[at - 1].id, id, RVT_ID_BYTES) > 0) + at--; + if (at && !memcmp(s->out[at - 1].id, id, RVT_ID_BYTES)) + return; + if (s->count == s->capacity) { + s->overflow = 1; + if (at == s->capacity) + return; + s->count--; + } + memmove(s->out + at + 1, s->out + at, (s->count - at) * sizeof *s->out); + memcpy(s->out[at].id, id, RVT_ID_BYTES); + s->count++; +} + +uint32_t theme_scan(struct theme_entry *out, uint32_t capacity, int *overflow) +{ + struct scan s = {out, capacity, 0, 0}; + struct look look; + struct rv_file *file; + uint8_t header[RVT_HEADER_BYTES]; + api->content_list(self, FOLDER, collect, &s); + uint32_t kept = 0; + for (uint32_t i = 0; i < s.count; i++) { + if (!theme_file_open(out[i].id, &file)) + continue; + int ok = header_read(file, header) && header_look(header, out[i].id, &look); + api->file_close(self, file); + if (!ok) + continue; + memcpy(out[kept].id, look.id, RVT_ID_BYTES); + memcpy(out[kept].name, look.name, RVT_NAME_BYTES); + kept++; + } + *overflow = s.overflow; + return kept; +} + +enum theme_result theme_open(const char *id, int dark, struct rv_file **file, + struct look *look, struct pack_place *pack) +{ + uint8_t header[RVT_HEADER_BYTES]; + enum theme_result result = THEME_OK; + *file = NULL; + if (!id_valid(id) || !theme_file_open(id, file)) + return THEME_UNAVAILABLE; + if (header_read(*file, header) && header_look(header, id, look)) { + if (!(look->appearances & + (dark ? RVT_APPEARANCE_DARK : RVT_APPEARANCE_LIGHT))) { + dark = !dark; + result = THEME_NOT_IN_APPEARANCE; + } + look->dark = dark; + if (pack_place(header, dark, pack)) + return result; + } + api->file_close(self, *file); + *file = NULL; + return THEME_UNAVAILABLE; +} diff --git a/extensions/appearance/theme.h b/extensions/appearance/theme.h new file mode 100644 index 0000000..8ac4a43 --- /dev/null +++ b/extensions/appearance/theme.h @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Theme files a listener copies to /Reprise/Themes/: .rvt, named after + * the id inside, and the `classic` asset, a theme file with the Classic dark + * pack. This reads and checks their headers; the switch module reads the + * packs where the header places them. */ + +#ifndef THEME_H +#define THEME_H +#include "look.h" +#include "rv_api.h" +#include + +struct theme_entry { + char id[RVT_ID_BYTES]; + char name[RVT_NAME_BYTES]; +}; + +/* How many files in the folder are named like a theme, before any is opened. */ +uint32_t theme_count(void); +/* The readable themes sorted by id, at most `capacity`; *overflow says more + * were named like one. */ +uint32_t theme_scan(struct theme_entry *out, uint32_t capacity, int *overflow); + +enum theme_result { + THEME_OK, + THEME_UNAVAILABLE, /* no such file, or not a theme of that id */ + THEME_NOT_IN_APPEARANCE /* opened, but has only the other appearance */ +}; +/* Opens theme `id` and fills `look` from its header, with `look->dark` the + * appearance asked for, or the only one the theme has, and `pack` where that + * appearance's pack is. The file is the caller's to close unless the theme is + * unavailable. */ +enum theme_result theme_open(const char *id, int dark, struct rv_file **file, + struct look *look, struct pack_place *pack); +/* Opens the file a look's pack is in without reading it: a theme's by id, + * Classic dark's the `classic` asset. 0 for Classic light, which has none. */ +int look_file_open(const struct look *look, struct rv_file **file); +/* Checks the header of `file`, opened for `look` (its id when it has one), + * sets look->header_crc and places the pack of look->dark; 0 when the file is + * no theme of that id or lacks the pack. */ +int look_pack_place(struct rv_file *file, struct look *look, struct pack_place *pack); +/* Whether theme `id`'s file is still the one whose header checksum is `crc`. */ +int theme_file_matches(const char *id, uint32_t crc); + +#endif diff --git a/extensions/appearance/theme_picker.c b/extensions/appearance/theme_picker.c new file mode 100644 index 0000000..8179bb3 --- /dev/null +++ b/extensions/appearance/theme_picker.c @@ -0,0 +1,120 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Settings > Theme: a list of Classic and the themes in /Reprise/Themes/, + * scanned when the screen opens into a block sized by a count of the folder + * and freed when it closes. More than THEMES entries end in a row saying so. */ + +#include "theme_picker.h" +#include "ext.h" +#include "look.h" +#include "rv_libc.h" +#include "theme.h" +#include + +#define THEMES 64 +#define STRINGIFY_(n) #n +#define STRINGIFY(n) STRINGIFY_(n) + +static struct theme_entry *entries; /* the scanned themes while the screen is open */ +static uint32_t count; /* themes in the list */ +static int overflow; /* the folder held more themes than the list shows */ +static int scanned; /* the folder was read since the screen opened */ +static const char *problem; /* the picker's own trouble: no memory for the list */ + +/* The active theme stays listed when the sorted list is full: in order, in + * place of the last entry when it sorts after every other. */ +static void insert_active(uint32_t capacity) +{ + const struct look *active = look_active(); + uint32_t at = 0; + while (at < count && memcmp(entries[at].id, active->id, RVT_ID_BYTES) < 0) + at++; + if (at < count && !memcmp(entries[at].id, active->id, RVT_ID_BYTES)) + return; + if (count == capacity) { + if (at == count) + at--; + else + memmove(entries + at + 1, entries + at, (count - 1 - at) * sizeof *entries); + } else { + memmove(entries + at + 1, entries + at, (count - at) * sizeof *entries); + count++; + } + memcpy(entries[at].id, active->id, RVT_ID_BYTES); + memcpy(entries[at].name, active->name, RVT_NAME_BYTES); +} + +/* The list is scanned the first time the screen asks for it, which is while + * it is built, before `opened`. */ +static void scan(void) +{ + if (scanned) + return; + scanned = 1; + uint32_t capacity = theme_count(); + if (!capacity) + return; + if (capacity > THEMES) + capacity = THEMES; + entries = api->alloc(self, capacity * sizeof *entries); + if (!entries) { + problem = "Not enough memory"; + return; + } + count = theme_scan(entries, capacity, &overflow); + if (overflow && count && look_active()->id[0]) + insert_active(capacity); +} + +void theme_picker_closed(const struct rv_context *ctx) +{ + (void)ctx; + if (entries) + api->free(self, entries); + entries = NULL; + problem = NULL; + count = overflow = scanned = 0; +} + +static const char *trouble(void) +{ + return problem ? problem : look_problem(PANE_THEME); +} + +uint32_t theme_picker_rows(const struct rv_context *ctx) +{ + (void)ctx; + scan(); + return 1 + count + (overflow || trouble()); +} + +const char *theme_picker_row(const struct rv_context *ctx, uint32_t index, + const char **detail) +{ + (void)ctx; + *detail = NULL; + if (index == 0) + return "Classic"; + if (index <= count) + return entries[index - 1].name; + return trouble() ? trouble() : "Showing " STRINGIFY(THEMES) " themes"; +} + +int theme_picker_select(const struct rv_context *ctx, uint32_t index) +{ + (void)ctx; + if (index > count) + return 0; + look_select(index ? entries[index - 1].id : ""); + return 0; +} + +uint32_t theme_picker_initial(const struct rv_context *ctx) +{ + (void)ctx; + const struct look *active = look_active(); + for (uint32_t i = 0; i < count; i++) + if (!memcmp(entries[i].id, active->id, RVT_ID_BYTES)) + return i + 1; + return 0; +} diff --git a/extensions/appearance/theme_picker.h b/extensions/appearance/theme_picker.h new file mode 100644 index 0000000..4a7fd9d --- /dev/null +++ b/extensions/appearance/theme_picker.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef THEME_PICKER_H +#define THEME_PICKER_H +#include "rv_api.h" +#include "rv_ui.h" + +/* The Theme screen: Classic, then the themes in the folder. */ +uint32_t theme_picker_rows(const struct rv_context *ctx); +const char *theme_picker_row(const struct rv_context *ctx, uint32_t index, + const char **detail); +int theme_picker_select(const struct rv_context *ctx, uint32_t index); +uint32_t theme_picker_initial(const struct rv_context *ctx); +void theme_picker_closed(const struct rv_context *ctx); +#define THEME_PICKER_SCREEN \ + RV_SCREEN_DYNAMIC_LIST("theme", "Theme", theme_picker_rows, theme_picker_row, \ + .dynamic.select = theme_picker_select, \ + .dynamic.initial = theme_picker_initial, \ + .closed = theme_picker_closed, \ + .bitmap = RV_BITMAP("settings-theme")) + +#endif diff --git a/extensions/appearance/tint.c b/extensions/appearance/tint.c new file mode 100644 index 0000000..f9df187 --- /dev/null +++ b/extensions/appearance/tint.c @@ -0,0 +1,306 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "tint.h" +#include "catalog.h" +#include "osos-2.0.5.h" +#include "pixel.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "style.h" +#include + +/* One past the index of the bitmap whose palette holds the on-accent colour + * between the two halves of one blit; 0 when none. */ +static uint32_t highlighted; + +/* The label colours that contrast with the artwork, picked once per switch: + * the wells, the Search field, the contrast texts, then the calendar's + * active cell, inactive cell and page; alpha 0 where the stock colour stays. */ +enum { + CONTRAST_WELL, + CONTRAST_FIELD = WELLS, + CONTRAST_TEXT, + CONTRAST_CALENDAR = CONTRAST_TEXT + CATALOG_CONTRAST_TEXTS, + CONTRASTS = CONTRAST_CALENDAR + 3 +}; + +static uint8_t contrast[CONTRASTS][4]; + +typedef void (*pixel_fn)(uint8_t *bgra, const uint8_t *color); + +/* Palette entries and ARGB pixels are BGRA; coverage stays in the alpha byte. + * Every palette entry is visited; clear ARGB pixels keep their bytes so stock + * art still compares exactly. */ +static void each_entry(uint8_t *entry, uint32_t colors, pixel_fn fn, + const uint8_t *color) +{ + for (; colors--; entry += 4) + fn(entry, color); +} + +static void each_pixel(uint32_t index, pixel_fn fn, const uint8_t *color) +{ + uint32_t colors, width, height, stride; + uint8_t *entry = catalog_palette(index, &colors); + if (entry) { + each_entry(entry, colors, fn, color); + return; + } + uint8_t *row = catalog_argb(index, &width, &height, &stride); + if (!row) + return; + for (; height--; row += stride) + for (uint8_t *p = row, *end = row + width * 4; p < end; p += 4) + if (p[3]) + fn(p, color); +} + +static void paint(uint8_t *bgra, const uint8_t *color) +{ + bgra[0] = color[2]; + bgra[1] = color[1]; + bgra[2] = color[0]; +} + +enum { + GRAY_CHROMA = + 24, /* below this (max minus min channel) a pixel is grey: letters, gloss, shadows */ + FULL_CHROMA = 96, /* from here on a pixel is fully recoloured; between, blended */ + BRIGHTNESS_MAX = 255 * 256, + /* Stock accent art is shaded around the stock accent fill, (35, 108, 197). */ + STOCK_ACCENT_BRIGHTNESS = 54 * 35 + 183 * 108 + 19 * 197, +}; + +/* Moves `color` toward white or black by how much brighter or darker the stock + * pixel is than the stock blue, so that blue becomes `color` exactly and the + * art keeps its gradients. */ +static void colorize(uint8_t *bgra, const uint8_t *color) +{ + static const uint8_t white[4] = {255, 255, 255, 255}, black[4] = {0, 0, 0, 255}; + uint8_t stock[4] = {bgra[2], bgra[1], bgra[0], 255}, shaded[4]; + int high = stock[0], low = stock[0]; + for (unsigned i = 1; i < 3; i++) { + high = stock[i] > high ? stock[i] : high; + low = stock[i] < low ? stock[i] : low; + } + int chroma = high - low; + if (chroma < GRAY_CHROMA) + return; + int brightness = color_brightness(stock); + if (brightness >= STOCK_ACCENT_BRIGHTNESS) + color_mix(shaded, color, white, + divide((unsigned)(brightness - STOCK_ACCENT_BRIGHTNESS) * 255, + reciprocal(BRIGHTNESS_MAX - STOCK_ACCENT_BRIGHTNESS))); + else + color_mix(shaded, color, black, + divide((unsigned)(STOCK_ACCENT_BRIGHTNESS - brightness) * 255, + reciprocal(STOCK_ACCENT_BRIGHTNESS))); + unsigned weight = chroma >= FULL_CHROMA + ? 255 + : divide((unsigned)(chroma - GRAY_CHROMA) * 255, + reciprocal(FULL_CHROMA - GRAY_CHROMA)); + color_mix(shaded, stock, shaded, weight); + paint(bgra, shaded); +} + +int tint_bmap(void *bmap, uint32_t bytes, const uint8_t *color) +{ + uint8_t *b = bmap; + uint32_t format = le16(b + BMap_format), stride = le16(b + BMap_stride); + const uint8_t *bounds = b + BMap_bounds; + uint32_t height = le32(bounds + 8) - le32(bounds), + width = le32(bounds + 12) - le32(bounds + 4); + uint8_t *rows = b + BMap_payload; + if (bytes < BMap_payload || le32(b + BMap_payload_bytes) > bytes - BMap_payload) + return 0; + if (format == BMapFormat_Indexed8) { + uint32_t colors = le32(rows); + if (le32(b + BMap_payload_bytes) < 4 + colors * 4) + return 0; + each_entry(rows + 4, colors, paint, color); + return 1; + } + if (format != BMapFormat_BGRA8888 || le16(b + BMap_depth) != 32 || + width * 4 > stride || height * stride > le32(b + BMap_payload_bytes)) + return 0; + for (; height--; rows += stride) + for (uint8_t *p = rows, *end = rows + width * 4; p < end; p += 4) + if (p[3]) + paint(p, color); + return 1; +} + +/* The pixel data of a bitmap context's bitmap, or NULL. */ +static const uint8_t *context_pixels(const void *context) +{ + const uint8_t *bitmap = + context ? RV_FIELD(context, GraphicsContext_bitmap, const uint8_t *) : NULL; + return bitmap ? RV_FIELD(bitmap, Bitmap_pixels, const uint8_t *) : NULL; +} + +const uint8_t *tint_mask_color(const void *view) +{ + uint32_t index; + const uint8_t *pixels = + context_pixels(RV_FIELD(view, BitmapView_context, const void *)); + const uint8_t *color = NULL; + if (!pixels || !style_from_theme()) + return NULL; + if (!catalog_from_pixels(pixels, &index)) + color = style_color(RVT_ROLE_ICON_TINT); + else if (style_tinted(index)) + color = style_tint_color(index); + if (color && (RV_FIELD(view, View_flags, uint32_t) & ViewFlags_Highlighted)) + return style_color(RVT_ROLE_ON_ACCENT); + return color; +} + +/* A tinted paletted bitmap: its palette takes the on-accent colour until the + * end call. ARGB art would need every pixel rewritten twice per blit. A blit + * inside another's two halves leaves the first one's bitmap the highlighted + * one. */ +static void highlight(const void *context) +{ + uint32_t index, colors; + uint8_t *entry; + const uint8_t *pixels = context_pixels(context); + if (highlighted || !pixels || !catalog_from_pixels(pixels, &index) || + !style_tinted(index) || !(entry = catalog_palette(index, &colors))) + return; + each_entry(entry, colors, paint, style_color(RVT_ROLE_ON_ACCENT)); + highlighted = index + 1; +} + +void tint_highlight_begin(const void *view, const void *context) +{ + if (style_from_theme() && + (RV_FIELD(view, View_flags, uint32_t) & ViewFlags_Highlighted)) + highlight(context); +} + +void tint_marker_highlight_begin(const void *cell, const void *context) +{ + uint32_t index; + const uint8_t *art = + context_pixels(RV_FIELD(cell, CalendarDayCell_art, const void *)); + if (style_from_theme() && art && catalog_from_pixels(art, &index) && + index == catalog_calendar_cell(CALENDAR_HILITE)) + highlight(context); +} + +void tint_highlight_end(void) +{ + if (!highlighted) + return; + each_pixel(highlighted - 1, paint, style_tint_color(highlighted - 1)); + highlighted = 0; +} + +/* The text or background role, whichever differs more in brightness from `art`. */ +static const uint8_t *contrast_with(const uint8_t *art) +{ + const uint8_t *text = style_color(RVT_ROLE_TEXT), + *background = style_color(RVT_ROLE_BACKGROUND); + int reference = color_brightness(art); + int text_gap = color_brightness(text) - reference; + int background_gap = color_brightness(background) - reference; + if (text_gap < 0) + text_gap = -text_gap; + if (background_gap < 0) + background_gap = -background_gap; + return text_gap >= background_gap ? text : background; +} + +/* Entry `slot` of `contrast`: the role against the centre pixel of `index`, + * or nothing when the art is clear. */ +static void pick_contrast(unsigned slot, uint32_t index) +{ + uint8_t art[4]; + if (catalog_center_pixel(index, art)) + memcpy(contrast[slot], contrast_with(art), 4); + else + memset(contrast[slot], 0, 4); +} + +static void pick_contrasts(void) +{ + uint8_t art[4]; + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + for (unsigned well = 0; well < WELLS; well++) + pick_contrast(CONTRAST_WELL + well, catalog_well_center(well)); + pick_contrast(CONTRAST_FIELD, catalog_field_center()); + for (unsigned entry = 0; entry < CATALOG_CONTRAST_TEXTS; entry++) + pick_contrast(CONTRAST_TEXT + entry, catalog_contrast_art(entry)); + /* A clear cell counts as the page: the role that contrasts with the + * background, mixed halfway toward it for days of other months. */ + for (unsigned place = CALENDAR_ACTIVE; place <= CALENDAR_INACTIVE; place++) { + const uint8_t *behind = + catalog_center_pixel(catalog_calendar_cell(place), art) ? art : background; + const uint8_t *color = contrast_with(behind); + if (place == CALENDAR_ACTIVE) + memcpy(contrast[CONTRAST_CALENDAR + place], color, 4); + else + color_mix(contrast[CONTRAST_CALENDAR + place], color, behind, 128); + } + color_mix(contrast[CONTRAST_CALENDAR + 2], contrast_with(background), background, + 128); +} + +void tint_refresh(void) +{ + if (style_from_theme()) + for (uint32_t i = 0; i < RVT_CATALOG_MAX; i++) + if (style_tinted(i)) + each_pixel(i, paint, style_tint_color(i)); + pick_contrasts(); +} + +void tint_accent_art(const uint32_t *skip, uint32_t *touched) +{ + uint32_t index; + uint8_t role; + if (!style_accent_art_active()) + return; + for (uint32_t i = 0; catalog_accent_art(i, &index, &role); i++) { + if (index >= RVT_CATALOG_MAX || bit_test(skip, index)) + continue; + each_pixel(index, colorize, style_color((enum rvt_role)role)); + bit_set(touched, index); + } +} + +static const uint8_t *picked(unsigned slot) +{ + return style_from_theme() && contrast[slot][3] ? contrast[slot] : NULL; +} + +const uint8_t *tint_well_letter_color(unsigned well) +{ + /* Classic dark repaints the Now Playing well. */ + if (well == WELL_NOW_PLAYING && style_dark() && contrast[CONTRAST_WELL + well][3]) + return contrast[CONTRAST_WELL + well]; + return well < WELLS ? picked(CONTRAST_WELL + well) : NULL; +} + +const uint8_t *tint_field_text_color(void) +{ + return picked(CONTRAST_FIELD); +} + +const uint8_t *tint_contrast_text_color(uint32_t view) +{ + int entry = style_from_theme() ? catalog_contrast_text(view) : -1; + return entry < 0 ? NULL : picked(CONTRAST_TEXT + (unsigned)entry); +} + +const uint8_t *tint_calendar_text_color(unsigned place, uint8_t out[4]) +{ + unsigned slot = place == CALENDAR_HEADER ? 2 : place; + if (place == CALENDAR_HILITE || place > CALENDAR_HEADER || + !picked(CONTRAST_CALENDAR + slot)) + return NULL; + if (place == CALENDAR_ACTIVE) + return contrast[CONTRAST_CALENDAR]; + memcpy(out, contrast[CONTRAST_CALENDAR + slot], 4); + return out; +} diff --git a/extensions/appearance/tint.h b/extensions/appearance/tint.h new file mode 100644 index 0000000..6ff1c40 --- /dev/null +++ b/extensions/appearance/tint.h @@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Colouring bitmaps in place and picking label colours against artwork. */ + +#ifndef TINT_H +#define TINT_H +#include + +/* The colour a bitmap view draws its mask in: its tint colour when the bitmap + * is a tinted catalog bitmap, the icon tint role when it is no catalog bitmap + * at all (an extension's menu icon) under a theme, the on-accent colour while + * the view is highlighted, NULL to keep the stock colour. */ +const uint8_t *tint_mask_color(const void *view); +/* Around one blit of a bitmap context by a view, or of a calendar day cell's + * marker: a tinted paletted asset in a highlighted view, or on the selected + * day, draws with the on-accent colour, put back by the end call. Tinted ARGB + * art keeps its tint while highlighted. */ +void tint_highlight_begin(const void *view, const void *context); +void tint_marker_highlight_begin(const void *cell, const void *context); +void tint_highlight_end(void); +/* Paints a decoded extension picture, a whole BMap of `bytes`, in `color`: + * the entries of an Indexed8 palette or the covered pixels of BGRA8888 rows, + * keeping their alpha. 0 for any other format. */ +int tint_bmap(void *bmap, uint32_t bytes, const uint8_t *color); +/* Rewrites the palettes of tinted paletted bitmaps and the pixels of tinted + * ARGB bitmaps with their tint colour, and picks the label colours that + * contrast with the artwork; after a switch or accent change, once the pack's + * records are applied. */ +void tint_refresh(void); +/* Tints the stock accent artwork with its role, skipping bitmaps set in + * `skip` (replaced by the pack), and sets each one it touched in `touched`. + * Expects stock pixels. */ +void tint_accent_art(const uint32_t *skip, uint32_t *touched); +/* The colour for labels on an option bar well (catalog.h WELL_*): the text or + * background role, whichever contrasts more with the well's centre art; NULL + * keeps the stock colour (no pack, or clear art). The Now Playing well has one + * under Dark without a pack too. */ +const uint8_t *tint_well_letter_color(unsigned well); +/* The same for the text typed into the Search field. */ +const uint8_t *tint_field_text_color(void); +/* The same for a stock label drawn in a fixed colour over art, by view id. */ +const uint8_t *tint_contrast_text_color(uint32_t view); +/* Calendar labels (catalog.h calendar_place): a day of the shown month on the + * active cell, of another month on the inactive cell (mixed halfway toward + * it), a weekday name on the page; `out` holds a mixed result. NULL keeps the + * stock colour. */ +const uint8_t *tint_calendar_text_color(unsigned place, uint8_t out[4]); + +#endif diff --git a/extensions/appearance/tools/catalog_inc.py b/extensions/appearance/tools/catalog_inc.py new file mode 100755 index 0000000..e453a45 --- /dev/null +++ b/extensions/appearance/tools/catalog_inc.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write catalog.inc from the Apple bitmap catalog, themes/rvt/data/osos-2.0.5.json: +the bank's base and file offset, each bitmap's offset in the bank +with its padding in the low two bits, the low 16 bits of each stock checksum, +the catalog fingerprint, and the indices of the assets the extension treats +specially. + + python3 tools/catalog_inc.py ../../themes/rvt/data/osos-2.0.5.json build/catalog.inc + python3 tools/catalog_inc.py ../../themes/rvt/data/osos-2.0.5.json --check build/classic.rvt + +The second form checks that a theme file carries the catalog's fingerprint. +""" + +import json +import sys +from pathlib import Path + +# Stock blue artwork and the role it is recoloured with. Blue that marks content +# (capacity legends, playlist kinds) is not listed. +ACCENT_ART = { + "RVT_ROLE_SELECTION": ( + "OptionBar_White_Thumb_LeftCap_Image", + "OptionBar_White_Thumb_Center_Image", + "OptionBar_White_Thumb_RightCap_Image", + "OptionBar_Black_Thumb_LeftCap_Image", + "OptionBar_Black_Thumb_Center_Image", + "OptionBar_Black_Thumb_RightCap_Image", + "System_ActiveButtonLeftCap_Image", + "System_ActiveButtonRightCap_Image", + "System_ActiveButtonFill_Image", + "DateTimePicker_Selection", + "Alarms_Timer_Time_Panel_Focus", + "Settings_DateTime_Capsule_Hilite", + "Calendar_Hilite_Cell", + "LockScreen_TumblerFocus_Image", + "Settings_MainMenu_CheckmarkWhite_Image", + ), + "RVT_ROLE_ACCENT_FILL": ( + "NowPlaying_ProgressBar_Active_Fill_Image", + "NowPlaying_ProgressBar_Scrub_Image", + "Genius_Slider_Endcap_Image", + "Genius_Slider_Fill_Image", + "Podcasts_new_item_Image", + "Podcasts_new_item_video_Image", + "NowPlaying_Blue_Dot_Image", + "NowPlaying_Blue_Star_Image", + "NowPlaying_Large_Blue_Star_Image", + "StatusBarWhite_PlayStatus_Image", + "NowPlaying_White_Play_Image", + "NowPlaying_White_Pause_Image", + "NowPlaying_White_FF_Image", + "NowPlaying_White_Rew_Image", + "Radio_Preset_Image", + "Radio_Signal_Indicator_Light_Image", + ), +} +RECOLORABLE_FORMATS = (0x64, 0x65, 0x1888) + +# Stock labels drawn in a fixed colour over art a theme may replace, by the +# first view of a run of consecutive ids, the run's length and the asset behind +# them: they take the text or background role, whichever contrasts more with +# that art. +CONTRAST_TEXT = ( + ("RES_NowPlaying_StatusBar_Text_View", 1, "NowPlaying_StatusBar_Image"), + ("RES_LockScreen_TumblerDigit0_View", 4, "LockScreen_TumblerBgnd_Image"), + ("RES_VolumeLimitLockScreen_TumblerDigit0_View", 4, "LockScreen_TumblerBgnd_Image"), + ("RES_DateTimePicker_Value1", 3, "DateTimePicker_Well"), + ("RES_CoverFlow_Backside_AlbumTitle_Text", 2, "CoverFlow_Backside_Top_Image"), +) +WELLS = ( + "OptionBar_White_Well_Center_Image", + "OptionBar_Black_Well_Center_Image", + "OptionBar_NowPlaying_Well_Center_Image", +) +FIELD = "System_Input_Field_Middle_Image" +CELLS = ("Calendar_Active_Cell", "Calendar_Inactive_Cell", "Calendar_Hilite_Cell") +FINGERPRINT_AT = 8 +FINGERPRINT_BYTES = 8 + + +def check(catalog, rvt): + stored = bytes.fromhex(catalog["fingerprint"]) + found = rvt.read_bytes()[FINGERPRINT_AT : FINGERPRINT_AT + FINGERPRINT_BYTES] + if found != stored: + raise SystemExit(f"{rvt} was compiled against another catalog") + + +def write(catalog, out): + bitmaps = sorted(catalog["bitmaps"], key=lambda b: b["address"]) + index = {b["name"]: i for i, b in enumerate(bitmaps)} + if len(index) != len(bitmaps): + raise SystemExit("catalog names are not unique") + base = bitmaps[0]["address"] + if base % 4 or bitmaps[0]["offset"] % 4: + raise SystemExit("the bank does not start on a word") + at = base + offsets = [] + for b in bitmaps: + if b["address"] != at: + raise SystemExit(f"{b['name']} does not follow the previous bitmap") + padding = -b["bytes"] & 3 + offsets.append(at - base | padding) + at += b["bytes"] + padding + offsets.append(at - base) + for name in ACCENT_ART["RVT_ROLE_SELECTION"] + ACCENT_ART["RVT_ROLE_ACCENT_FILL"]: + if bitmaps[index[name]]["format"] not in RECOLORABLE_FORMATS: + raise SystemExit(f"{name} is not paletted or ARGB") + digest = bytes.fromhex(catalog["fingerprint"]) + lines = [ + "/* Generated by tools/catalog_inc.py from osos-2.0.5.json; do not edit. */", + f"#define CATALOG_COUNT {len(bitmaps)}", + f"#define CATALOG_BASE {base:#x}u /* first bitmap in RAM */", + f"#define CATALOG_FILE_OFFSET {bitmaps[0]['offset']:#x}u" + " /* the same in the firmware file */", + f"#define CATALOG_BANK_BYTES {at - base}u", + "static const uint8_t fingerprint[RVT_FINGERPRINT_BYTES] = {" + + ", ".join(f"{b:#04x}" for b in digest) + + "};", + "static const uint32_t catalog_offsets[CATALOG_COUNT + 1] = {", + *(f" {o}u," for o in offsets), + "};", + "static const uint16_t catalog_crcs[CATALOG_COUNT] = {", + *(f" {b['crc32'] & 0xFFFF:#06x}," for b in bitmaps), + "};", + "static const uint16_t well_centers[3] = {" + + ", ".join(str(index[n]) for n in WELLS) + + "};", + f"static const uint16_t field_center = {index[FIELD]};", + "static const uint16_t calendar_cells[3] = {" + + ", ".join(str(index[n]) for n in CELLS) + + "};", + "static const struct contrast_text contrast_text[] = {", + *( + f" {{{first}, {count}, {index[name]}}}," + for first, count, name in CONTRAST_TEXT + ), + "};", + "static const struct accent_art accent_art[] = {", + *( + f" {{{index[name]}, {role}}}," + for role, names in ACCENT_ART.items() + for name in names + ), + "};", + "", + ] + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text("\n".join(lines)) + + +def main(): + catalog = json.loads(Path(sys.argv[1]).read_text()) + if sys.argv[2] == "--check": + check(catalog, Path(sys.argv[3])) + else: + write(catalog, Path(sys.argv[2])) + + +if __name__ == "__main__": + main() diff --git a/themes/tests/test_style.py b/themes/tests/test_style.py index 01d2558..69fdafd 100644 --- a/themes/tests/test_style.py +++ b/themes/tests/test_style.py @@ -81,8 +81,6 @@ def test_classic_dark_and_accent_defaults(self): ) def test_builtin_accents_equal_the_extension(self): - if not STYLE_C.is_file(): - self.skipTest("the Appearance extension is not in the tree") source = STYLE_C.read_text() table = re.search( r"accents\[RVT_ACCENTS\]\[2\]\[2\]\[4\] = \{(.*?)\};", source, re.S From 5274bd839c6e1d6908bb425727792f6d055d7f3d Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 14:36:48 +0000 Subject: [PATCH 15/20] docs: name the firmware file /Reprise/Firmware/reprise.bin RepriseOS moves the firmware there (repriseos#99). Appearance reads the stock artwork from it; the rvt tool accepts it as --firmware. --- extensions/appearance/README.md | 2 +- extensions/appearance/stock.h | 12 ++++++------ themes/docs/authoring.md | 2 +- themes/docs/toolchain.md | 2 +- themes/rvt/cli.py | 4 ++-- themes/rvt/firmware.py | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/extensions/appearance/README.md b/extensions/appearance/README.md index 8cef0b5..da5504f 100644 --- a/extensions/appearance/README.md +++ b/extensions/appearance/README.md @@ -18,7 +18,7 @@ Themes are `.rvt` files in `/Reprise/Themes/`, built with the compiler in th A theme may have a light appearance, a dark one or both. With only one, Dark Mode shows that one, its row value says which, and the pane says "Theme only supports dark mode" or "Theme only supports light mode". If the chosen theme's file is missing, Classic shows and Theme says "Theme unavailable"; the choice comes back with the file. -A theme that cannot be read leaves the look unchanged. One that fails part way through is undone to the stock light look, and the row the action came from says so. If the stock artwork cannot be restored from `/osos-cfw.bin`, the Appearance row disappears until the next boot. Presses queued during a switch cannot reverse it. Turning the extension off restores the stock artwork. +A theme that cannot be read leaves the look unchanged. One that fails part way through is undone to the stock light look, and the row the action came from says so. If the stock artwork cannot be restored from `/Reprise/Firmware/reprise.bin`, the Appearance row disappears until the next boot. Presses queued during a switch cannot reverse it. Turning the extension off restores the stock artwork. ## Auto diff --git a/extensions/appearance/stock.h b/extensions/appearance/stock.h index a7baf5c..f15e852 100644 --- a/extensions/appearance/stock.h +++ b/extensions/appearance/stock.h @@ -1,11 +1,11 @@ /* SPDX-License-Identifier: GPL-3.0-only */ -/* Stock artwork comes back from the firmware file: /osos-cfw.bin - * is Apple's image with the core appended, so every bitmap lies there at its - * catalog offset, unchanged. The file must be the image the iPod booted: it - * is checked once per session before a switch writes anything, so recovery - * is possible afterwards, and again after USB disk mode, which may have - * replaced it. */ +/* Stock artwork comes back from the firmware file, + * /Reprise/Firmware/reprise.bin: Apple's image with the core appended, so + * every bitmap lies there at its catalog offset, unchanged. The file must be + * the image the iPod booted: it is checked once per session before a switch + * writes anything, so recovery is possible afterwards, and again after USB + * disk mode, which may have replaced it. */ #ifndef STOCK_H #define STOCK_H diff --git a/themes/docs/authoring.md b/themes/docs/authoring.md index ea515c6..9bba54e 100644 --- a/themes/docs/authoring.md +++ b/themes/docs/authoring.md @@ -10,7 +10,7 @@ A theme is a folder compiled into one `.rvt` file. It sets colours, a palette pe 4. `python3 -m rvt compile mytheme` writes `dist/mytheme/mytheme.rvt` and `report.json`. `--strict` turns warnings into errors. 5. Copy `mytheme.rvt` to `/Reprise/Themes/` on the iPod. It appears under Settings > Appearance > Theme. -The iPod derives the theme's art from `/osos-cfw.bin`, so that file must be the build that is running; a mismatch leaves the look unchanged and the Theme row reports it. +The iPod derives the theme's art from `/Reprise/Firmware/reprise.bin`, so that file must be the build that is running; a mismatch leaves the look unchanged and the Theme row reports it. ``` mytheme/ diff --git a/themes/docs/toolchain.md b/themes/docs/toolchain.md index 093f627..685ccf7 100644 --- a/themes/docs/toolchain.md +++ b/themes/docs/toolchain.md @@ -14,7 +14,7 @@ | `rvt catalog list --extensions [--group ID] [--format FMT]` | One line per extension bitmap: id, asset, size, format, palette entries, menu or bitmap | | `rvt catalog show ` | Every catalog field of one Apple bitmap, by name or hex id | | `rvt catalog show /` | Every catalog field of one extension bitmap, and its two hashes | -| `rvt preview --firmware FILE` | Renders every derived bitmap of a theme from a decrypted `osos.bin` or the booted `osos-cfw.bin` to `dist//derived/` | +| `rvt preview --firmware FILE` | Renders every derived bitmap of a theme from a decrypted `osos.bin` or the booted `reprise.bin` to `dist//derived/` | | `rvt recolor --firmware FILE` | Turns `//apple/.png` into a `recolor` rule file when the PNG is a pure recolour of the stock bitmap | | Option | On | Does | diff --git a/themes/rvt/cli.py b/themes/rvt/cli.py index 10ff99a..a936f53 100644 --- a/themes/rvt/cli.py +++ b/themes/rvt/cli.py @@ -95,7 +95,7 @@ def theme_options(command): ) theme_options(preview) preview.add_argument( - "--firmware", type=Path, required=True, help="osos.bin or osos-cfw.bin" + "--firmware", type=Path, required=True, help="osos.bin or reprise.bin" ) preview.add_argument("--out", type=Path, default=Path("dist")) @@ -104,7 +104,7 @@ def theme_options(command): ) recolor.add_argument("png", type=Path, help="//apple/.png") recolor.add_argument( - "--firmware", type=Path, required=True, help="osos.bin or osos-cfw.bin" + "--firmware", type=Path, required=True, help="osos.bin or reprise.bin" ) catalog_option(recolor) diff --git a/themes/rvt/firmware.py b/themes/rvt/firmware.py index 3fbc8f7..521d80b 100644 --- a/themes/rvt/firmware.py +++ b/themes/rvt/firmware.py @@ -11,7 +11,7 @@ class Firmware: - """Stock bitmaps read at the catalog's offsets; osos.bin or osos-cfw.bin.""" + """Stock bitmaps read at the catalog's offsets; osos.bin or reprise.bin.""" def __init__(self, path, catalog): self.data = path.read_bytes() From 2762d64f6bd0f89f9585fcba9608d3db779e332f Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 14:52:33 +0000 Subject: [PATCH 16/20] fix: title-case the schedule's no-zone caption --- extensions/appearance/README.md | 2 +- extensions/appearance/tests/contracts.c | 4 ++-- extensions/night-shift/test.c | 4 ++-- extensions/shared/schedule.c | 2 +- extensions/shared/schedule.h | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/extensions/appearance/README.md b/extensions/appearance/README.md index da5504f..0486282 100644 --- a/extensions/appearance/README.md +++ b/extensions/appearance/README.md @@ -22,7 +22,7 @@ A theme that cannot be read leaves the look unchanged. One that fails part way t ## Auto -Dark Mode's Auto follows sunset and sunrise in the city set under Settings > Date & Time > Time Zone, by the iPod's clock, checked once a minute: dark from the sunset minute to the sunrise minute. Without a time zone, Auto is light and says "Set a time zone". +Dark Mode's Auto follows sunset and sunrise in the city set under Settings > Date & Time > Time Zone, by the iPod's clock, checked once a minute: dark from the sunset minute to the sunrise minute. Without a time zone, Auto is light and says "Set a Time Zone". A theme with one appearance turns Dark Mode's Auto into the value it shows, as it does On and Off. diff --git a/extensions/appearance/tests/contracts.c b/extensions/appearance/tests/contracts.c index a829a26..14f6588 100644 --- a/extensions/appearance/tests/contracts.c +++ b/extensions/appearance/tests/contracts.c @@ -2724,7 +2724,7 @@ static void schedule_contracts(void) /* Without a known zone: day, and the caption asks for one. */ schedule_read(&s); assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); - assert(!strcmp(schedule_caption(), "Set a time zone")); + assert(!strcmp(schedule_caption(), "Set a Time Zone")); /* Berlin, 21 June: sunset 21:33 CEST, sunrise 04:43 (NOAA, within 3 minutes). */ put16(host_zones + 90 * TimeZone_bytes + TimeZone_zone_id, 0x1234); memcpy(host_app + App_browser, &(uint8_t *){host_browser}, sizeof(void *)); @@ -2763,7 +2763,7 @@ static void schedule_contracts(void) put16(host_preferences + PreferencesFile_time_zone_id, 0x7777); schedule_read(&s); assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); - assert(!strcmp(schedule_caption(), "Set a time zone")); + assert(!strcmp(schedule_caption(), "Set a Time Zone")); put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); clock_now[DateTime_hour] = 23, clock_now[DateTime_minute] = 0; } diff --git a/extensions/night-shift/test.c b/extensions/night-shift/test.c index 9f828c8..c21ef1c 100644 --- a/extensions/night-shift/test.c +++ b/extensions/night-shift/test.c @@ -146,7 +146,7 @@ static void night_shift_contracts(void) /* Auto without a known zone stays neutral and says so. */ night_shift_set(NIGHT_SHIFT_AUTO); assert(gamma_loads == loads + 2); - assert(!strcmp(night_shift_caption(), "Set a time zone")); + assert(!strcmp(night_shift_caption(), "Set a Time Zone")); /* Berlin, 21 June, 23:00 CEST: an hour and a half after sunset. */ put16(host_zones + 90 * TimeZone_bytes + TimeZone_zone_id, 0x1234); memcpy(host_app + App_browser, &(uint8_t *){host_browser}, sizeof(void *)); @@ -210,7 +210,7 @@ static void schedule_contracts(void) put16(host_preferences + PreferencesFile_time_zone_id, 0x7777); schedule_read(&s); assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); - assert(!strcmp(schedule_caption(), "Set a time zone")); + assert(!strcmp(schedule_caption(), "Set a Time Zone")); put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); clock_now[DateTime_hour] = 23, clock_now[DateTime_minute] = 0; } diff --git a/extensions/shared/schedule.c b/extensions/shared/schedule.c index 1d96045..29edb7f 100644 --- a/extensions/shared/schedule.c +++ b/extensions/shared/schedule.c @@ -74,5 +74,5 @@ const char *schedule_caption(void) { struct schedule s; schedule_read(&s); - return s.state == SCHEDULE_NO_ZONE ? "Set a time zone" : "Sunset to Sunrise"; + return s.state == SCHEDULE_NO_ZONE ? "Set a Time Zone" : "Sunset to Sunrise"; } diff --git a/extensions/shared/schedule.h b/extensions/shared/schedule.h index c82931d..570b70c 100644 --- a/extensions/shared/schedule.h +++ b/extensions/shared/schedule.h @@ -26,7 +26,7 @@ void schedule_read(struct schedule *out); int schedule_night(const struct schedule *s); /* `value` folded into 0..1439. */ int schedule_minute(int value); -/* "Sunset to Sunrise", or "Set a time zone" without a known zone. */ +/* "Sunset to Sunrise", or "Set a Time Zone" without a known zone. */ const char *schedule_caption(void); #endif From 8c47631aaa2f32b26c5ca9622cd66bee2003b7eb Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Sat, 28 Nov 2026 01:34:00 +0000 Subject: [PATCH 17/20] fix: match copied pane views by stock id Appearance picks views by their stock id. The day number of a 130 x 128 pane is a copy of the Calendars pane's and missed the native text rule, so it turned light grey on the picture in Dark Mode. view_id passes the id through ui_stock_view when the core has it (API 1.91). --- extensions/appearance/render.c | 9 ++++++++- extensions/appearance/tests/contracts.c | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/extensions/appearance/render.c b/extensions/appearance/render.c index ac0b8a7..dea34e0 100644 --- a/extensions/appearance/render.c +++ b/extensions/appearance/render.c @@ -36,9 +36,16 @@ enum { /* Which of a bar view's own label colours a draw passes. */ enum bar_slot { BAR_OTHER, BAR_LABEL, BAR_SELECTED }; +/* The stock id of view id `id`: a picture pane copied from an Apple template + * gives its views new ids. */ +static uint32_t stock_id(uint32_t id) +{ + return RV_HAS(api, ui_stock_view) ? api->ui_stock_view(id) : id; +} + static uint32_t view_id(uint32_t view) { - return RV_FIELD(view, View_id, uint32_t); + return stock_id(RV_FIELD(view, View_id, uint32_t)); } static int same_rgb(const uint8_t *color, const uint8_t *other) diff --git a/extensions/appearance/tests/contracts.c b/extensions/appearance/tests/contracts.c index 14f6588..66a5dd9 100644 --- a/extensions/appearance/tests/contracts.c +++ b/extensions/appearance/tests/contracts.c @@ -2052,6 +2052,30 @@ static void classic_mapping(void) style_set_accent(ACCENT_DEFAULT); } +enum { COPIED_DAY = 0x0dad8001 }; + +static uint32_t ui_stock_view(uint32_t view) +{ + return view == COPIED_DAY ? RES_Alarms_PickDate_Preivew_NumericDay : view; +} + +/* The day number of a copied Calendars pane keeps its stock black in dark + * mode, as the stock pane's does; a core without ui_stock_view leaves the id. */ +static void copied_view_text(void) +{ + style_set_dark(1); + expect_text(black, RES_Alarms_PickDate_Preivew_NumericDay, 0, 0, 0); + assert(stock_id(COPIED_DAY) == COPIED_DAY); + fake.size = sizeof fake; + fake.ui_stock_view = ui_stock_view; + assert(stock_id(COPIED_DAY) == RES_Alarms_PickDate_Preivew_NumericDay); + assert(stock_id(ORDINARY_VIEW) == ORDINARY_VIEW); + expect_text(black, stock_id(COPIED_DAY), 0, 0, 0); + fake.size = 0; + fake.ui_stock_view = NULL; + style_set_dark(0); +} + static void accent_mapping(void) { /* Purple recolours accents but leaves Classic light surfaces and text alone. */ @@ -2827,6 +2851,7 @@ int main(void) scan_contracts(); puts("PASS: theme folder"); classic_mapping(); + copied_view_text(); accent_mapping(); theme_mapping(); bar_mapping(); From fce1f448fe2d1727d60e1b1bca6bd648bcfea1b4 Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 17:08:14 +0000 Subject: [PATCH 18/20] feat: add Sound Menu Settings > Sound, where Volume Limit was: a list that takes Apple's Volume Limit, EQ and Sound Check rows out of Settings and hosts the audio extensions' rows after them. The moved rows keep Apple's titles, values, screens and panes, and Volume Limit and EQ return to the list. Without the extension every row is back in Settings. Needs a core with moved stock rows (API 1.89). From RevolaOS extensions a32d616f5a06. --- Makefile | 4 +- NOTICE | 6 ++- README.md | 1 + catalog/sources.toml | 5 +++ extensions/sound-menu/Makefile | 3 ++ extensions/sound-menu/README.md | 11 +++++ .../sound-menu/assets/LICENSE.cupertino-icons | 20 +++++++++ extensions/sound-menu/assets/render.py | 32 +++++++++++++ .../sound-menu/assets/settings-sound.png | Bin 0 -> 1239 bytes extensions/sound-menu/listing.toml | 5 +++ extensions/sound-menu/main.c | 42 ++++++++++++++++++ extensions/sound-menu/manifest.toml | 18 ++++++++ extensions/sound-menu/screenshots/sound.png | Bin 0 -> 31251 bytes themes/docs/extension-bitmaps.md | 1 + themes/rvt/data/extensions.json | 1 + 15 files changed, 145 insertions(+), 4 deletions(-) create mode 100644 extensions/sound-menu/Makefile create mode 100644 extensions/sound-menu/README.md create mode 100644 extensions/sound-menu/assets/LICENSE.cupertino-icons create mode 100644 extensions/sound-menu/assets/render.py create mode 100644 extensions/sound-menu/assets/settings-sound.png create mode 100644 extensions/sound-menu/listing.toml create mode 100644 extensions/sound-menu/main.c create mode 100644 extensions/sound-menu/manifest.toml create mode 100644 extensions/sound-menu/screenshots/sound.png diff --git a/Makefile b/Makefile index 13d3858..e1eeccc 100644 --- a/Makefile +++ b/Makefile @@ -2,8 +2,8 @@ SDK ?= ../osos-lab/rvx-sdk OUT ?= build extensions := album-artists appearance balance clicker-modes crossfeed dsp equalizer \ - eu-volume-limit file-info homebrew iap-auth-bypass night-shift playback-log \ - playback-queue + eu-volume-limit file-info homebrew iap-auth-bypass night-shift \ + playback-log playback-queue sound-menu .PHONY: all $(extensions) all: $(extensions) $(OUT)/assets.json diff --git a/NOTICE b/NOTICE index d463540..ae35110 100644 --- a/NOTICE +++ b/NOTICE @@ -24,8 +24,10 @@ a32d616f5a06, and derives from the RepriseOS core's Dark Mode by lgreitis and Alex Ball; its Settings icons are Cupertino Icons glyphs (MIT), see the LICENSE.cupertino-icons beside them, and the Classic theme it carries is built by the rvt compiler in themes/ (see themes/NOTICE). Night Shift's hosted row and -choice screen are from RevolaOS extensions, revision d04fa7d. The original -RevolaOS notice follows. +choice screen are from RevolaOS extensions, revision d04fa7d. Sound Menu is from +RevolaOS extensions, revision a32d616f5a06; its icon is a Cupertino Icons glyph +(MIT), see the LICENSE.cupertino-icons beside it. 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 3148bb0..d38f27e 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ This repository hosts the source for these RepriseOS extensions and accepts prop - [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/). +- [Sound Menu](extensions/sound-menu/) adds Settings > Sound with Apple's Volume Limit, EQ and Sound Check rows and the audio extensions' rows after them. - [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. diff --git a/catalog/sources.toml b/catalog/sources.toml index ae6140d..4272bd4 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -67,3 +67,8 @@ tag_prefix = "eu-volume-limit/v" repo = "RepriseOS/repriseos-extensions" path = "extensions/homebrew" tag_prefix = "homebrew/v" + +[sound-menu] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/sound-menu" +tag_prefix = "sound-menu/v" diff --git a/extensions/sound-menu/Makefile b/extensions/sound-menu/Makefile new file mode 100644 index 0000000..cb973a7 --- /dev/null +++ b/extensions/sound-menu/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c +include $(SDK)/rv.mk diff --git a/extensions/sound-menu/README.md b/extensions/sound-menu/README.md new file mode 100644 index 0000000..fe80e33 --- /dev/null +++ b/extensions/sound-menu/README.md @@ -0,0 +1,11 @@ +# Sound Menu + +Adds Settings > Sound, a menu that gathers the sound settings. Apple's Volume Limit, EQ and Sound Check rows move into it from Settings, and the audio extensions' rows that sit after them in Settings sit after them in Sound too. The Sound row sits where Volume Limit was. With the extension off, every row is back in its place in Settings. + +The moved rows stay Apple's: the same titles, values, screens and preview pane. + +| | | +|---|---| +| Default | off | +| Memory | about 6 KB once opened: the list, its bindings and clones of the three rows' Settings layouts | +| Settings | none | diff --git a/extensions/sound-menu/assets/LICENSE.cupertino-icons b/extensions/sound-menu/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/sound-menu/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/sound-menu/assets/render.py b/extensions/sound-menu/assets/render.py new file mode 100644 index 0000000..b2663d1 --- /dev/null +++ b/extensions/sound-menu/assets/render.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render settings-sound.png, the Settings pane icon: Cupertino Icons' +waveform fitted into the art box of a 78 x 121 gray coverage mask in the +style of the stock Settings icons, lit from the top and mirrored in a fading +reflection below. Drawing uses ImageMagick's `magick`; the font +(CupertinoIcons.ttf from the Flutter `cupertino_icons` package, MIT, see +LICENSE.cupertino-icons) is not in the repository. + + python3 assets/render.py --font CupertinoIcons.ttf + python3 assets/render.py --font CupertinoIcons.ttf --check +""" + +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import ART_BOTTOM, ART_TOP, glyph, icon, main + +OUT = HERE / "settings-sound.png" +# The glyph's code point in the font, and its reach: the longer side of the +# box it is fitted into, centred on the art box. +WAVEFORM, REACH = 0xF894, 52 + + +def render(out, work, font): + icon(out, work, glyph(work, font, WAVEFORM, REACH), ART_TOP, ART_BOTTOM) + + +if __name__ == "__main__": + main(__doc__, {OUT: render}, font=True) diff --git a/extensions/sound-menu/assets/settings-sound.png b/extensions/sound-menu/assets/settings-sound.png new file mode 100644 index 0000000000000000000000000000000000000000..e9d54fef49bfcbea5e1bc28751e799fd14618826 GIT binary patch literal 1239 zcmeAS@N?(olHy`uVBq!ia0vp^en4Ew0VEhU?en+-q!f}pf_xbms?-=58d?|_egTCV zUNA6}8Za=tN?>5Hn!&&zUNC1@pbb!hDaqU2g@IvJud)%4$6n&;>&pI$TS{14{#yD^ zX`qm5iEBhjN@7W>RdP`(kYX@0Ff!9MG}JXR3o*2`GBLI?Hq?!>9pu#s}kWe>)t$>ad6H;nN;oL1*>~|{?5uzb1VP!@x}Y<_sv!AX<~1_ef_fH zV)aXgb5$?6Qd)SpmT8Bm%&{)pXPtt`4JAGF!gtilF1I_EX>{5{FBSnJBpaNIUecK1o?9e=*^9!Oa>QCX;D(OdNe@qd+N z=gwhDshW96%Rb_qGyBX*UrLNbC-p5n^6t^qzvb~l7dOtn)OxqPoG1OA%PHCU3tsZ> z;C4-s&`K?rPu93~^Y`y}uS+F;m3xHOs?R;j|NLb5y1zws zR%yTGR9>W<39+)i%+jT(?kpm(JM46a^YvH0uQayy2%iva=?T)fl)1IXa^L1p4~rZt zPFtAGZ7JY#_3ixsl6&grGuIZcU)E%s%9GT)dEc(t%27AACMzdpY*!H4@@Ur4Qj5EX zH``p^lK<|=1yjdLZOxdxTwi%5_05kISFbBiwv0M=azpyBFMf=-{nuYvCUl}wO-)}m zE!}jn(sF;6BYydX%lvI)oh;8k*?025GN+k7eN&kd8D`Yk{&_oj(j<{{tNg;}PnY^u zI%Bh={@Gtz#kuUSeyx63puT)@xXFh~&xP56%e{`CS9h&GI^|>&&w^bUcMs1kcXhI~ zyyJX5MZHU^J7%ZxMC~%~(_y8G*1M*D>em&Y zd2{B}V|S8j@{3RFZog9mCahzO7g_PlXE>jKWNLRztr&;Kk!9ZdivI6^vPZhn%e}V$ z^65&m1ye7UWfy9%D1T%d>E3$w+?R8czTfFORKIIMKzrhI^HnNM$y~(xJbc+vW6QklU`Uv=RLRY{ZYht&MR{B>Xt`t zOJWwbSZRhhmMn9eW!~(+Zga~my{Ml*UfL*|8O_IdF6-q##y Sound, a list that takes Apple's Volume Limit, EQ + * and Sound Check rows out of Settings and hosts the audio rows other + * extensions anchor on them. */ + +#include "rv_api.h" +#include "rv_menus.h" +#include "rv_ui.h" + +static const struct rv_row rows[] = { + RV_ROW_STOCK(RV_SETTINGS_VOLUME_LIMIT, .id = "volume-limit"), + RV_ROW_STOCK(RV_SETTINGS_EQ, .id = "eq"), + RV_ROW_STOCK(RV_SETTINGS_SOUND_CHECK, .id = "sound-check"), +}; +/* A pane per row, so hosted rows show theirs; the stock rows bring Apple's. */ +static const struct rv_pane panes[RV_COUNT(rows)]; + +static const struct rv_screen screens[] = { + RV_SCREEN_LIST_PANES("sound", "Sound", rows, panes), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_MUSIC_MENU, + RV_ROW_PUSH("Sound", "sound"), + .pane = RV_PANE(.caption = "Shape How Your Media Sounds", + .bitmap = RV_BITMAP("settings-sound"))), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_SCREENS(screens), + RV_ENTRIES(entries), +}; + +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/sound-menu/manifest.toml b/extensions/sound-menu/manifest.toml new file mode 100644 index 0000000..d03ddc9 --- /dev/null +++ b/extensions/sound-menu/manifest.toml @@ -0,0 +1,18 @@ +id = "sound-menu" +name = "Sound Menu" +description = "A Sound menu in Settings with Apple's Volume Limit, EQ and Sound Check and the audio extensions' rows." +version = "0.1.0" +author = "RevolaOS" +license = "GPL-3.0-only" +api = "1.89" +stability = "alpha" +category = "system" + +[[module]] +name = "main" +trigger = "always" + +[[asset]] +name = "settings-sound" +file = "assets/settings-sound.png" +pane = "icon" diff --git a/extensions/sound-menu/screenshots/sound.png b/extensions/sound-menu/screenshots/sound.png new file mode 100644 index 0000000000000000000000000000000000000000..450a7e1c575bc76711b50200891d1381fa619fa4 GIT binary patch literal 31251 zcmZ5nb8uu&xSeq0jcq#{+jcUsZQHhOZfx5&HrB@4*vUqlH@{c){&`hXQ+H-+Zg=1Q z`s>r@oG(gAK@t%T7Y+abAWBP#0RaFoA<*?L3^?fhpCTk-?)TLXlw;O-WHM0ZB0ALZmE7L3?yC zFaRlkuPECJtxW@W57CX1+vKv7eL$n4}#+uLA-K2p8SkKktx9Wt*I zl?2w9DDIWN8ThX-tWv=2z;xmFF^BN5&T7QB z@YA>4`WqTrZ=TZ1sc)rkQJe}h{j9ru>j)3OyTA*)eke5zX621hXTi^Q_)2&eb!f% zm)!q0?@9xhth!t7h7TQ$>awYJxP1fR?YvG%=yO3#hND6K62FDs?D)mx--9JvGgf$v)WT2pq+Gi#F8wQ zKF`49->}}XXh`%ykisNC*Y9Ut+9pDi_j!1^+(-i`vtsn?XaVZrRK_+G`P#)FHn3OS z@30(p#nHvBYA_7{z}3J5nClm0{o7_snixrf{p?bp!EiPADSVZu%lc#Ke3b&7B)q?l znfIahv^i_zJwA_f{5_h*S}U({p|Qq;`k2rt%T%t&wTVQ%$IX|kHmJbKOf&Y|Vjbkd zjUH_p=8hgQ>Vm@=sJYP>EE|L6_&(1T6Zdt!%~C*1IXi%$8LiK_j^i9S7A>pj^?FRe zBHO-756CWCU@R>>wwQi%BVY{8+d%p;6EB(gk?2-0-^;HM_%NoWj?&n6z4Xy!_eP(_3kmnNF!OY@iXgYibibfF1>)+pu}bjt8Jd%qL%rhVLYX z_;HOJ>(=azzqZk)PZ2tTj}2D1#7@7t!OC{xdN%R12_h%hn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W f9xj@`pD3*4Q`pmFsE>ez1CkQ^AzCG@7x4c8td)eJ literal 0 HcmV?d00001 diff --git a/themes/docs/extension-bitmaps.md b/themes/docs/extension-bitmaps.md index 554ea58..0fa66ca 100644 --- a/themes/docs/extension-bitmaps.md +++ b/themes/docs/extension-bitmaps.md @@ -26,3 +26,4 @@ Regenerate this page with `python3 tools/extension_bitmaps_doc.py`. | `night-shift` | `settings-night-shift` | 78x121 | mask8 | - | yes | | `playback-log` | `settings-playback-log` | 78x121 | mask8 | - | yes | | `reprise` | `settings-info` | 78x121 | mask8 | - | yes | +| `sound-menu` | `settings-sound` | 78x121 | mask8 | - | yes | diff --git a/themes/rvt/data/extensions.json b/themes/rvt/data/extensions.json index 2ab84e7..e67f600 100644 --- a/themes/rvt/data/extensions.json +++ b/themes/rvt/data/extensions.json @@ -11,3 +11,4 @@ {"asset": "settings-night-shift", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "night-shift", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-playback-log", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "playback-log", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-info", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "reprise", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} +{"asset": "settings-sound", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "sound-menu", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} From 4a3641f080aa8a2703cc4c4377963bb19547dc1c Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 17:08:17 +0000 Subject: [PATCH 19/20] feat: host the sound rows in Sound Menu Crossfeed, Balance and Edit EQ name sound-menu as their host, after the stock row each anchors on in Settings, so they sit in Settings > Sound while Sound Menu runs and keep their place otherwise. From RevolaOS extensions 51ee278. --- extensions/balance/README.md | 2 +- extensions/balance/main.c | 3 ++- extensions/crossfeed/README.md | 2 +- extensions/crossfeed/main.c | 3 ++- extensions/equalizer/README.md | 2 +- extensions/equalizer/main.c | 3 ++- 6 files changed, 9 insertions(+), 6 deletions(-) diff --git a/extensions/balance/README.md b/extensions/balance/README.md index e20b3ea..ffc1b55 100644 --- a/extensions/balance/README.md +++ b/extensions/balance/README.md @@ -12,7 +12,7 @@ Settings > Balance draws the stereo image as a lobe in a half disc, the ears at | R 1 dB to R 20 dB | the left ear that much quieter | | R only | the right ear alone | -Changes apply immediately and are saved. The Balance row sits after Volume Limit, with the position as its caption. Center costs nothing per sample. +Changes apply immediately and are saved. The Balance row sits after Volume Limit, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise, with the position as its caption. Center costs nothing per sample. | | | |---|---| diff --git a/extensions/balance/main.c b/extensions/balance/main.c index 56fdae0..cbf3bbe 100644 --- a/extensions/balance/main.c +++ b/extensions/balance/main.c @@ -44,7 +44,8 @@ static const struct rv_menu_entry entries[] = { RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_VOLUME_LIMIT, RV_ROW_PUSH("Balance", "editor"), .pane = RV_PANE(.bitmap = RV_BITMAP("settings-balance")), - .caption_setting = KEY_BALANCE), + .caption_setting = KEY_BALANCE, .host = "sound-menu", + .host_screen = "sound", .host_after = "volume-limit"), }; static const struct rv_descriptor extension = { diff --git a/extensions/crossfeed/README.md b/extensions/crossfeed/README.md index e30634d..0e1f530 100644 --- a/extensions/crossfeed/README.md +++ b/extensions/crossfeed/README.md @@ -24,7 +24,7 @@ The plot shows the ear's own channel and the one fed across, with the precut app Cross is the level of the other channel below the Cutoff, Highs its level above. A centred passage reaches each ear through both paths, so below the Cutoff it plays at Direct plus Cross, about +2.5 dB at the defaults. Precut lowers both paths: Auto picks the smallest 0.5 dB step that keeps the largest possible sum at or below 0 dB. Simple has no precut and can go up to 3.4 dB over when the channels differ. A look-ahead limiter catches what still goes over, in Simple or with a fixed precut, and delays the output by about 0.7 ms. -The Crossfeed row sits after Sound Check, with the mode as its caption. Off costs nothing per sample. +The Crossfeed row sits after Sound Check, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise, with the mode as its caption. Off costs nothing per sample. | | | |---|---| diff --git a/extensions/crossfeed/main.c b/extensions/crossfeed/main.c index c6b1a5d..95901c1 100644 --- a/extensions/crossfeed/main.c +++ b/extensions/crossfeed/main.c @@ -73,7 +73,8 @@ static const struct rv_menu_entry entries[] = { RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_SOUND_CHECK, RV_ROW_PUSH("Crossfeed", "editor"), .pane = RV_PANE(.bitmap = RV_BITMAP("settings-crossfeed")), - .caption_setting = KEY_MODE), + .caption_setting = KEY_MODE, .host = "sound-menu", + .host_screen = "sound", .host_after = "sound-check"), }; static const struct rv_descriptor extension = { diff --git a/extensions/equalizer/README.md b/extensions/equalizer/README.md index 0ce7f30..fa936cc 100644 --- a/extensions/equalizer/README.md +++ b/extensions/equalizer/README.md @@ -4,7 +4,7 @@ Partly adapted from the RepriseOS core's [Custom EQ](https://github.com/RepriseO 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: +The EQ list gains a Custom preset after Apple's. While Custom is selected, an Edit EQ row shapes it. The row sits after EQ, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise. 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 | |---|---|---| diff --git a/extensions/equalizer/main.c b/extensions/equalizer/main.c index c99fb92..10f46c8 100644 --- a/extensions/equalizer/main.c +++ b/extensions/equalizer/main.c @@ -204,7 +204,8 @@ static const struct rv_menu_entry entries[] = { RV_ROW_ACTION("Edit EQ", open_editor), .pane = RV_PANE(.caption = "Adjust Your Sound", .bitmap = RV_BITMAP("settings-eq")), - .shown_by = KEY_CUSTOM_SHOWN), + .shown_by = KEY_CUSTOM_SHOWN, .host = "sound-menu", + .host_screen = "sound", .host_after = "eq"), }; static const struct rv_descriptor extension = { From 5ca7dd4e6289c701053ca688d3bd085a71b642de Mon Sep 17 00:00:00 2001 From: Paul-Vincent Roll Date: Fri, 27 Nov 2026 17:08:18 +0000 Subject: [PATCH 20/20] feat: add five sound effects Channels, Compressor, Surround, Bass Enhancement and Fatigue Reduction: five effects on the shared output stage, each with a Settings row after Sound Check that opens a canvas editor, in Settings > Sound while Sound Menu runs. Channels narrows or widens the stereo image or plays mono, one channel in both ears, karaoke or swapped channels. Compressor turns loud passages down. Surround delays the right channel outside a band that stays in place. Bass Enhancement and Fatigue Reduction run fixed filter banks at a chosen strength. All but Channels use the dsp library. Channels, Compressor and Fatigue Reduction are ported from Rockbox; Bass Enhancement and Surround are based on it. From RevolaOS extensions a32d616f5a06. --- Makefile | 12 +- NOTICE | 12 +- README.md | 5 + catalog/sources.toml | 25 + extensions/bass-enhancement/Makefile | 6 + extensions/bass-enhancement/README.md | 25 + extensions/bass-enhancement/assets/render.py | 74 +++ .../assets/settings-bass-enhancement.png | Bin 0 -> 2633 bytes extensions/bass-enhancement/bass.h | 18 + extensions/bass-enhancement/design.c | 59 ++ extensions/bass-enhancement/editor.c | 155 +++++ extensions/bass-enhancement/listing.toml | 5 + extensions/bass-enhancement/main.c | 84 +++ extensions/bass-enhancement/manifest.toml | 27 + extensions/bass-enhancement/modes.c | 6 + .../bass-enhancement/screenshots/editor.png | Bin 0 -> 10053 bytes extensions/bass-enhancement/shared.h | 33 + extensions/bass-enhancement/tests/host.c | 43 ++ extensions/bass-enhancement/tests/run.py | 192 ++++++ extensions/channels/Makefile | 4 + extensions/channels/README.md | 27 + extensions/channels/assets/render.py | 65 ++ .../channels/assets/settings-channels.png | Bin 0 -> 1243 bytes extensions/channels/channels.c | 154 +++++ extensions/channels/channels.h | 39 ++ extensions/channels/editor.c | 258 ++++++++ extensions/channels/labels.c | 12 + extensions/channels/labels.h | 18 + extensions/channels/listing.toml | 5 + extensions/channels/main.c | 94 +++ extensions/channels/manifest.toml | 24 + extensions/channels/modes.c | 7 + extensions/channels/modes.h | 11 + extensions/channels/screenshots/editor.png | Bin 0 -> 8812 bytes extensions/channels/shared.h | 26 + extensions/channels/tests/host.c | 33 + extensions/channels/tests/run.py | 258 ++++++++ extensions/compressor/Makefile | 7 + extensions/compressor/README.md | 27 + extensions/compressor/assets/render.py | 61 ++ .../compressor/assets/settings-compressor.png | Bin 0 -> 1017 bytes extensions/compressor/compressor.c | 202 ++++++ extensions/compressor/compressor.h | 56 ++ extensions/compressor/curve.c | 54 ++ extensions/compressor/design.c | 115 ++++ extensions/compressor/editor.c | 271 ++++++++ extensions/compressor/labels.c | 29 + extensions/compressor/labels.h | 27 + extensions/compressor/listing.toml | 5 + extensions/compressor/main.c | 88 +++ extensions/compressor/manifest.toml | 27 + extensions/compressor/screenshots/editor.png | Bin 0 -> 15663 bytes extensions/compressor/shared.h | 53 ++ extensions/compressor/tests/host.c | 33 + extensions/compressor/tests/run.py | 585 ++++++++++++++++++ extensions/fatigue-reduction/Makefile | 6 + extensions/fatigue-reduction/README.md | 26 + .../assets/LICENSE.cupertino-icons | 20 + extensions/fatigue-reduction/assets/render.py | 32 + .../assets/settings-fatigue-reduction.png | Bin 0 -> 2009 bytes extensions/fatigue-reduction/design.c | 42 ++ extensions/fatigue-reduction/editor.c | 146 +++++ extensions/fatigue-reduction/fatigue.h | 16 + extensions/fatigue-reduction/listing.toml | 5 + extensions/fatigue-reduction/main.c | 82 +++ extensions/fatigue-reduction/manifest.toml | 27 + extensions/fatigue-reduction/modes.c | 6 + .../fatigue-reduction/screenshots/editor.png | Bin 0 -> 8475 bytes extensions/fatigue-reduction/shared.h | 25 + extensions/fatigue-reduction/tests/host.c | 43 ++ extensions/fatigue-reduction/tests/run.py | 159 +++++ extensions/surround/Makefile | 8 + extensions/surround/README.md | 29 + extensions/surround/assets/render.py | 71 +++ .../surround/assets/settings-surround.png | Bin 0 -> 2506 bytes extensions/surround/design.c | 25 + extensions/surround/editor.c | 211 +++++++ extensions/surround/labels.c | 28 + extensions/surround/labels.h | 27 + extensions/surround/listing.toml | 5 + extensions/surround/main.c | 89 +++ extensions/surround/manifest.toml | 27 + extensions/surround/response.c | 69 +++ extensions/surround/screenshots/editor.png | Bin 0 -> 15132 bytes extensions/surround/shared.h | 69 +++ extensions/surround/surround.c | 166 +++++ extensions/surround/surround.h | 41 ++ extensions/surround/tests/host.c | 33 + extensions/surround/tests/run.py | 418 +++++++++++++ themes/docs/extension-bitmaps.md | 5 + themes/rvt/data/extensions.json | 5 + 91 files changed, 5410 insertions(+), 7 deletions(-) create mode 100644 extensions/bass-enhancement/Makefile create mode 100644 extensions/bass-enhancement/README.md create mode 100644 extensions/bass-enhancement/assets/render.py create mode 100644 extensions/bass-enhancement/assets/settings-bass-enhancement.png create mode 100644 extensions/bass-enhancement/bass.h create mode 100644 extensions/bass-enhancement/design.c create mode 100644 extensions/bass-enhancement/editor.c create mode 100644 extensions/bass-enhancement/listing.toml create mode 100644 extensions/bass-enhancement/main.c create mode 100644 extensions/bass-enhancement/manifest.toml create mode 100644 extensions/bass-enhancement/modes.c create mode 100644 extensions/bass-enhancement/screenshots/editor.png create mode 100644 extensions/bass-enhancement/shared.h create mode 100644 extensions/bass-enhancement/tests/host.c create mode 100644 extensions/bass-enhancement/tests/run.py create mode 100644 extensions/channels/Makefile create mode 100644 extensions/channels/README.md create mode 100644 extensions/channels/assets/render.py create mode 100644 extensions/channels/assets/settings-channels.png create mode 100644 extensions/channels/channels.c create mode 100644 extensions/channels/channels.h create mode 100644 extensions/channels/editor.c create mode 100644 extensions/channels/labels.c create mode 100644 extensions/channels/labels.h create mode 100644 extensions/channels/listing.toml create mode 100644 extensions/channels/main.c create mode 100644 extensions/channels/manifest.toml create mode 100644 extensions/channels/modes.c create mode 100644 extensions/channels/modes.h create mode 100644 extensions/channels/screenshots/editor.png create mode 100644 extensions/channels/shared.h create mode 100644 extensions/channels/tests/host.c create mode 100644 extensions/channels/tests/run.py create mode 100644 extensions/compressor/Makefile create mode 100644 extensions/compressor/README.md create mode 100644 extensions/compressor/assets/render.py create mode 100644 extensions/compressor/assets/settings-compressor.png create mode 100644 extensions/compressor/compressor.c create mode 100644 extensions/compressor/compressor.h create mode 100644 extensions/compressor/curve.c create mode 100644 extensions/compressor/design.c create mode 100644 extensions/compressor/editor.c create mode 100644 extensions/compressor/labels.c create mode 100644 extensions/compressor/labels.h create mode 100644 extensions/compressor/listing.toml create mode 100644 extensions/compressor/main.c create mode 100644 extensions/compressor/manifest.toml create mode 100644 extensions/compressor/screenshots/editor.png create mode 100644 extensions/compressor/shared.h create mode 100644 extensions/compressor/tests/host.c create mode 100644 extensions/compressor/tests/run.py create mode 100644 extensions/fatigue-reduction/Makefile create mode 100644 extensions/fatigue-reduction/README.md create mode 100644 extensions/fatigue-reduction/assets/LICENSE.cupertino-icons create mode 100644 extensions/fatigue-reduction/assets/render.py create mode 100644 extensions/fatigue-reduction/assets/settings-fatigue-reduction.png create mode 100644 extensions/fatigue-reduction/design.c create mode 100644 extensions/fatigue-reduction/editor.c create mode 100644 extensions/fatigue-reduction/fatigue.h create mode 100644 extensions/fatigue-reduction/listing.toml create mode 100644 extensions/fatigue-reduction/main.c create mode 100644 extensions/fatigue-reduction/manifest.toml create mode 100644 extensions/fatigue-reduction/modes.c create mode 100644 extensions/fatigue-reduction/screenshots/editor.png create mode 100644 extensions/fatigue-reduction/shared.h create mode 100644 extensions/fatigue-reduction/tests/host.c create mode 100644 extensions/fatigue-reduction/tests/run.py create mode 100644 extensions/surround/Makefile create mode 100644 extensions/surround/README.md create mode 100644 extensions/surround/assets/render.py create mode 100644 extensions/surround/assets/settings-surround.png create mode 100644 extensions/surround/design.c create mode 100644 extensions/surround/editor.c create mode 100644 extensions/surround/labels.c create mode 100644 extensions/surround/labels.h create mode 100644 extensions/surround/listing.toml create mode 100644 extensions/surround/main.c create mode 100644 extensions/surround/manifest.toml create mode 100644 extensions/surround/response.c create mode 100644 extensions/surround/screenshots/editor.png create mode 100644 extensions/surround/shared.h create mode 100644 extensions/surround/surround.c create mode 100644 extensions/surround/surround.h create mode 100644 extensions/surround/tests/host.c create mode 100644 extensions/surround/tests/run.py diff --git a/Makefile b/Makefile index e1eeccc..87e7295 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,10 @@ # SPDX-License-Identifier: GPL-3.0-only SDK ?= ../osos-lab/rvx-sdk OUT ?= build -extensions := album-artists appearance balance clicker-modes crossfeed dsp equalizer \ - eu-volume-limit file-info homebrew iap-auth-bypass night-shift \ - playback-log playback-queue sound-menu +extensions := album-artists appearance balance bass-enhancement channels clicker-modes \ + compressor crossfeed dsp equalizer eu-volume-limit fatigue-reduction file-info \ + homebrew iap-auth-bypass night-shift playback-log playback-queue sound-menu \ + surround .PHONY: all $(extensions) all: $(extensions) $(OUT)/assets.json @@ -27,10 +28,15 @@ check: $(PYTHON) extensions/album-artists/tests/run.py "$(abspath $(SDK))" $(PYTHON) extensions/appearance/tests/run.py "$(abspath $(SDK))" $(PYTHON) extensions/balance/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/bass-enhancement/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/channels/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/compressor/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/fatigue-reduction/tests/run.py "$(abspath $(SDK))" $(PYTHON) extensions/file-info/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/surround/tests/run.py "$(abspath $(SDK))" @mkdir -p "$(OUT)" $(CC) $(TEST_FLAGS) -Iextensions/shared extensions/night-shift/test.c -o "$(OUT)/test-night-shift" "$(OUT)/test-night-shift" diff --git a/NOTICE b/NOTICE index ae35110..63571e3 100644 --- a/NOTICE +++ b/NOTICE @@ -24,10 +24,14 @@ a32d616f5a06, and derives from the RepriseOS core's Dark Mode by lgreitis and Alex Ball; its Settings icons are Cupertino Icons glyphs (MIT), see the LICENSE.cupertino-icons beside them, and the Classic theme it carries is built by the rvt compiler in themes/ (see themes/NOTICE). Night Shift's hosted row and -choice screen are from RevolaOS extensions, revision d04fa7d. Sound Menu is from -RevolaOS extensions, revision a32d616f5a06; its icon is a Cupertino Icons glyph -(MIT), see the LICENSE.cupertino-icons beside it. The original RevolaOS notice -follows. +choice screen are from RevolaOS extensions, revision d04fa7d. Channels, +Compressor, Surround, Bass Enhancement, Fatigue Reduction and Sound Menu are +from RevolaOS extensions, revision a32d616f5a06, as are the Sound Menu rows of +Crossfeed, Balance and Equalizer. Channels, Compressor and Fatigue Reduction are +ported from Rockbox and Bass Enhancement and Surround are based on it (see the +Rockbox entry below). The Fatigue Reduction and Sound Menu icons are Cupertino +Icons glyphs (MIT), see the LICENSE.cupertino-icons beside each. 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 d38f27e..85b7a1c 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,11 @@ This repository hosts the source for these RepriseOS extensions and accepts prop - [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/). +- [Channels](extensions/channels/) narrows or widens the stereo image, or plays mono, one channel in both ears, karaoke or swapped channels. +- [Compressor](extensions/compressor/) turns loud passages down so quiet ones stay audible. It uses the included [DSP library](extensions/dsp/). +- [Surround](extensions/surround/) widens the stage for headphones by delaying the right channel outside a band that stays in place. It uses the included [DSP library](extensions/dsp/). +- [Bass Enhancement](extensions/bass-enhancement/) fills out the bass and clears the mids with five fixed filters at a chosen strength. It uses the included [DSP library](extensions/dsp/). +- [Fatigue Reduction](extensions/fatigue-reduction/) takes the edge off the upper mids and treble in three strengths for long listening. It uses the included [DSP library](extensions/dsp/). - [Sound Menu](extensions/sound-menu/) adds Settings > Sound with Apple's Volume Limit, EQ and Sound Check rows and the audio extensions' rows after them. - [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. diff --git a/catalog/sources.toml b/catalog/sources.toml index 4272bd4..f4bcf57 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -68,6 +68,31 @@ repo = "RepriseOS/repriseos-extensions" path = "extensions/homebrew" tag_prefix = "homebrew/v" +[channels] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/channels" +tag_prefix = "channels/v" + +[compressor] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/compressor" +tag_prefix = "compressor/v" + +[surround] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/surround" +tag_prefix = "surround/v" + +[bass-enhancement] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/bass-enhancement" +tag_prefix = "bass-enhancement/v" + +[fatigue-reduction] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/fatigue-reduction" +tag_prefix = "fatigue-reduction/v" + [sound-menu] repo = "RepriseOS/repriseos-extensions" path = "extensions/sound-menu" diff --git a/extensions/bass-enhancement/Makefile b/extensions/bass-enhancement/Makefile new file mode 100644 index 0000000..6979839 --- /dev/null +++ b/extensions/bass-enhancement/Makefile @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: GPL-3.0-only +# The per-sample work is the dsp library's cascade, built as ARM there. +main_SOURCES := main.c design.c modes.c ../shared/bank.c +editor_SOURCES := editor.c design.c modes.c +EXTRA_CFLAGS := -I../shared -DBANK_STAGES=5 +include $(SDK)/rv.mk diff --git a/extensions/bass-enhancement/README.md b/extensions/bass-enhancement/README.md new file mode 100644 index 0000000..46a2992 --- /dev/null +++ b/extensions/bass-enhancement/README.md @@ -0,0 +1,25 @@ +# Bass Enhancement + +Based on Rockbox's perceptual bass enhancement (`lib/rbcodec/dsp/pbe.c`) by Chiwen Chang, GPL-2.0-or-later. + +Fills out the bass and clears the mids with five fixed filters: a lift at 64 Hz and at 2 kHz, a cut at 7.5 kHz and at 10 kHz, and a shelf that lifts the top above 16 kHz. Runs at its own stage of the shared [output stage](https://github.com/paviro/revola/blob/main/docs/sdk/audio.md), after Crossfeed and before Fatigue Reduction. + +Settings > Bass Enhancement plots the response of the chosen strength, with the strength and its precut below. The wheel picks a strength, holding Select resets it to Off, Menu goes back. Changes apply immediately and are saved. + +| Strength | 64 Hz | 2 kHz | 7.5 kHz | 10 kHz | Above 16 kHz | +|---|---|---|---|---|---| +| Off | nothing changes | | | | | +| 25 % | +1.3 dB | +1.5 dB | -2.1 dB | -0.7 dB | +1.3 dB | +| 50 % | +2.7 dB | +2.9 dB | -4.1 dB | -1.5 dB | +2.7 dB | +| 75 % | +4.0 dB | +4.4 dB | -6.2 dB | -2.2 dB | +4.0 dB | +| 100 % | +5.3 dB | +5.8 dB | -8.2 dB | -2.9 dB | +5.3 dB | + +At 100 % these are Rockbox's gains, with the whole cascade a further 0.5 dB down; a lower strength scales each of them in decibels. Rockbox's strength sets the delays of a band split instead, which is left out here, as is its precut setting. The precut takes the whole cascade down by its largest lift, so the level never exceeds the input's, and the plot shows the curves with it. Peaks that still line up above full scale go through a look-ahead limiter, which delays the output by about 0.7 ms. The filters are designed for 44.1 and 48 kHz; at other rates the audio passes through. + +The Bass Enhancement row sits after Sound Check, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise, with the strength as its caption. Off costs nothing per sample. + +| | | +|---|---| +| Default | off | +| Memory | image only | +| Settings | strength | diff --git a/extensions/bass-enhancement/assets/render.py b/extensions/bass-enhancement/assets/render.py new file mode 100644 index 0000000..cbc69c9 --- /dev/null +++ b/extensions/bass-enhancement/assets/render.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render settings-bass-enhancement.png, the Settings pane icon: one period of +a low wave inside a ring, on a 78 x 121 gray coverage mask in the style of the +stock Settings icons, lit from the top and mirrored in a fading reflection +below. Drawing uses ImageMagick's `magick`. + + python3 assets/render.py + python3 assets/render.py --check +""" + +import math +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import icon, main, supersampled + +OUT = HERE / "settings-bass-enhancement.png" +# The ring about CENTRE between OUTER and INNER; inside it one period of a +# sine, WAVE_HALF each side of the centre and WAVE_AMPLITUDE high, stroked +# WAVE_STROKE wide with round ends, which stop short of the ring. +CENTRE = (39, 37) +OUTER, INNER = 26, 21 +WAVE_HALF, WAVE_AMPLITUDE, WAVE_STROKE = 17.5, 7, 4.5 +WAVE_POINTS = 240 +ART_TOP, ART_BOTTOM = CENTRE[1] - OUTER, CENTRE[1] + OUTER + + +def wave(k): + """The sine as a magick path, left to right, with every coordinate scaled + by k.""" + cx, cy = CENTRE + points = [] + for i in range(WAVE_POINTS + 1): + x = cx - WAVE_HALF + 2 * WAVE_HALF * i / WAVE_POINTS + y = cy - WAVE_AMPLITUDE * math.sin(2 * math.pi * i / WAVE_POINTS) + points.append(f"{x * k:.1f},{y * k:.1f}") + return "M " + " L ".join(points) + + +def shapes(k): + """magick -draw arguments for the ring and the wave, white on black, with + every coordinate scaled by k.""" + cx, cy = (v * k for v in CENTRE) + return [ + "-fill", + "white", + "-draw", + f"circle {cx},{cy} {cx + OUTER * k},{cy}", + "-fill", + "black", + "-draw", + f"circle {cx},{cy} {cx + INNER * k},{cy}", + "-fill", + "none", + "-stroke", + "white", + "-strokewidth", + str(WAVE_STROKE * k), + "-draw", + f"stroke-linecap round path '{wave(k)}'", + "-stroke", + "none", + ] + + +def render(out, work): + icon(out, work, supersampled(work, shapes), ART_TOP, ART_BOTTOM) + + +if __name__ == "__main__": + main(__doc__, {OUT: render}) diff --git a/extensions/bass-enhancement/assets/settings-bass-enhancement.png b/extensions/bass-enhancement/assets/settings-bass-enhancement.png new file mode 100644 index 0000000000000000000000000000000000000000..15db6c519cbaff3115a253bbc3f686794d58f649 GIT binary patch literal 2633 zcmZ{mS5Oo97RLW{Bp?RGKxjc}QUjrv(5nm5lqw=6)IjJ>AQVFpL@CmXRFSm&1sGV-=>wvR_w1L+1 zjUmv`SeIcH0);BjY-iSB&Mm<}UF$%X`+=^?&i=0F0%VXf@)FY064DBm(hACQa>_`Q z7!s+BL~h@e-1+9ly3Hx^-20XJk2Somt5a@w*4G6rC#r-=o$^J0~fD00aI+~X5 zq>Wr`O6CN6&lzQoGM#G^oUPDSk(?+czQA?+9lL?Ij+n7`-Y@M5ck#(ig+zGg9p}3G zncBQ4cW=)W+shKz@|kgK<2s`((WmlvOwFk1m});YJQ8nS9~x5KFN#)Y?o~w%4^Ru8 zepM^RY|c^k3j#J9DWm{;j;GMWZ;!Zl#CeH23Ujo#KNgpps8*I{uxWAFOr#5gEb!IzU(@|}FVxf;iuR0v?%8<5FGWeAH^eYc06N1+49$j{t zUP14S61LV;BQb$pN$BvRwAficLo-jzcqP8qr>IzQOWq#+gog>Q6yfv3FX^W8oVMO zbJS?{6(QKFg2+#_7`OF%aB|gv@hq%jYRM^lf~8-Ov3D0i6g|*#*3Hd& zIK!1%2g&hbTTe3;go)>W^NGoTp#wa7$G2GZ{`#{X!GcS!wlI`<1(^3q8hj77`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gp3A5vgYFB}V2L9_%Vd|UEub1R8MxWbIeUn9cOhz<$COoWKqAzV2O(~); z*|-k$5_H(GqVAJF7xd>sSM%V+EL-nt;xNheJd5Cna6Ml zxZ=Ihw_tb`yPip``ppwJ@l*)$WQ*J4u>LfIxv0M+h?_O`Eq3;Dby#8I7LU6{toMGL zjH*daF;m=q+@c1C=AKbAM1sCF@~wEs0>YxOZKQP?PDc~5_^EA#yhQ`KApy;x1&L~5z?{RI zAjW~;F{N2jw&lV5M?*n+3^g8ZpZbnROZ#5Bp_h`Vu&fs3pG&|xru^c2X-T-N&T_v! z;lx_{jsTGr%BUo5q$JzDZhwLtPV{ J*IJIT{{d*`yeI$w literal 0 HcmV?d00001 diff --git a/extensions/bass-enhancement/bass.h b/extensions/bass-enhancement/bass.h new file mode 100644 index 0000000..510f879 --- /dev/null +++ b/extensions/bass-enhancement/bass.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef BASS_H +#define BASS_H + +/* The strength as a quarter: Off, 25, 50, 75 or 100 %. */ +enum { + BASS_OFF, + BASS_25, + BASS_50, + BASS_75, + BASS_100, + BASS_STRENGTHS, +}; + +enum { BASS_STAGES = 5 }; + +#endif diff --git a/extensions/bass-enhancement/design.c b/extensions/bass-enhancement/design.c new file mode 100644 index 0000000..ab3b30c --- /dev/null +++ b/extensions/bass-enhancement/design.c @@ -0,0 +1,59 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The five filters, with every gain scaled by the strength: a high shelf of + * +5.3 dB above 16 kHz with the whole cascade down 0.5 dB, bells of +5.3 dB at + * 64 Hz and +5.8 dB at 2 kHz with Q 2.8, and bells of -8.2 dB at 7.5 kHz and + * -2.9 dB at 10 kHz with Q 4.3. At 100 % these are the gains of Rockbox's + * perceptual bass enhancement; a lower strength scales each in decibels. The + * precut is the cascade's peak, so the output never exceeds the input's level + * before the limiter. + * + * Based on Rockbox lib/rbcodec/dsp/pbe.c (Copyright (C) 2014 by Chiwen + * Chang). */ + +#include "rv_dsp.h" +#include "shared.h" + +struct bell { + uint16_t hz; + uint8_t q_tenths; + int16_t gain_tenths; +}; + +static const struct bell bells[BASS_STAGES - 1] = { + {64, 28, 53}, + {2000, 28, 58}, + {7500, 43, -82}, + {10000, 43, -29}, +}; + +enum { SHELF_HZ = 16000, SHELF_GAIN = 53, OVERALL_GAIN = -5, PRECUT_LIMIT = 100 }; + +/* `tenths` at `percent`, rounded to the nearest tenth of a decibel. */ +static int scaled(int tenths, unsigned int percent) +{ + int value = tenths * (int)percent; + return (value + (value < 0 ? -50 : 50)) / 100; +} + +int bass_design(int32_t out[BASS_STAGES][5], unsigned int *precut_tenths, + unsigned int strength, unsigned int rate) +{ + if (strength >= BASS_STRENGTHS) + return 0; + unsigned int percent = bass_percent(strength); + if (!rv_dsp_bishelf(out[0], 20, SHELF_HZ, 0, scaled(SHELF_GAIN, percent), + scaled(OVERALL_GAIN, percent), rate)) + return 0; + for (unsigned int i = 0; i < BASS_STAGES - 1; i++) + if (!rv_dsp_biquad(out[i + 1], RV_DSP_PEAKING, bells[i].hz, bells[i].q_tenths, + scaled(bells[i].gain_tenths, percent), 0, rate)) + return 0; + int peak = strength == BASS_OFF ? 0 : rv_dsp_peak(out, BASS_STAGES, rate); + unsigned int precut = peak <= 0 ? 0 + : peak > PRECUT_LIMIT ? PRECUT_LIMIT + : (unsigned int)peak; + rv_dsp_attenuate(out[0], precut); + *precut_tenths = precut; + return 1; +} diff --git a/extensions/bass-enhancement/editor.c b/extensions/bass-enhancement/editor.c new file mode 100644 index 0000000..b924bdb --- /dev/null +++ b/extensions/bass-enhancement/editor.c @@ -0,0 +1,155 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Bass Enhancement screen: the response of the chosen strength as a + * curve, with its precut included, over the strength and the precut it + * brings. The wheel picks the strength, holding Select puts it back to Off and + * Menu steps back out. Every change plays at once. */ + +#include "rv_canvas.h" +#include "rv_dsp.h" +#include "rv_libc.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +enum { DEPTHS = 1 }; /* the wheel edits the one value */ + +enum { + PLOT_POINTS = 261, + PLOT_TOP = 36, + TICK_GAP = 6, /* plot bottom to the tick labels */ + TICK_HEIGHT = 22, + FIELD_GAP = 5, /* tick labels to the field row */ + FIELD_HEIGHT = + 27, /* Strength | Precut, title left and value right, at the bottom */ + PRECUT_BYTES = 9, /* "-10.0 dB" */ +}; + +/* 0 dB at the top, -15 dB at the bottom, just under the deepest cut at 100 % + * with its precut; the plot runs down to the tick labels above the field row, + * which sits on the bottom edge. */ +static struct rv_plot plot_for(int height) +{ + struct rv_plot plot = { + .left = 44, .top = PLOT_TOP, .points = PLOT_POINTS, .bottom_value = -150}; + plot.bottom = (int16_t)(height - FIELD_HEIGHT - FIELD_GAP - TICK_HEIGHT - TICK_GAP); + return plot; +} + +static struct { + struct rv_editor input; + unsigned int precut; /* tenths of a decibel */ + int16_t curve[PLOT_POINTS]; +} editor; + +static int strength(void) +{ + return rv_clamp(api->setting_get_int(self, KEY_STRENGTH), BASS_OFF, BASS_100); +} + +/* The chosen strength's curve with its precut, drawn for 44.1 kHz, the rate + * nearly everything plays at; it barely moves at 48 kHz. Off is the zero + * line. */ +static void compute_curve(void) +{ + int32_t coefficients[BASS_STAGES][5]; + int chosen = strength(); + editor.precut = 0; + if (chosen != BASS_OFF && + bass_design(coefficients, &editor.precut, (unsigned int)chosen, 44100)) + rv_dsp_response(coefficients, BASS_STAGES, 44100, editor.curve, PLOT_POINTS); + else + memset(editor.curve, 0, sizeof editor.curve); +} + +static void draw_plot(const struct rv_canvas *c, const struct rv_plot *plot) +{ + static const char *const ticks[] = {"20", "200", "2k", "20k Hz"}; + static const char *const scale[] = {"0", "-5", "-10", "-15"}; + + rv_plot_ticks(c, plot, ticks, 4, plot->bottom + TICK_GAP, TICK_HEIGHT); + rv_plot_grid(c, plot, scale, 4); + rv_canvas_header(c, "Response", NULL, 0); + rv_plot_curve(c, plot, editor.curve, 2, RV_CANVAS_ACCENT); +} + +/* Strength edits; the precut beside it only reads, muted, so the level under + * the zero line has a name. */ +static void draw_fields(const struct rv_canvas *c, int height) +{ + static const char *const titles[] = {"Strength", "Precut"}; + char precut[PRECUT_BYTES]; + rv_format_tenths(precut, sizeof precut, -(int)editor.precut, 0, " dB"); + const char *values[] = {strength_labels[strength()], precut}; + uint8_t states[] = {RV_CELL_EDITING, RV_CELL_IDLE | RV_CELL_MUTED}; + rv_canvas_fields(c, height - FIELD_HEIGHT, FIELD_HEIGHT, titles, values, states, 2); +} + +static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width, + int height) +{ + struct rv_canvas c; + (void)ctx; + struct rv_plot plot = plot_for(height); + rv_canvas_begin(&c, g, width, height); + draw_plot(&c, &plot); + draw_fields(&c, height); +} + +/* Main republishes from setting_changed, so a change plays at once. */ +static void set_strength(int next) +{ + if (next == strength()) + return; + api->setting_set_int(self, KEY_STRENGTH, next); + compute_curve(); +} + +static int input(const struct rv_context *ctx, const struct rv_input *input) +{ + (void)ctx; + switch (rv_editor_input(&editor.input, input)) { + case RV_EDITOR_IGNORED: + return 0; + case RV_EDITOR_CONSUMED: + return 1; + case RV_EDITOR_WHEEL: + set_strength(rv_clamp(strength() + input->delta, BASS_OFF, BASS_100)); + break; + case RV_EDITOR_RESET: + set_strength(STRENGTH_DEFAULT); + break; + default: + 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; + compute_curve(); +} + +static const struct rv_screen screens[] = { + RV_SCREEN_CANVAS("editor", "Bass Enhancement", draw, input, + .transition = RV_TRANSITION_FROM_PANE, .opened = opened), +}; + +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/bass-enhancement/listing.toml b/extensions/bass-enhancement/listing.toml new file mode 100644 index 0000000..addf0b0 --- /dev/null +++ b/extensions/bass-enhancement/listing.toml @@ -0,0 +1,5 @@ +details = "Open Settings > Bass Enhancement to fill out the bass and clear the mids with five fixed filters at a strength from 25 to 100 %. The plot shows the response." + +[[screenshots]] +file = "screenshots/editor.png" +alt = "The Bass Enhancement editor at 75 %, with the response plot above Strength and Precut." diff --git a/extensions/bass-enhancement/main.c b/extensions/bass-enhancement/main.c new file mode 100644 index 0000000..7352be6 --- /dev/null +++ b/extensions/bass-enhancement/main.c @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Bass Enhancement: Settings > Bass Enhancement opens the editor screen, which + * holds the strength, Off or 25 to 100 %. The output-stage hook runs what is + * chosen on every buffer. */ + +#include "rv_api.h" +#include "bank.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; +static struct bank bank; +_Static_assert(BANK_STAGES == BASS_STAGES, "the Makefile's BANK_STAGES"); + +static const struct rv_setting settings[] = { + RV_SETTING_LABELLED(KEY_STRENGTH, "Bass Enhancement", STRENGTH_DEFAULT, + strength_labels), +}; + +/* Designs the filters of the chosen strength for both banks and leaves them for + * the pump task. */ +static void publish(void) +{ + unsigned int strength = (unsigned int)api->setting_get_int(self, KEY_STRENGTH); + struct bank_set set = {.on = strength != BASS_OFF}; + for (unsigned int b = 0; b < BANKS; b++) { + unsigned int precut; + if (!bass_design(set.coefficients[b], &precut, strength, bank_rate(b))) + set.on = 0; + } + bank_publish(&bank, &set); +} + +static void setting_changed(uint16_t key) +{ + (void)key; + publish(); +} + +/* The processed output before Apple submits it: (samples, frames, context). + * Only 16-bit stereo is touched. */ +static uint32_t on_output(uint32_t samples, uint32_t frames, uint32_t context, + const void *next) +{ + uint32_t rate; + if (rv_audio_stereo16((const void *)context, frames, 0, UINT32_MAX, &rate)) + bank_process(&bank, (int16_t *)samples, frames, rate); + return api->hook_next(next, samples, frames, context, 0, 0, 0); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER_AT(RV_SITE_AudioOutputQueue_Get_call, on_output, + RV_AUDIO_STAGE_BASS_ENHANCEMENT), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_SOUND_CHECK, + RV_ROW_PUSH("Bass Enhancement", "editor"), + .pane = RV_PANE(.bitmap = RV_BITMAP("settings-bass-enhancement")), + .caption_setting = KEY_STRENGTH, .host = "sound-menu", + .host_screen = "sound", .host_after = "sound-check"), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .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; + bank.effect.api = core; + return &extension; +} diff --git a/extensions/bass-enhancement/manifest.toml b/extensions/bass-enhancement/manifest.toml new file mode 100644 index 0000000..a091cf3 --- /dev/null +++ b/extensions/bass-enhancement/manifest.toml @@ -0,0 +1,27 @@ +id = "bass-enhancement" +name = "Bass Enhancement" +description = "Fuller bass and clearer mids from five fixed filters, scaled by a strength from 25 to 100 %, with the level held under full scale." +version = "0.1.0" +author = "RevolaOS" +note = "Based on Rockbox's bass enhancement" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "effects" + +[libraries] +required = ["dsp"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "editor" +trigger = "screen" +screens = ["editor"] + +[[asset]] +name = "settings-bass-enhancement" +file = "assets/settings-bass-enhancement.png" +pane = "icon" diff --git a/extensions/bass-enhancement/modes.c b/extensions/bass-enhancement/modes.c new file mode 100644 index 0000000..78bd996 --- /dev/null +++ b/extensions/bass-enhancement/modes.c @@ -0,0 +1,6 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "shared.h" + +const char *const strength_labels[BASS_STRENGTHS] = {"Off", "25 %", "50 %", "75 %", + "100 %"}; diff --git a/extensions/bass-enhancement/screenshots/editor.png b/extensions/bass-enhancement/screenshots/editor.png new file mode 100644 index 0000000000000000000000000000000000000000..9c87e7f21269a79cb14d13839c50e108e1a1cd15 GIT binary patch literal 10053 zcmc(FWmp_tw`F0WgA?2#Nbo=!cL?sm9fCLR8r&_oTOdeqcL)$XKycRp!3o-U!}R-o zbDx(S|9pE^6+q7BsKG4k9N{=H8VD>?joFHc>K!~%iZ zlZ)s^#xK_ezlvz-)ATbo4dc+qemoyBl4jWw3T6=!mSh>F>eaFh32L?~pv-@(@G;S> z#s$7jW4-bqlIAfydLA;Un z*qBlT_3A5jHSoAn+}vy3HD`A9GSGXFw-DvhT$d^vwbk&O+I_R}UAXfc2(HN>=e8!>?^ET=ZFI7$hirwV z&Qt?i(F!<#_Ckw#5-pOUaZRh@0{lLC0|ku+6(KsOo*Ek)o@`sbTBU`~lkr~*7>S;= z>%HX-1N~Cd2UnFN45At4JoGQ?FPHXFKj^n$HuqGYIDX|Z>~74OJXg(ZoRzWJ=>m<< zxL@?fY=aUOCV-*3D=0`dmtTU}APpJk8Ev3yG3 z_9wO29U4nSZtTSye~uB}>hDNgUAs6&C&&2QMNpk4gK0Cxde;*3F;;3l9sp?Qyu4;b z_n}m0L|HNte0f$IhpgRNsW{lby+1r_S*4_rkZv5NOh@CODRvSu87x`g4@Jcugb8#c zFuedGJ0xNHU5)H-*neDp%KR;$B5#V$zUdJ)#vyNp9vYd3eFqh34cz9F&*Z)tgjO0Z zIDvYgmFRk_^d3&e)ZSoDU-#ze9GrLV4)VviGM{5Zjj_QELaEa6vG7M_Ur&P_o2E8+ z3`nwOcU0t@vMKz| zbwXn3J*|v1>*$i5$Hgk0*`M$!*W_4EHO`?gth>=QN^E=|azuDDM=bj(KP1rskpUvS zp7ai|pRSKPsL9g~F9B2Vd0T}mfKwew;2m9aMknHFfdzDitS39>?eJj%E^VtjZE|tb ziSK(S&n4oi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J?`uLmZMb_#+)XEcOimkUOW}jeSQN%us#xVG3#KowJs8s-Lz>O(a2RxQ8(Lb0s|01OKb>-DZ_O6lYd>un$z)v7FhtQeLYgT!Vj(>o`0 zL(T>&hC{Rqb7AwB9L}0Cl&>TvoP8)IvAHD_hd;Dnf-}7!aNUguttO7A*D5qD!RCdnI&F2j*k~Z9ab@1PB{3u5_C z#=~V|%d9vK>NX-Od$br%e<9o8KMFDez5LTms2iGlz+?;`4mlESWXRof+26M+AA3)` R;Gf3 + +enum { + KEY_STRENGTH = 1, /* int: BASS_OFF to BASS_100 */ +}; + +enum { STRENGTH_DEFAULT = BASS_OFF }; + +/* The strength as a percentage. */ +static inline unsigned int bass_percent(unsigned int strength) +{ + return 25 * strength; +} + +/* design.c: the five filters of `strength` at `rate`, 44100 or 48000 Hz, in + * rv_dsp_biquad's format, the first cut by the precut that keeps the cascade's + * peak at or below 0 dB, which `precut_tenths` receives; Off is flat with no + * precut. 0 when a filter is not stable. */ +int bass_design(int32_t out[BASS_STAGES][5], unsigned int *precut_tenths, + unsigned int strength, unsigned int rate); + +/* modes.c: the strengths by name, for the Settings caption and the editor. */ +extern const char *const strength_labels[BASS_STRENGTHS]; + +#endif diff --git a/extensions/bass-enhancement/tests/host.c b/extensions/bass-enhancement/tests/host.c new file mode 100644 index 0000000..d309c0a --- /dev/null +++ b/extensions/bass-enhancement/tests/host.c @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The engine as the tone test drives it: the shared bank over interrupt + * masking that does nothing, fed the set layout the test builds. */ + +#include "bass.h" +#include "bank.h" +#include "rv_libc.h" + +static uint32_t irq_save(void) +{ + return 0; +} + +static void irq_restore(uint32_t state) +{ + (void)state; +} + +static const struct rv_api api = { + .size = sizeof api, .irq_save = irq_save, .irq_restore = irq_restore}; + +static struct bank bank = {.effect.api = &api}; + +struct test_set { + uint8_t strength; + int32_t coefficients[BANKS][BASS_STAGES][5]; +}; + +void bass_publish(const struct test_set *chosen) +{ + struct bank_set set = {.on = chosen->strength != 0}; + memcpy(set.coefficients[0], chosen->coefficients[0], + sizeof chosen->coefficients[0]); + memcpy(set.coefficients[1], chosen->coefficients[1], + sizeof chosen->coefficients[1]); + bank_publish(&bank, &set); +} + +void bass_process(int16_t *samples, uint32_t frames, uint32_t rate) +{ + bank_process(&bank, samples, frames, rate); +} diff --git a/extensions/bass-enhancement/tests/run.py b/extensions/bass-enhancement/tests/run.py new file mode 100644 index 0000000..e8ce66e --- /dev/null +++ b/extensions/bass-enhancement/tests/run.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the host tests with a staged SDK: python3 tests/run.py SDK. + +The reference gains at 100 % are those of Rockbox lib/rbcodec/dsp/pbe.c +(Copyright (C) 2014 by Chiwen Chang). Modified by the RevolaOS authors, 2026. +Rockbox is GPL-2.0-or-later; this version is GPL-3.0-only. +""" + +import ctypes +import math +import sys +import tempfile +from pathlib import Path + +root = Path(__file__).resolve().parent +dsp = root.parents[1] / "dsp" +shared = root.parents[1] / "shared" +sys.path.insert(0, str(dsp / "tests")) +from harness import build, strings # noqa: E402 +from model import SCALE, bishelf, peaking, power # noqa: E402 + +RATES = (44100, 48000) +STAGES, BANKS, STRENGTHS = 5, 2, 5 +OFF = 0 +FULL = STRENGTHS - 1 +# pbe.c's gains in tenths of a decibel: the shelf's high side and overall +# gain, then the four bells as (hz, Q tenths, gain). +SHELF_HZ, SHELF_GAIN, OVERALL = 16000, 53, -5 +BELLS = ((64, 28, 53), (2000, 28, 58), (7500, 43, -82), (10000, 43, -29)) +Biquad = ctypes.c_int32 * 5 +Bank = Biquad * STAGES + + +class Set(ctypes.Structure): + _fields_ = [("strength", ctypes.c_uint8), ("coefficients", Bank * BANKS)] + + +def scaled(tenths, percent): + """design.c's rounding of a gain at a strength.""" + value = tenths * percent + return int((value + (-50 if value < 0 else 50)) / 100) + + +def reference(strength, rate): + """The five filters at a strength before the precut, b0, b1, b2, a1, a2 + over a0.""" + percent = 25 * strength + shelf = bishelf( + 20, SHELF_HZ, 0, scaled(SHELF_GAIN, percent), scaled(OVERALL, percent), rate + ) + return [shelf] + [ + peaking(hz, q, scaled(gain, percent), rate) for hz, q, gain in BELLS + ] + + +def dense_peak(bank, rate): + """The largest response over 20 Hz to 20 kHz in tenths of a decibel.""" + points = (20 * 1000 ** (i / 6000) for i in range(6001)) + return 100 * math.log10(max(power(bank, hz, rate) for hz in points)) + + +def designed(dll, strength, rate): + out, precut = Bank(), ctypes.c_uint() + assert dll.bass_design(out, precut, strength, rate) == 1 + return out, precut.value + + +def design_tests(dll): + design = dll.bass_design + design.argtypes = [ctypes.POINTER(Biquad), ctypes.POINTER(ctypes.c_uint)] + design.argtypes += [ctypes.c_uint, ctypes.c_uint] + for rate in RATES: + for strength in range(STRENGTHS): + out, precut = designed(dll, strength, rate) + expected = reference(strength, rate) + if strength == OFF: + assert precut == 0 + for stage in out: + assert list(stage) == [SCALE, 0, 0, 0, 0] + continue + # The precut is the peak of the cascade, rounded up: at most a + # tenth above it, and the cut cascade stays at or below 0 dB. + peak = dense_peak(expected, rate) + assert peak > 0 + assert peak - 0.01 <= precut <= math.ceil(peak) + 1, ( + rate, + strength, + precut, + peak, + ) + cut = 10 ** (-precut / 200) + for i, (stage, ref) in enumerate(zip(out, expected, strict=True)): + scale = cut if i == 0 else 1 + for k, (a, b) in enumerate(zip(stage, ref, strict=True)): + b = b * scale if k < 3 else b + assert abs(a / SCALE - b) <= 2 / SCALE, ( + rate, + strength, + i, + list(stage), + ref, + ) + quantized = [[c / SCALE for c in stage] for stage in out] + assert dense_peak(quantized, rate) <= 0.05 + # The bells sit where the design says, scaled by the strength. + lift = 100 * math.log10(power(expected, 64, rate)) + assert abs(lift - scaled(53, 25 * strength)) < 8, (strength, lift) + cut_7k5 = 100 * math.log10(power(expected, 7500, rate)) + assert abs(cut_7k5 - scaled(-82, 25 * strength)) < 12, (strength, cut_7k5) + # 100 % is Rockbox's gains, 25 % a quarter of them in decibels. + assert reference(FULL, rate)[1] == peaking(64, 28, 53, rate) + assert reference(1, rate)[1] == peaking(64, 28, 13, rate) + assert reference(1, rate)[3] == peaking(7500, 43, -21, rate) + precut = ctypes.c_uint() + assert design(Bank(), precut, STRENGTHS, 44100) == 0 + assert design(Bank(), precut, 1, 32000) == 0 + + +def label_tests(dll): + labels = strings(dll, "strength_labels", STRENGTHS) + assert labels == ["Off", "25 %", "50 %", "75 %", "100 %"] + + +def tone_tests(dll): + """At 100 % a full-scale 2 kHz tone, the strongest lift, stays inside full + scale under the precut, and comes out at the design's level once the + filters and the limiter have settled.""" + publish = dll.bass_publish + publish.argtypes = [ctypes.POINTER(Set)] + publish.restype = None + process = dll.bass_process + process.argtypes = [ctypes.POINTER(ctypes.c_int16)] + [ctypes.c_uint32] * 2 + process.restype = None + chosen = Set(strength=FULL) + for bank, rate in enumerate(RATES): + bank_out, _ = designed(dll, FULL, rate) + ctypes.memmove(chosen.coefficients[bank], bank_out, ctypes.sizeof(Bank)) + publish(chosen) + frames = 8192 + tone = [ + round(32767 * math.sin(2 * math.pi * 2000 * i / 44100)) for i in range(frames) + ] + buffer = (ctypes.c_int16 * (2 * frames))(*[s for s in tone for _ in range(2)]) + process(buffer, frames, 44100) + peak = max(abs(buffer[2 * i]) for i in range(frames // 2, frames)) + assert peak <= 32767 + bank_out, _ = designed(dll, FULL, 44100) + quantized = [[c / SCALE for c in stage] for stage in bank_out] + designed_tenths = 100 * math.log10(power(quantized, 2000, 44100)) + assert abs(200 * math.log10(peak / 32767) - designed_tenths) < 3, ( + peak, + designed_tenths, + ) + + +def response_tests(dll): + """The editor's curve of each strength is the cut design's response, so it + peaks at 0 dB or just below.""" + response = dll.rv_dsp_response + response.argtypes = [ctypes.POINTER(Biquad), ctypes.c_uint, ctypes.c_uint] + response.argtypes += [ctypes.POINTER(ctypes.c_int16), ctypes.c_uint] + response.restype = None + points = 261 + hertz = [20 * 1000 ** (i / (points - 1)) for i in range(points)] + for strength in range(1, STRENGTHS): + bank, precut = designed(dll, strength, 44100) + curve = (ctypes.c_int16 * points)() + response(bank, STAGES, 44100, curve, points) + expected = reference(strength, 44100) + for hz, tenths in zip(hertz, curve, strict=True): + model = 100 * math.log10(power(expected, hz, 44100)) - precut + assert abs(tenths - model) <= 1, (hz, tenths, model) + assert -5 <= max(curve) <= 0 and min(curve) >= -240 + + +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="bass-enhancement-tests-") as name: + work = Path(name) + sources = ( + [root / "host.c", sdk / "rv_libc.c"] + + [dsp / name for name in ("math.c", "limiter.c", "filter.c", "cascade.c")] + + [shared / "bank.c"] + + [root.parent / name for name in ("design.c", "modes.c")] + ) + includes = [sdk, dsp, shared, root.parent] + dll = build(work, "bass-enhancement.so", sources, includes, "-DBANK_STAGES=5") + design_tests(dll) + label_tests(dll) + response_tests(dll) + tone_tests(dll) +print("Bass Enhancement tests passed") diff --git a/extensions/channels/Makefile b/extensions/channels/Makefile new file mode 100644 index 0000000..32fe15e --- /dev/null +++ b/extensions/channels/Makefile @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c channels.c modes.c +editor_SOURCES := editor.c labels.c modes.c +include $(SDK)/rv.mk diff --git a/extensions/channels/README.md b/extensions/channels/README.md new file mode 100644 index 0000000..63709f5 --- /dev/null +++ b/extensions/channels/README.md @@ -0,0 +1,27 @@ +# Channels + +Ported from Rockbox's channel modes (`lib/rbcodec/dsp/channel_mode.c`) by Thom Johansen and Michael Sevakis, GPL-2.0-or-later. + +Narrows or widens the stereo image by mixing part of each channel into the other, and plays Mono, one channel in both ears, Karaoke or swapped channels. Runs on the shared [output stage](https://github.com/paviro/revola/blob/main/docs/sdk/audio.md) after Crossfeed and before the Compressor. + +Settings > Channels draws the stereo image as a lobe in a half disc, with the two values below. The wheel picks a value, Select edits it, holding Select resets it, Menu goes back. Changes apply immediately and are saved. The Settings pane shows the mode, or the width under Custom. + +| Mode | What plays | +|---|---| +| Stereo | nothing changes | +| Mono | both ears hear the average of the channels | +| Left Only | both ears hear the left channel | +| Right Only | both ears hear the right channel | +| Karaoke | the difference between the channels, which drops a voice mixed in the centre | +| Swap | the channels exchanged | +| Custom | the image at Width: 0 to 250 % in 5 % steps, 100 % by default | + +Below 100 % part of each channel is added to the other, down to Mono at 0 %. Above 100 % part of each channel is subtracted from the other. No width clips. + +The Channels row sits after Sound Check, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise. Stereo costs nothing per sample. + +| | | +|---|---| +| Default | off | +| Memory | image only | +| Settings | mode and width | diff --git a/extensions/channels/assets/render.py b/extensions/channels/assets/render.py new file mode 100644 index 0000000..de906bd --- /dev/null +++ b/extensions/channels/assets/render.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render settings-channels.png, the Settings pane icon: the editor's half +disc with a lobe inside it on a 78 x 121 gray coverage mask in the style of the +stock Settings icons, lit from the top and mirrored in a fading reflection +below. Drawing uses ImageMagick's `magick`. + + python3 assets/render.py + python3 assets/render.py --check +""" + +import math +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import HEIGHT, WIDTH, canvas, icon, main + +OUT = HERE / "settings-channels.png" +# The half disc: a ring about CENTRE, the upper half only. +CENTRE = (39, 50) +OUTER, INNER = 26, 22 +# The lobe: a quarter-circle fan from the centre, LOBE from it, between the +# arms at 45 degrees. +LOBE = 18 + + +def fan(): + """Points along the lobe's arc between the arms, left to right.""" + cx, cy = CENTRE + points = [] + for step in range(0, 91, 3): + t = math.radians(225 + step) + points.append(f"{cx + LOBE * math.cos(t):.2f},{cy + LOBE * math.sin(t):.2f}") + return points + + +def shapes(): + """magick -draw arguments for the half disc and lobe, white on black.""" + cx, cy = CENTRE + return [ + "-fill", + "white", + "-draw", + f"ellipse {cx},{cy} {OUTER},{OUTER} 180,360", + "-fill", + "black", + "-draw", + f"ellipse {cx},{cy} {INNER},{INNER} 180,360", + "-draw", + f"rectangle 0,{cy} {WIDTH},{HEIGHT}", + "-fill", + "white", + "-draw", + "polygon " + " ".join([f"{cx},{cy}", *fan()]), + ] + + +def render(out, work): + icon(out, work, canvas(*shapes()), CENTRE[1] - OUTER, CENTRE[1]) + + +if __name__ == "__main__": + main(__doc__, {OUT: render}) diff --git a/extensions/channels/assets/settings-channels.png b/extensions/channels/assets/settings-channels.png new file mode 100644 index 0000000000000000000000000000000000000000..d1a0454aef3d4a23c3b1649e7417e8b73a5d6b8b GIT binary patch literal 1243 zcmeAS@N?(olHy`uVBq!ia0vp^en4Ew0VEhU?en+-q!f}pf_xbms?-=58d?|_egTCV zUNA6}8Za=tN?>5Hn!&&zUNC1@pbb!hDaqU2h2ejD|C#+j9(#$WuPgg2ZXRB1L*<?)FK#IZ0z{pJ3&`{UVD8$g%%GA=z#8TV9z{akfBou?^xnz;`p)uuZSlQ3yRF!H z*qRR}82ky3IGvYKx#RW6_Dd%Z&7T~umgjT(zgxQPrr)aNPbP1+zmB{uGses0l%I- z&Y$~mdE7lI_6KLrhcE2jvynfc?vHN$JC}Ib12fCNdX;XRnAhOFo;Cd6KeGmI=d9FS zCr%VQe7qw5^yx46?KamY&ieiI)l>PjQxnDet~1B;z7&1Q#@;aVACp7v_k_nmYW7tN zIVQ+N^VeAI61w|Yy)pVP!^M4y`DH0F49CnE)X(d$-~C_5;IGmFW_gnz^>5#;-p^Qb zjp@z5TFbem%S5|sSrdM*e6ZM}PSB(8`r#{f=WF|_zT53Sz3uHpX@~Qi)-&F{obUMe z>y}*e6r-)HyXQ0O@iUwB3Odz`J$S3@;D2&zXGPgNfr*a{7;e^aF3U;Yp`m2GV(I3- z%(bhZPrbXi`Nrh6PtIqr?T_4A@>a>He%G#3d@NVY0=5=b#kt(dep%La;>abV?bp+9 z&yM!;?>KQz%4&7E%N+Fyx8HAkTYf`Acw(G(%yku|*6ed0?;1{*9msqf<>)f&Q0dyJ z*P7p-Kj*XZdzf%;?wm_e+uL4SxujhB%l6Z`d#miJ>Y~X?mju^k^Iw=~AG1;R+pQU2 zl|UUak*G zH#*A|v0~}t_tlDlTeq_Cv@b~A^~n22*JoadHNP8z z3UN$}mKwx{Fc*3SeDDeWvw2<>w+4fY@WE}Yjh{-lck3+Qyoe#|<;CtB-SbuNU3_Y9 Y#wO(QZ)1cuF#9ujy85}Sb4q9e0B7Pc%>V!Z literal 0 HcmV?d00001 diff --git a/extensions/channels/channels.c b/extensions/channels/channels.c new file mode 100644 index 0000000..7b4c830 --- /dev/null +++ b/extensions/channels/channels.c @@ -0,0 +1,154 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Ported from Rockbox lib/rbcodec/dsp/channel_mode.c. + * + * Copyright (C) 2006 Thom Johansen + * Copyright (C) 2012 Michael Sevakis + * Modified by the RevolaOS authors, 2026. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + */ + +/* Rockbox's channel modes on the native interleaved S16 output, in place. + * Custom mixes each channel with the other: below 100 % a part of the other + * channel is added, above it a part is taken away. Mono, Left Only, Right Only, + * Karaoke and Swap need no coefficients. + * + * The UI task leaves a set with interrupts masked and moves the generation; + * the pump task takes it over when it sees the generation move and fades the + * mode that played into the new one. Only the pump task touches what plays. + * The coefficients are Q15 and |gain| + |cross| is at most 32768, so a sample + * times the pair fits int32 and the output cannot leave S16: Thumb multiplies + * suffice. */ + +#include "channels.h" +#include "rv_audio.h" + +static const struct rv_api *api; + +static struct channels_set next; +static struct rv_handoff handoff; + +/* Pump task only. */ +struct channels_state { + struct channels_set set; + int32_t gain, cross; +}; +static struct channels_state playing, fading; +static struct rv_fade fade; + +void channels_start(const struct rv_api *core) +{ + api = core; +} + +void channels_publish(const struct channels_set *set) +{ + rv_handoff_publish(api, &handoff, &next, set, sizeof next); +} + +void channels_coefficients(unsigned int percent, int32_t *gain_out, int32_t *cross_out) +{ + int32_t w = (int32_t)((percent * 32768u + 50) / 100); + if (percent <= 100) { + /* (1 + w) / 2 and (1 - w) / 2. */ + *gain_out = (32768 + w) >> 1; + *cross_out = *gain_out - w; + } else { + /* (1 + w) / (2 w) and that less 1; the numerator pre-shifted by 14 + * stays below 2^31 up to 250 %. */ + *gain_out = (((32768 + w) << 14) + w / 2) / w; + *cross_out = *gain_out - 32768; + } +} + +/* Takes over the set the UI task left. A set left meanwhile moves the + * generation again, and the next call takes that one. */ +static void take(void) +{ + fading = playing; + rv_handoff_take(&handoff, &playing.set, &next, sizeof playing.set); + if (playing.set.mode == CHANNELS_CUSTOM) + channels_coefficients(5u * playing.set.width, &playing.gain, &playing.cross); + rv_fade_start(&fade, 0); +} + +static void custom(const struct channels_state *state, int16_t *samples, + uint32_t frames) +{ + const int32_t g = state->gain, c = state->cross; + for (int16_t *end = samples + frames * 2; samples < end; samples += 2) { + int32_t left = samples[0], right = samples[1]; + samples[0] = (int16_t)((left * g + right * c + 16384) >> 15); + samples[1] = (int16_t)((right * g + left * c + 16384) >> 15); + } +} + +static void mono(int16_t *samples, uint32_t frames) +{ + for (int16_t *end = samples + frames * 2; samples < end; samples += 2) { + int16_t mid = (int16_t)(samples[0] / 2 + samples[1] / 2); + samples[0] = mid; + samples[1] = mid; + } +} + +static void one_side(int16_t *samples, uint32_t frames, unsigned int heard) +{ + for (int16_t *end = samples + frames * 2; samples < end; samples += 2) + samples[heard ^ 1] = samples[heard]; +} + +static void karaoke(int16_t *samples, uint32_t frames) +{ + for (int16_t *end = samples + frames * 2; samples < end; samples += 2) { + int16_t side = (int16_t)(samples[0] / 2 - samples[1] / 2); + samples[0] = side; + samples[1] = (int16_t)-side; + } +} + +static void swap(int16_t *samples, uint32_t frames) +{ + for (int16_t *end = samples + frames * 2; samples < end; samples += 2) { + int16_t left = samples[0]; + samples[0] = samples[1]; + samples[1] = left; + } +} + +static void run(void *state, int16_t *samples, uint32_t frames) +{ + switch (((struct channels_state *)state)->set.mode) { + case CHANNELS_MONO: + mono(samples, frames); + break; + case CHANNELS_LEFT: + one_side(samples, frames, 0); + break; + case CHANNELS_RIGHT: + one_side(samples, frames, 1); + break; + case CHANNELS_KARAOKE: + karaoke(samples, frames); + break; + case CHANNELS_SWAP: + swap(samples, frames); + break; + case CHANNELS_CUSTOM: + custom(state, samples, frames); + break; + default: + break; + } +} + +void channels_process(int16_t *samples, uint32_t frames) +{ + if (rv_handoff_pending(&handoff)) + take(); + rv_fade_run(&fade, run, &playing, &fading, samples, frames); +} diff --git a/extensions/channels/channels.h b/extensions/channels/channels.h new file mode 100644 index 0000000..1336985 --- /dev/null +++ b/extensions/channels/channels.h @@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef CHANNELS_H +#define CHANNELS_H + +#include + +struct rv_api; + +enum { + CHANNELS_STEREO, + CHANNELS_MONO, + CHANNELS_LEFT, + CHANNELS_RIGHT, + CHANNELS_KARAOKE, + CHANNELS_SWAP, + CHANNELS_CUSTOM, + CHANNELS_MODES, +}; + +/* What the settings say: the mode, and the Custom width as an index, 5 % per + * step from 0 to 250 %. */ +struct channels_set { + uint8_t mode; + uint8_t width; +}; + +/* Rockbox's width as Q15: `gain` for a channel's own sample, `cross` for the + * other's. |gain| + |cross| never exceeds 32768. */ +void channels_coefficients(unsigned int percent, int32_t *gain, int32_t *cross); + +/* `publish` leaves a set for the pump task from any task; `process` runs the + * set that plays on `frames` interleaved stereo S16 frames in place, on the pump + * task only. */ +void channels_start(const struct rv_api *core); +void channels_publish(const struct channels_set *set); +void channels_process(int16_t *samples, uint32_t frames); + +#endif diff --git a/extensions/channels/editor.c b/extensions/channels/editor.c new file mode 100644 index 0000000..971ea3a --- /dev/null +++ b/extensions/channels/editor.c @@ -0,0 +1,258 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Channels screen: the stereo image as a half disc, Left and Right at + * its arms, with a lobe as wide as the chosen mode and width leave it. The + * wheel picks Mode or Width, Select edits it, holding Select puts it back to + * its default and Menu steps back out. Every change plays at once. */ + +#include "labels.h" +#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_PARAMETER, DEPTH_EDIT, DEPTHS }; + +static const char *const titles[PARAM_COUNT] = {"Mode", "Width"}; +static const uint8_t keys[PARAM_COUNT] = {KEY_MODE, KEY_WIDTH}; +static const uint8_t counts[PARAM_COUNT] = {CHANNELS_MODES, WIDTH_LABELS}; +static const uint8_t defaults[PARAM_COUNT] = {MODE_DEFAULT, WIDTH_DEFAULT}; + +enum { + CENTRE_Y = 154, /* the listener; the baseline of the half disc */ + RADIUS = 110, + TAG_RADIUS = RADIUS + 14, /* the L and R tags sit just outside the arc */ + TAG_SIZE = 18, + CELL_TOP = 169, /* the cells run to the bottom of the canvas */ +}; + +static struct { + struct rv_editor input; + int parameter; +} editor; + +static int value(int parameter) +{ + return rv_clamp(api->setting_get_int(self, keys[parameter]), 0, + counts[parameter] - 1); +} + +static int isqrt(int n) +{ + int r = 0; + while ((r + 1) * (r + 1) <= n) + r++; + return r; +} + +/* The image the mode draws: a lobe of this width in percent, or none, and the + * channel each arm of it plays. Mono, Left Only and Right Only are a width of + * 0; Karaoke is pure side, drawn along the baseline instead. */ +struct image { + int lobe; /* a lobe is drawn */ + int width; /* percent */ + int baseline; /* Karaoke's line along the baseline */ + const char *left_tag, *right_tag; /* at the lobe's arms, NULL for none */ + const char *top_tag; /* above a centre line, NULL for none */ +}; + +static struct image image_of(int mode, int width_index) +{ + struct image image = {.lobe = 1, .width = 100, .left_tag = "L", .right_tag = "R"}; + switch (mode) { + case CHANNELS_MONO: + image.width = 0; + image.left_tag = image.right_tag = NULL; + break; + case CHANNELS_LEFT: + case CHANNELS_RIGHT: + image.width = 0; + image.left_tag = image.right_tag = NULL; + image.top_tag = mode == CHANNELS_LEFT ? "L" : "R"; + break; + case CHANNELS_KARAOKE: + image.lobe = 0; + image.baseline = 1; + image.left_tag = image.right_tag = NULL; + break; + case CHANNELS_SWAP: + image.left_tag = "R"; + image.right_tag = "L"; + break; + case CHANNELS_CUSTOM: + image.width = (int)width_percent(width_index); + break; + default: + break; + } + return image; +} + +/* A tag centred on (x, y). */ +static void tag(const struct rv_canvas *c, int x, int y, const char *text) +{ + rv_canvas_text(c, x - TAG_SIZE / 2, y - TAG_SIZE / 2, TAG_SIZE, TAG_SIZE, text, 0, + RV_ALIGN_CENTER, RV_CANVAS_ACCENT); +} + +/* A curve's two sides on one row, each a run from where it was on the row + * below to where it is now, so a flat stretch stays joined. */ +static void sides(const struct rv_canvas *c, int y, int from, int to, int thickness, + uint8_t color) +{ + int centre = c->width / 2; + int near = from < to ? from : to; + int far = from > to ? from : to; + rv_canvas_rect(c, centre - far - thickness + 1, y, far - near + thickness, 1, + color); + rv_canvas_rect(c, centre + near, y, far - near + thickness, 1, color); +} + +/* The half disc row by row: the arc and the 45-degree arms of the Stereo frame + * in the grid colour, then the lobe, whose edge a hard-panned source sits on, + * at tan(angle) = width / 100 from the centre line, held inside the arc. */ +static void draw_image(const struct rv_canvas *c, const struct image *image) +{ + int centre = c->width / 2; + rv_canvas_header(c, "Stereo image", NULL, 0); + int d_below = RADIUS, e_below = 0; + for (int h = 1; h <= RADIUS; h++) { + int y = CENTRE_Y - h; + int d = isqrt(RADIUS * RADIUS - h * h); + sides(c, y, d_below, d, 1, RV_CANVAS_GRID); + if (image->lobe) { + int e = h * image->width / 100; + if (e > d) + e = d; + rv_canvas_rect(c, centre - e, y, 2 * e + 1, 1, RV_CANVAS_SELECTION); + if (h <= d) + sides(c, y, h, h, 1, RV_CANVAS_GRID); + sides(c, y, h == 1 ? e : e_below, e, 2, RV_CANVAS_ACCENT); + e_below = e; + } else if (h <= d) { + sides(c, y, h, h, 1, RV_CANVAS_GRID); + } + d_below = d; + } + rv_canvas_rect(c, centre - RADIUS, CENTRE_Y, 2 * RADIUS + 1, 1, RV_CANVAS_GRID); + if (image->baseline) + rv_canvas_rect(c, centre - RADIUS, CENTRE_Y - 1, 2 * RADIUS + 1, 2, + RV_CANVAS_ACCENT); + + /* The arm tags follow the lobe's edge out past the arc; at 0 % they would + * meet, so they keep a little apart. */ + if (image->left_tag) { + int w = image->width; + int h = isqrt(TAG_RADIUS * TAG_RADIUS * 10000 / (10000 + w * w)); + int x = h * w / 100; + if (x < TAG_SIZE / 2) + x = TAG_SIZE / 2; + tag(c, centre - x, CENTRE_Y - h, image->left_tag); + tag(c, centre + x, CENTRE_Y - h, image->right_tag); + } + if (image->top_tag) + tag(c, centre, CENTRE_Y - TAG_RADIUS, image->top_tag); +} + +/* The Width cell reads inactive while another mode than Custom plays it no part. */ +static void draw_parameters(const struct rv_canvas *c, int custom) +{ + char text[PARAM_COUNT][LABEL_BYTES]; + const char *values[PARAM_COUNT]; + uint8_t states[PARAM_COUNT]; + for (int parameter = 0; parameter < PARAM_COUNT; parameter++) { + values[parameter] = + channels_label(parameter, value(parameter), text[parameter]); + states[parameter] = parameter != editor.parameter ? RV_CELL_IDLE + : editor.input.depth == DEPTH_EDIT ? RV_CELL_EDITING + : RV_CELL_SELECTED; + if (!custom && parameter != PARAM_MODE) + states[parameter] |= RV_CELL_MUTED; + } + rv_canvas_cells(c, CELL_TOP, c->height - CELL_TOP, titles, values, states, + PARAM_COUNT); +} + +static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width, + int height) +{ + struct rv_canvas c; + (void)ctx; + rv_canvas_begin(&c, g, width, height); + int mode = value(PARAM_MODE); + struct image image = image_of(mode, value(PARAM_WIDTH)); + draw_image(&c, &image); + draw_parameters(&c, mode == CHANNELS_CUSTOM); +} + +static void wheel(int delta) +{ + if (editor.input.depth == DEPTH_PARAMETER) { + editor.parameter = rv_clamp(editor.parameter + delta, 0, PARAM_COUNT - 1); + return; + } + int previous = value(editor.parameter); + int next = rv_clamp(previous + delta, 0, counts[editor.parameter] - 1); + if (next == previous) + return; + /* Main republishes from setting_changed, so the change plays at once. */ + api->setting_set_int(self, keys[editor.parameter], next); +} + +/* A held Select puts the highlighted value back to its default. */ +static void reset(void) +{ + if (value(editor.parameter) == defaults[editor.parameter]) + return; + /* Main republishes from setting_changed, so the change plays at once. */ + api->setting_set_int(self, keys[editor.parameter], defaults[editor.parameter]); +} + +static int input(const struct rv_context *ctx, const struct rv_input *input) +{ + (void)ctx; + switch (rv_editor_input(&editor.input, input)) { + case RV_EDITOR_IGNORED: + return 0; + case RV_EDITOR_CONSUMED: + return 1; + case RV_EDITOR_WHEEL: + wheel(input->delta); + break; + case RV_EDITOR_RESET: + reset(); + break; + default: + 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 const struct rv_screen screens[] = { + RV_SCREEN_CANVAS("editor", "Channels", draw, input, + .transition = RV_TRANSITION_FROM_PANE, .opened = opened), +}; + +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/channels/labels.c b/extensions/channels/labels.c new file mode 100644 index 0000000..5ed2b71 --- /dev/null +++ b/extensions/channels/labels.c @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "labels.h" +#include "rv_libc.h" + +const char *channels_label(int parameter, int index, char out[LABEL_BYTES]) +{ + if (parameter == PARAM_MODE) + return mode_labels[index]; + rv_format_int(out, LABEL_BYTES, (int)width_percent(index), " %"); + return out; +} diff --git a/extensions/channels/labels.h b/extensions/channels/labels.h new file mode 100644 index 0000000..3af4e7a --- /dev/null +++ b/extensions/channels/labels.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef CHANNELS_LABELS_H +#define CHANNELS_LABELS_H + +#include "modes.h" +#include "shared.h" + +/* The editor's values in wheel order. */ +enum { PARAM_MODE, PARAM_WIDTH, PARAM_COUNT }; + +enum { LABEL_BYTES = 6 }; /* "250 %" */ + +/* Value `index` of `parameter` as the editor shows it: a constant, or + * formatted into `out`. */ +const char *channels_label(int parameter, int index, char out[LABEL_BYTES]); + +#endif diff --git a/extensions/channels/listing.toml b/extensions/channels/listing.toml new file mode 100644 index 0000000..4a02c54 --- /dev/null +++ b/extensions/channels/listing.toml @@ -0,0 +1,5 @@ +details = "Open Settings > Channels to narrow or widen the stereo image, or play Mono, one channel in both ears, Karaoke or swapped channels." + +[[screenshots]] +file = "screenshots/editor.png" +alt = "The Channels editor with the stereo image plot above Mode and Width." diff --git a/extensions/channels/main.c b/extensions/channels/main.c new file mode 100644 index 0000000..9e35801 --- /dev/null +++ b/extensions/channels/main.c @@ -0,0 +1,94 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Channels: Settings > Channels opens the editor screen, which chooses + * the mode and shapes the Custom width. The output-stage hook runs what is + * chosen on every buffer, after Crossfeed and before the Compressor. */ + +#include "modes.h" +#include "rv_api.h" +#include "rv_audio.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +static const struct rv_setting settings[] = { + RV_SETTING_INT(KEY_MODE, "Channels", MODE_DEFAULT, CHANNELS_STEREO, + CHANNELS_CUSTOM), + RV_SETTING_INT(KEY_WIDTH, NULL, WIDTH_DEFAULT, 0, WIDTH_LABELS - 1), +}; + +/* Leaves what the settings say for the pump task. */ +static void publish(void) +{ + struct channels_set set = { + .mode = (uint8_t)api->setting_get_int(self, KEY_MODE), + .width = (uint8_t)api->setting_get_int(self, KEY_WIDTH), + }; + channels_publish(&set); +} + +static void setting_changed(uint16_t key) +{ + (void)key; + publish(); +} + +/* The processed output before Apple submits it: (samples, frames, context). + * Only 16-bit stereo is touched; the mixes do not depend on the rate. */ +static uint32_t on_output(uint32_t samples, uint32_t frames, uint32_t context, + const void *next) +{ + uint32_t rate; + if (rv_audio_stereo16((const void *)context, frames, 0, UINT32_MAX, &rate)) + channels_process((int16_t *)samples, frames); + return api->hook_next(next, samples, frames, context, 0, 0, 0); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER_AT(RV_SITE_AudioOutputQueue_Get_call, on_output, + RV_AUDIO_STAGE_CHANNELS), +}; + +/* The Settings pane names the mode, or the width under Custom, as Apple's EQ + * row names its preset. */ +static const char *caption(const struct rv_context *ctx) +{ + static char text[8]; + (void)ctx; + int mode = api->setting_get_int(self, KEY_MODE); + if (mode != CHANNELS_CUSTOM) + return mode_labels[mode]; + rv_format(text, sizeof text, "%u %%", + width_percent(api->setting_get_int(self, KEY_WIDTH))); + return text; +} + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY( + RV_MENU_SETTINGS, RV_SETTINGS_SOUND_CHECK, RV_ROW_PUSH("Channels", "editor"), + .pane = + RV_PANE(.caption_text = caption, .bitmap = RV_BITMAP("settings-channels")), + .host = "sound-menu", .host_screen = "sound", .host_after = "sound-check"), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .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; + channels_start(core); + return &extension; +} diff --git a/extensions/channels/manifest.toml b/extensions/channels/manifest.toml new file mode 100644 index 0000000..34b592b --- /dev/null +++ b/extensions/channels/manifest.toml @@ -0,0 +1,24 @@ +id = "channels" +name = "Channels" +description = "Narrow or widen the stereo image, or play mono, one channel in both ears, karaoke or swapped channels." +version = "0.1.0" +author = "RevolaOS" +note = "Ported from Rockbox" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "effects" + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "editor" +trigger = "screen" +screens = ["editor"] + +[[asset]] +name = "settings-channels" +file = "assets/settings-channels.png" +pane = "icon" diff --git a/extensions/channels/modes.c b/extensions/channels/modes.c new file mode 100644 index 0000000..46cc839 --- /dev/null +++ b/extensions/channels/modes.c @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "modes.h" + +const char *const mode_labels[CHANNELS_MODES] = { + "Stereo", "Mono", "Left Only", "Right Only", "Karaoke", "Swap", "Custom", +}; diff --git a/extensions/channels/modes.h b/extensions/channels/modes.h new file mode 100644 index 0000000..6fa882b --- /dev/null +++ b/extensions/channels/modes.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef MODES_H +#define MODES_H + +#include "channels.h" + +/* The modes by name, for the Settings caption and the editor. */ +extern const char *const mode_labels[CHANNELS_MODES]; + +#endif diff --git a/extensions/channels/screenshots/editor.png b/extensions/channels/screenshots/editor.png new file mode 100644 index 0000000000000000000000000000000000000000..3f5acec046ad937030f8bac3326bb6dfbbf1bfb7 GIT binary patch literal 8812 zcmcI~Ra9I}5awlY36S8yCAbC1kl;S};6Z{U1b25CBuLOO5G1&}2e%MNU~maea36xZ z?EJgu?9=W!`?4?hc9(SbxwpEy>Z^{@P=`FhdyWSHz!N1!IV}J{lR~wRa6qW%1C&z? z02lxzIcXj5Z^+CbYZ^%BN|%o??72qHwz`CGx5?tak6A|g30X!+Btf}XNvxZ935M?&toJ7*;yQ#>Pv=*=2ishkI6Vdd^?~%`76B z)MoP2qU`60I2}31b+msr{$^hvx*t!b^s4*XOj{9!TS^}cXGnF5`lzif6 zfzErSO#w0_9@^j(ovN_;%$@a+1k{kn!RFP)WQ%=65*PsN;9C+SYd!nT;tma9*QDtM zE%r9UI_j*_fSO|28Bk_<9-(8bQ~a&ozt^{by;)5?qJvNWGtYp@{I?F;obL^mzdM}` zv`wVj%Dz9BP9^HbT0>V#d1CxkU9l+5p*=8@d1K+$r97(ZD|rybUcp$-7u)7a^qF;9 zQKL#JoDyc+qf`vApqgMumL)hrA}>y^j(qxDHAA2&DZS#EOrDhvmsR16Xnmh-;q9y5 zgF*v~=2h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`MvG$G(T5joh*LA3^u-qMcjiVV`6%`(qySDIRoc9-1*9N6F=n z|7}rhc0J$wAw7qGk?jV#iFX&J@RJ(dIWW~f`ioT<)O7zX#$C1UVJ;6oA*tCdyNN<1z0anZ5p{UsA?`XiyDizRZGMI!@o#EV zhlhS)-GlLg4;rXKW%_rx!5cgDQ;)vM>t_}1 z6iCZ}JIikX literal 0 HcmV?d00001 diff --git a/extensions/channels/shared.h b/extensions/channels/shared.h new file mode 100644 index 0000000..433ff43 --- /dev/null +++ b/extensions/channels/shared.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the two modules of Channels agree on. */ + +#ifndef CHANNELS_SHARED_H +#define CHANNELS_SHARED_H + +#include "channels.h" + +enum { + KEY_MODE = 1, /* int: CHANNELS_STEREO to CHANNELS_CUSTOM */ + KEY_WIDTH, /* int: indexes into labels.c; 5 % per step */ +}; + +enum { + WIDTH_LABELS = 51, + WIDTH_DEFAULT = 20, /* 100 % */ + MODE_DEFAULT = CHANNELS_STEREO, +}; + +static inline unsigned int width_percent(int index) +{ + return 5 * (unsigned int)index; +} + +#endif diff --git a/extensions/channels/tests/host.c b/extensions/channels/tests/host.c new file mode 100644 index 0000000..12ba2ed --- /dev/null +++ b/extensions/channels/tests/host.c @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The rv_api the host tests hand channels.c: interrupt masking that counts. */ + +#include "rv_api.h" +#include "channels.h" + +static uint32_t irq_calls; + +static uint32_t irq_save(void) +{ + irq_calls++; + return 0; +} + +static void irq_restore(uint32_t state) +{ + (void)state; + irq_calls++; +} + +uint32_t test_irq_calls(void) +{ + return irq_calls; +} + +static const struct rv_api api = { + .size = sizeof api, .irq_save = irq_save, .irq_restore = irq_restore}; + +__attribute__((constructor)) static void start(void) +{ + channels_start(&api); +} diff --git a/extensions/channels/tests/run.py b/extensions/channels/tests/run.py new file mode 100644 index 0000000..0039727 --- /dev/null +++ b/extensions/channels/tests/run.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the host tests with a staged SDK: python3 tests/run.py SDK. + +The reference models follow Rockbox lib/rbcodec/dsp/channel_mode.c +(Copyright (C) 2006 Thom Johansen, 2012 Michael Sevakis). Modified by the +RevolaOS authors, 2026. Rockbox is GPL-2.0-or-later; this version is +GPL-3.0-only. +""" + +import ctypes +import sys +import tempfile +from itertools import pairwise +from pathlib import Path + +root = Path(__file__).resolve().parent +dsp = root.parents[1] / "dsp" +sys.path.insert(0, str(dsp / "tests")) +from harness import build, labeller, strings # noqa: E402 +from harness import noise as stereo_noise # noqa: E402 + +Q15 = 1 << 15 +WIDTHS = range(0, 255, 5) +MODES = ["Stereo", "Mono", "Left Only", "Right Only", "Karaoke", "Swap", "Custom"] +STEREO, MONO, LEFT, RIGHT, KARAOKE, SWAP, CUSTOM = range(7) + + +class Set(ctypes.Structure): + _fields_ = [("mode", ctypes.c_uint8), ("width", ctypes.c_uint8)] + + +def reference_coefficients(percent): + """Rockbox's width in floating point, as Q15.""" + w = percent / 100 + if percent <= 100: + gain, cross = (1 + w) / 2, (1 - w) / 2 + else: + gain = (1 + w) / (2 * w) + cross = gain - 1 + return gain * Q15, cross * Q15 + + +def rockbox_coefficients(percent): + """Rockbox's integer design (channel_mode_custom_set_width), as Q15.""" + width = percent * 0x7FFFFF // 100 + if percent <= 100: + straight = (0x7FFFFF + width) // 2 + cross = straight - width + else: + straight = ((0x7FFFFF + width) << 22) // width + cross = straight - 0x7FFFFF + return (straight << 8) >> 16, (cross << 8) >> 16 + + +def coefficient_tests(dll): + coefficients = dll.channels_coefficients + coefficients.argtypes = [ctypes.c_uint] + [ctypes.POINTER(ctypes.c_int32)] * 2 + coefficients.restype = None + + def designed(percent): + gain, cross = ctypes.c_int32(), ctypes.c_int32() + coefficients(percent, gain, cross) + return gain.value, cross.value + + for percent in WIDTHS: + gain, cross = designed(percent) + for actual, expected in zip((gain, cross), reference_coefficients(percent)): + assert abs(actual - expected) <= 1, (percent, actual, expected) + for actual, expected in zip((gain, cross), rockbox_coefficients(percent)): + assert abs(actual - expected) <= 2, (percent, actual, expected) + assert abs(gain) + abs(cross) <= Q15, (percent, gain, cross) + assert designed(100) == (Q15, 0) + assert designed(0) == (Q15 // 2, Q15 // 2) + assert designed(250) == (22938, -9830) + + +def label_tests(dll): + labels = labeller(dll.channels_label) + assert strings(dll, "mode_labels", 7) == MODES + assert labels(0, 7) == MODES + widths = labels(1, 51) + assert widths == [f"{5 * i} %" for i in range(51)] + assert widths[20] == "100 %" + + +def truncate(value): + """C's division by two: toward zero.""" + return int(value / 2) + + +def model(mode, frames, gain=0, cross=0): + out = [] + for left, right in frames: + if mode == STEREO: + out.append((left, right)) + elif mode == MONO: + mid = truncate(left) + truncate(right) + out.append((mid, mid)) + elif mode == LEFT: + out.append((left, left)) + elif mode == RIGHT: + out.append((right, right)) + elif mode == KARAOKE: + side = truncate(left) - truncate(right) + out.append((side, -side)) + elif mode == SWAP: + out.append((right, left)) + else: + out.append( + ( + (left * gain + right * cross + 16384) >> 15, + (right * gain + left * cross + 16384) >> 15, + ) + ) + return out + + +def noise(count, seed): + """Independent noise on each channel, with a hard-panned first frame.""" + frames = stereo_noise(count, seed) + frames[0] = (32767, 0) + return frames + + +FADE = 128 + + +def faded(old, new): + """What rv_fade plays after a take: old blended into new over the first FADE + frames at weights 1 to FADE, floor-shifted as C's arithmetic shift does, then new.""" + out = [] + for i, (a, b) in enumerate(zip(old, new)): + weight = min(i + 1, FADE) + out.append(tuple((x * (FADE - weight) + y * weight) >> 7 for x, y in zip(a, b))) + return out + + +def process_tests(dll): + publish = dll.channels_publish + publish.argtypes = [ctypes.POINTER(Set)] + publish.restype = None + process = dll.channels_process + process.argtypes = [ctypes.POINTER(ctypes.c_int16), ctypes.c_uint32] + process.restype = None + coefficients = dll.channels_coefficients + coefficients.argtypes = [ctypes.c_uint] + [ctypes.POINTER(ctypes.c_int32)] * 2 + coefficients.restype = None + dll.test_irq_calls.restype = ctypes.c_uint32 + count = 512 + + def run(frames, *splits): + """Processes the frames in one buffer, or in buffers cut at the splits.""" + buffer = (ctypes.c_int16 * (2 * len(frames)))( + *[s for frame in frames for s in frame] + ) + edges = [0, *splits, len(frames)] + for first, last in pairwise(edges): + process( + ctypes.cast(ctypes.byref(buffer, 4 * first), process.argtypes[0]), + last - first, + ) + return [(buffer[2 * i], buffer[2 * i + 1]) for i in range(len(frames))] + + def designed(percent): + gain, cross = ctypes.c_int32(), ctypes.c_int32() + coefficients(percent, gain, cross) + return gain.value, cross.value + + # What plays and, after a take, what fades out: (mode, gain, cross). + players = {"new": (STEREO, 0, 0), "old": None} + + def switch(mode, width=0): + """Publishes a set; `expected` then fades from the mode that played.""" + publish(Set(mode=mode, width=width)) + players["old"] = players["new"] + players["new"] = ( + (mode, *designed(5 * width)) if mode == CUSTOM else (mode, 0, 0) + ) + + def expected(frames): + old, players["old"] = players["old"], None + new = players["new"] + return faded(model(old[0], frames, *old[1:]), model(new[0], frames, *new[1:])) + + def play(frames, *splits): + """Runs the frames and checks them against the model, returning them.""" + got = run(frames, *splits) + assert got == expected(frames), splits + return got + + # Stereo leaves the stream alone; one publish masks interrupts once. + switch(STEREO) + frames = noise(count, 1) + assert play(frames) == frames + assert dll.test_irq_calls() == 2 + + # Each fixed mode against its model, faded in from the last. + for mode in (MONO, LEFT, RIGHT, KARAOKE, SWAP): + switch(mode) + frames = noise(count, 2 + mode) + play(frames) + + # Custom at several widths; 100 % is the input bit for bit. + for index in (0, 10, 20, 30, 50): + switch(CUSTOM, index) + frames = noise(count, 20 + index) + play(frames) + if index == 20: + assert model(CUSTOM, frames, *designed(100)) == frames + + # No width can leave S16: the four corners at every width, unclamped model. + corners = [(32767, 32767), (32767, -32768), (-32768, 32767), (-32768, -32768)] + loud = (corners * (count // 4 + 1))[:count] + for index in range(51): + switch(CUSTOM, index) + plain = model(CUSTOM, loud, *designed(5 * index)) + assert all(-32768 <= s <= 32767 for frame in plain for s in frame), index + play(loud) + + # The latest set wins: one published after a process, and the last of two + # published before one, which fades from what played, not from the skipped set. + switch(MONO) + frames = noise(count, 90) + play(frames) + switch(SWAP) + frames = noise(count, 91) + play(frames) + publish(Set(mode=KARAOKE)) + switch(CUSTOM, 40) + frames = noise(count, 92) + play(frames) + + # A fade spans buffer edges, and ends after FADE frames whatever their size. + switch(CUSTOM, 10) + frames = noise(count, 93) + play(frames, 17, 100) + + # A set taken during a fade restarts the fade from the set that plays. + switch(KARAOKE) + frames = noise(64, 94) + play(frames) + switch(LEFT) + frames = noise(count, 95) + play(frames) + + +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="channels-tests-") as name: + work = Path(name) + sources = [root / "host.c", sdk / "rv_libc.c"] + [ + root.parent / name for name in ("channels.c", "labels.c", "modes.c") + ] + dll = build(work, "channels.so", sources, [sdk, sdk / "extension", root.parent]) + coefficient_tests(dll) + label_tests(dll) + process_tests(dll) +print("Channels tests passed") diff --git a/extensions/compressor/Makefile b/extensions/compressor/Makefile new file mode 100644 index 0000000..970fe6d --- /dev/null +++ b/extensions/compressor/Makefile @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c curve.c design.c +# Every frame is about nine 32 by 32 to 64 bit multiplies: one smull each in +# ARM, a library call each in Thumb. +main_ARM_SOURCES := compressor.c +editor_SOURCES := editor.c labels.c curve.c +include $(SDK)/rv.mk diff --git a/extensions/compressor/README.md b/extensions/compressor/README.md new file mode 100644 index 0000000..26cef32 --- /dev/null +++ b/extensions/compressor/README.md @@ -0,0 +1,27 @@ +# Compressor + +Ported from Rockbox's compressor (`lib/rbcodec/dsp/compressor.c`) by Jeffrey Goode, GPL-2.0-or-later. + +Turns loud passages down so quiet ones stay audible. Runs after Channels on the shared [output stage](https://github.com/paviro/revola/blob/main/docs/sdk/audio.md). + +Settings > Compressor plots output level against input level, with the switch and the six values below. The wheel picks a value, Select edits it, holding Select resets it, Menu goes back. Changes apply immediately and are saved. Switching off keeps the values. The Settings pane says Off or On. + +| Value | Range | Default | What it does | +|---|---|---|---| +| State | Off, On | Off | whether the compressor plays | +| Threshold | -3 to -24 dB in 3 dB steps | -12 dB | the level above which the gain comes down | +| Ratio | 2:1, 4:1, 6:1, 10:1, Limit | 4:1 | how much of a rise above the threshold still reaches the output; Limit holds it there | +| Knee | Hard, Soft | Soft | Soft eases the gain in over 3 dB either side of the threshold | +| Makeup | Off, Auto | Auto | Auto lifts the output back up by what a full-scale signal lost | +| Attack | 0 to 30 ms in 5 ms steps | 5 ms | how quickly the gain comes down | +| Release | 100 to 1000 ms in 100 ms steps | 500 ms | how quickly it comes back up | + +As in Rockbox, the gain follows the average of both channels with the treble weighted up. It acts on audio delayed by 3 ms, so Limit catches a peak before it plays. With Makeup on, a look-ahead limiter after the compressor keeps loud passages from clipping and adds about 0.7 ms of delay. + +The Compressor row sits after Sound Check, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise. Off costs nothing per sample. + +| | | +|---|---| +| Default | off | +| Memory | image only | +| Settings | the switch and the six values | diff --git a/extensions/compressor/assets/render.py b/extensions/compressor/assets/render.py new file mode 100644 index 0000000..bc2708a --- /dev/null +++ b/extensions/compressor/assets/render.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render settings-compressor.png, the Settings pane icon: a waveform pressed +flat against two bars, on a 78 x 121 gray coverage mask in the style of the +stock Settings icons, lit from the top and mirrored in a fading reflection +below. Drawing uses ImageMagick's `magick`. + + python3 assets/render.py + python3 assets/render.py --check +""" + +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import canvas, icon, main + +OUT = HERE / "settings-compressor.png" +# The two bars the waveform presses against, and the gap between them. +BAR_LEFT, BAR_RIGHT = 13, 65 +BAR_TOP, BAR_BOTTOM, BAR_HEIGHT, BAR_RADIUS = 12, 61, 3, 1.5 +GAP_TOP, GAP_BOTTOM = BAR_TOP + BAR_HEIGHT + 3, BAR_BOTTOM - 3 +# The waveform: bars of these full heights, centred in the gap and cut to it. +WAVE_HEIGHTS = (12, 24, 40, 52, 40, 24, 12) +WAVE_PITCH, WAVE_WIDTH, WAVE_RADIUS = 7.5, 4.5, 1.5 + + +def shapes(): + """magick -draw arguments for the glyph, white on black.""" + draw = ["-fill", "white"] + for top in (BAR_TOP, BAR_BOTTOM): + draw += [ + "-draw", + ( + f"roundrectangle {BAR_LEFT},{top} {BAR_RIGHT},{top + BAR_HEIGHT} " + f"{BAR_RADIUS},{BAR_RADIUS}" + ), + ] + centre = (GAP_TOP + GAP_BOTTOM) / 2 + first = (BAR_LEFT + BAR_RIGHT) / 2 - WAVE_PITCH * (len(WAVE_HEIGHTS) - 1) / 2 + for i, height in enumerate(WAVE_HEIGHTS): + half = min(height, GAP_BOTTOM - GAP_TOP) / 2 + left = first + i * WAVE_PITCH - WAVE_WIDTH / 2 + draw += [ + "-draw", + ( + f"roundrectangle {left:.2f},{centre - half:.2f} " + f"{left + WAVE_WIDTH:.2f},{centre + half:.2f} " + f"{WAVE_RADIUS},{WAVE_RADIUS}" + ), + ] + return draw + + +def render(out, work): + icon(out, work, canvas(*shapes()), BAR_TOP, BAR_BOTTOM + BAR_HEIGHT) + + +if __name__ == "__main__": + main(__doc__, {OUT: render}) diff --git a/extensions/compressor/assets/settings-compressor.png b/extensions/compressor/assets/settings-compressor.png new file mode 100644 index 0000000000000000000000000000000000000000..9955a2851601623d50640fe63971dd680bea0f07 GIT binary patch literal 1017 zcmeAS@N?(olHy`uVBq!ia0vp^en4Ew0VEhU?en+-q!f}pf_xbms?-=58d?|_egTCV zUNA6}8Za=tN?>5Hn!&&zUNC1@pbb!hDaqU2h2ejD|C#+j9(#$WuPgg2ZXO;JE|C}i zfr=SaOI#yLQW8s2t&)pUffR$0fsvW6p`os!QHY_Dm8p@Hp@Fu6ft7(l$5zJ)C>nC} zQ!>*kaclVb;-?N!g9hA&lFZ!H;*!MN0^EAm{k`!S=<2(kE{-7?_ufX@W=lH?)GpVT z_u}GCY`Ma^lWQfDX0pt6&DbSeGyXJQSt)ww){)p*TQYf9Iu|GxaImP)?YYcinUEr0 zG{M1q@}sh)w?DtVw@&G#(VgsR%V$>3nt3<+?z#pZNuxWe62wSLdVfA{V&%$PazsKvrVS-Q{PufK3=AHRU0qRbPCjkm<2Qy4V(CUs8@`+e_d z)qJ0~Pm}igFZ(>b+qZT9?Y#HDKHke-QF85cZoW}|UbpDMfHvt63+b-4LJg~)hIpj! zowGCYCI88qrzx^eoW#S|Z2bQ6_tiPo)A#(H_3}{H-UJ5mX-B=Db0qQKd? z4hxw`_twpdyA!>0CmCA5%$d;@G5KsTWAx6Y_j=t~7?gd>F3oCqB7ZC~`#|%xfX~+2 zYrh?>t4*B6mAQ4=2r<;GS%>4WDgPirE-|ueOwgO`& z<-`O}sY|>Zq^b^w{VA@s-bt>Q7!iamn0TYp>nxY&~}JsMqS+jT@&<^qKoKt<+iV+;5qd zk0(uH&#nF;5wj__>{6tDxSpWb)9jr_E}Kn4EM{-wW~cxLZ2I0iJ@0$ZYAe?^cc!PW z@pBdr&k=YgzvIG{H%ZYQGiPmT{`EJ^q^aJgTe~DWM4fhpW9v literal 0 HcmV?d00001 diff --git a/extensions/compressor/compressor.c b/extensions/compressor/compressor.c new file mode 100644 index 0000000..2120b66 --- /dev/null +++ b/extensions/compressor/compressor.c @@ -0,0 +1,202 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Ported from Rockbox lib/rbcodec/dsp/compressor.c. + * + * Copyright (C) 2009 Jeffrey Goode + * Modified by the RevolaOS authors, 2026. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + */ + +/* Rockbox's compressor on the native interleaved S16 output. The channels' + * mean goes through two high-pass filters that weight the treble, the result + * picks a gain from the curve, and that gain follows a one-pole attack or + * release. The gain applies to the samples of 3 ms ago, held in a delay line, + * so the curve's Limit ratio can pull the gain down before a peak plays. What + * makeup lifts past full scale goes to the SDK's limiter instead of Rockbox's + * fixed gain step. + * + * The UI task leaves a set with interrupts masked and moves the generation; + * the pump task takes it over when it sees the generation move and fades the + * state that played into the new one. Only the pump task touches what plays. + * Samples are S16 raised to Rockbox's 28 fractional bits, so its S7.24 gains + * and shifts apply unchanged. */ + +#include "compressor.h" +#include "rv_dsp.h" +#include "rv_libc.h" + +enum { + SAMPLE_SHIFT = 13, /* S16 to S3.28 */ + UNITY = 1 << 24, + DELAY_MS = 3, + DELAY_FRAMES = DELAY_MS * 48000 / 1000, /* at the highest rate */ +}; + +static struct compressor_set next; + +/* Pump task only. */ +struct compressor_state { + struct compressor_set set; + struct compressor_design design; + int32_t release_gain, release_holdoff; + int32_t hp_x1, hp1_y1, hp2_y1; + /* The delay line is exactly the look-ahead long: each frame reads the one + * it replaces. */ + int16_t delay[DELAY_FRAMES][2]; + uint32_t delay_index, delay_length; +}; +static struct compressor_state playing, fading; +static struct rv_effect effect; +static struct rv_limiter limiter; + +void compressor_start(const struct rv_api *core) +{ + effect.api = core; +} + +void compressor_publish(const struct compressor_set *set) +{ + rv_effect_publish(&effect, &next, set, sizeof next); +} + +/* a (S7.24) times b. */ +static inline int32_t scale(int32_t a, int32_t b) +{ + return (int32_t)(((int64_t)a * b) >> 24); +} + +static inline int32_t magnitude(int32_t sample) +{ + return sample < 0 ? -(sample + 1) : sample; +} + +static void reset(struct compressor_state *state, uint32_t rate) +{ + state->release_gain = UNITY; + state->hp_x1 = state->hp1_y1 = state->hp2_y1 = 0; + memset(state->delay, 0, sizeof state->delay); + state->delay_index = 0; + state->delay_length = DELAY_MS * rate / 1000; + state->release_holdoff = (int32_t)state->delay_length; +} + +/* Takes over the set the UI task left, fading from what played when the rate is + * the same. A set left meanwhile moves the generation again, and the next call + * takes that one; a set left while an on/off fade lasts waits for its end, + * which rv_effect_pending says. The state starts over when the compressor turns + * on or the rate changes, as in Rockbox; new values while it runs keep it. + * Turning on, the old state plays alone until the new delay line is full, so + * the fade blends into delayed samples, not into the silence the line held. A + * rate change comes with a track, so it ends a fade instead of starting one. */ +static void take(uint32_t rate) +{ + int was_on = playing.set.on, same_rate = rate == effect.rate; + if (same_rate) + fading = playing; + rv_handoff_take(&effect.handoff, &playing.set, &next, sizeof playing.set); + int on = playing.set.on; + if (on) { + compressor_design(&playing.design, &playing.set, rate); + if (!was_on || !same_rate) + reset(&playing, rate); + } + if (on && !was_on) + rv_limiter_rest(&limiter); + rv_effect_taken(&effect, rate, + on && !was_on ? playing.delay_length + RV_LIMITER_FRAMES : 0); +} + +/* The gain the curve gives a sidechain level, S7.24: between the two entries + * the level's top six bits pick, or up to two bits over full scale between the + * last two. -1 for a level further out. */ +static inline int32_t curve_gain(const struct compressor_design *design, int32_t level) +{ + const int32_t *gain = design->gain; + level = magnitude(level) >> SAMPLE_SHIFT; /* 15 fractional bits */ + if (level < 1 << 15) { + unsigned int index = (unsigned int)level >> 9; + int32_t rest = (level & 0x1ff) << 22; + return gain[index] - rv_fracmul(rest, gain[index] - gain[index + 1]); + } + if (level < 1 << 17) + return gain[64] - + rv_fracmul(((level - (1 << 15)) / 3) << 16, gain[64] - gain[65]); + return -1; +} + +/* ARM: every frame is about nine 32 by 32 to 64 bit multiplies, one smull + * each here, a library call each in Thumb. */ +static int run(void *instance, const int16_t *in, int32_t *out, uint32_t frames) +{ + struct compressor_state *state = instance; + if (!state->set.on) + return 0; + const struct compressor_design *design = &state->design; + int32_t gain_now = state->release_gain, holdoff = state->release_holdoff; + int32_t x1 = state->hp_x1, y1 = state->hp1_y1, y2 = state->hp2_y1; + int16_t (*delay)[2] = state->delay; + uint32_t index = state->delay_index, delay_length = state->delay_length; + for (const int16_t *end = in + frames * 2; in < end; in += 2, out += 2) { + int32_t left = (int32_t)in[0] * (1 << SAMPLE_SHIFT); + int32_t right = (int32_t)in[1] * (1 << SAMPLE_SHIFT); + int32_t x = (left + right) >> 1; + + /* y[n] = a (y[n-1] + x[n] - x[n-1]): the two high-pass filters, then + * x/2 + y1 + 2 y2, times 3/4. */ + y1 = scale(design->hp1, x - x1 + y1); + y2 = scale(design->hp2, x - x1 + y2); + x1 = x; + int32_t level = (x >> 1) + y1 + y2 * 2; + level >>= 1; + level += level >> 1; + int32_t wanted = curve_gain(design, level); + + if (wanted <= gain_now && wanted > 0) { + gain_now = design->attack_a == UNITY ? wanted + : scale(gain_now, design->attack_b) + + scale(wanted, design->attack_a); + /* No release before the delayed signal has passed the peak. */ + holdoff = (int32_t)delay_length; + } else if (holdoff > 0) { + holdoff--; + } else { + gain_now = + scale(gain_now, design->release_b) + scale(wanted, design->release_a); + } + + /* With makeup a loud passage can pass full scale; the limiter + * behind takes it back. */ + int32_t total = scale(gain_now, design->makeup); + int16_t delayed_left = delay[index][0], delayed_right = delay[index][1]; + delay[index][0] = in[0]; + delay[index][1] = in[1]; + if (++index >= delay_length) + index = 0; + if (total != UNITY) { + out[0] = (int32_t)(((int64_t)total * delayed_left + (1 << 23)) >> 24); + out[1] = (int32_t)(((int64_t)total * delayed_right + (1 << 23)) >> 24); + } else { + out[0] = delayed_left; + out[1] = delayed_right; + } + } + state->release_gain = gain_now; + state->release_holdoff = holdoff; + state->hp_x1 = x1; + state->hp1_y1 = y1; + state->hp2_y1 = y2; + state->delay_index = index; + return 1; +} + +void compressor_process(int16_t *samples, uint32_t frames, uint32_t rate) +{ + if (rv_effect_pending(&effect, rate)) + take(rate); + rv_fade_run_limited(&effect.fade, &limiter, run, &playing, &fading, samples, + frames); +} diff --git a/extensions/compressor/compressor.h b/extensions/compressor/compressor.h new file mode 100644 index 0000000..4e910e0 --- /dev/null +++ b/extensions/compressor/compressor.h @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef COMPRESSOR_H +#define COMPRESSOR_H + +#include + +struct rv_api; + +enum { RATIO_2, RATIO_4, RATIO_6, RATIO_10, RATIO_LIMIT, RATIO_COUNT }; + +/* What the settings say, in Rockbox's units: whether it plays, the threshold + * in whole decibels below full scale, makeup 1 for Auto, the ratio's index, + * knee 1 for Soft, and the attack and release times in milliseconds. */ +struct compressor_set { + uint8_t on; + int8_t threshold_db; + uint8_t makeup, ratio, knee; + uint16_t attack_ms, release_ms; +}; + +/* Rockbox's compression curve for a set, in S15.16 decibels: five input + * levels and the gain offset (0 or below) at each, straight between them, and + * the makeup gain added after. Index 0 is the bottom of the knee, 1 the + * threshold, 2 the top of the knee, 3 full scale and 4 two bits over it. */ +struct compressor_points { + int32_t db[5], offset[5]; + int32_t makeup; +}; + +/* A set at one sample rate, in Rockbox's formats: the gain, S7.24, by input + * level in steps of 1/64 of full scale (0 silence, 64 full scale, 65 two + * bits over), the makeup gain, and the one-pole coefficients of the attack, + * release and the two sidechain high-pass filters. */ +struct compressor_design { + int32_t gain[66]; + int32_t makeup; + int32_t attack_a, attack_b, release_a, release_b; + int32_t hp1, hp2; +}; + +/* curve.c */ +void compressor_points(const struct compressor_set *set, struct compressor_points *out); + +/* design.c */ +void compressor_design(struct compressor_design *out, const struct compressor_set *set, + unsigned int rate); + +/* compressor.c: `publish` leaves a set for the pump task from any task; + * `process` runs the set that plays on `frames` interleaved stereo S16 frames in + * place, on the pump task only. */ +void compressor_start(const struct rv_api *core); +void compressor_publish(const struct compressor_set *set); +void compressor_process(int16_t *samples, uint32_t frames, uint32_t rate); + +#endif diff --git a/extensions/compressor/curve.c b/extensions/compressor/curve.c new file mode 100644 index 0000000..3e94108 --- /dev/null +++ b/extensions/compressor/curve.c @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Ported from Rockbox lib/rbcodec/dsp/compressor.c. + * + * Copyright (C) 2009 Jeffrey Goode + * Modified by the RevolaOS authors, 2026. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + */ + +/* The shape of Rockbox's compression curve as decibels: no change below the + * knee, a straight run across the knee to its offset, then the ratio's slope + * up to full scale and two bits over. Both modules carry this; the editor + * plots it, design.c turns it into gains. */ + +#include "compressor.h" + +enum { + DB_ONE = 1 << 16, + KNEE_HALF_DB = 3, /* the soft knee spans the threshold +- 3 dB */ + OVER_DB = 0xC0A8C, /* two bits above full scale, about 12.04 dB */ + MAKEUP_HEADROOM = + 0x4AC4, /* Rockbox's margin under the full-scale offset, about 0.3 dB */ +}; + +/* The gain offset for a rise of `db` in input above the threshold: the input + * rises, the output rises by 1/ratio of it; Limit holds the output. */ +static int32_t slope(int32_t db, int ratio) +{ + return ratio ? -db * (ratio - 1) / ratio : -db; +} + +void compressor_points(const struct compressor_set *set, struct compressor_points *out) +{ + static const int8_t ratios[RATIO_COUNT] = {2, 4, 6, 10, 0}; + int ratio = ratios[set->ratio]; + int32_t threshold = set->threshold_db * DB_ONE; + int32_t knee = set->knee ? KNEE_HALF_DB * DB_ONE : 0; + + out->db[0] = threshold - knee; + out->db[1] = threshold; + out->db[2] = threshold + knee; + out->db[3] = 0; + out->db[4] = OVER_DB; + out->offset[0] = 0; + out->offset[2] = slope(knee, ratio); + out->offset[1] = out->offset[2] / 2; + out->offset[3] = slope(-threshold, ratio); + out->offset[4] = slope(OVER_DB, ratio) + out->offset[3]; + out->makeup = set->makeup ? -out->offset[3] - MAKEUP_HEADROOM : 0; +} diff --git a/extensions/compressor/design.c b/extensions/compressor/design.c new file mode 100644 index 0000000..ece12e9 --- /dev/null +++ b/extensions/compressor/design.c @@ -0,0 +1,115 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Ported from Rockbox lib/rbcodec/dsp/compressor.c. + * + * Copyright (C) 2009 Jeffrey Goode + * Modified by the RevolaOS authors, 2026. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + */ + +/* The curve as the pump task uses it: a gain for each of the 64 input levels + * the top six bits of a sample pick out, with the one-pole coefficients at the + * sample rate. Decibels become gains through 2^x: the whole part a shift, the + * fraction a short table, so no exponential is needed. */ + +#include "compressor.h" + +enum { + UNITY = 1 << 24, + /* The sidechain high-pass filters' 1/RC, as Rockbox writes them: cutoffs + * near 237 Hz and 2.18 kHz. */ + HP1_RC = 0x003C1, + HP2_RC = 0x02065, + /* 1000 * 10 / (20 log10 e): the time constant becomes a 10 dB change per period. */ + PER_TEN_DB = 1152, + LOG2_10_OVER_20_Q24 = 2786707, +}; + +/* -20 log10(i / 64) for i from 1 to 63, S15.16; entry 0 stands for silence. */ +static const uint32_t level_db[64] = { + 0x000000, 0x241FA4, 0x1E1A5E, 0x1A94C8, 0x181518, 0x1624EA, 0x148F82, 0x1338BD, + 0x120FD2, 0x1109EB, 0x101FA4, 0x0F4BB6, 0x0E8A3C, 0x0DD840, 0x0D3377, 0x0C9A0E, + 0x0C0A8C, 0x0B83BE, 0x0B04A5, 0x0A8C6C, 0x0A1A5E, 0x09ADE1, 0x094670, 0x08E398, + 0x0884F6, 0x082A30, 0x07D2FA, 0x077F0F, 0x072E31, 0x06E02A, 0x0694C8, 0x064BDF, + 0x060546, 0x05C0DA, 0x057E78, 0x053E03, 0x04FF5F, 0x04C273, 0x048726, 0x044D64, + 0x041518, 0x03DE30, 0x03A89B, 0x037448, 0x03412A, 0x030F32, 0x02DE52, 0x02AE80, + 0x027FB0, 0x0251D6, 0x0224EA, 0x01F8E2, 0x01CDB4, 0x01A359, 0x0179C9, 0x0150FC, + 0x0128EB, 0x010190, 0x00DAE4, 0x00B4E1, 0x008F82, 0x006AC1, 0x004699, 0x002305, +}; + +/* 2^(i / 64) for i from 0 to 64, Q30. */ +static const uint32_t pow2[65] = { + 1073741824, 1085434106, 1097253708, 1109202018, 1121280436, 1133490379, 1145833280, + 1158310587, 1170923762, 1183674286, 1196563654, 1209593378, 1222764986, 1236080024, + 1249540052, 1263146652, 1276901417, 1290805962, 1304861917, 1319070932, 1333434672, + 1347954824, 1362633090, 1377471191, 1392470869, 1407633882, 1422962010, 1438457051, + 1454120821, 1469955159, 1485961921, 1502142985, 1518500250, 1535035634, 1551751076, + 1568648537, 1585730000, 1602997467, 1620452965, 1638098541, 1655936265, 1673968228, + 1692196547, 1710623359, 1729250827, 1748081133, 1767116489, 1786359126, 1805811301, + 1825475297, 1845353420, 1865448001, 1885761398, 1906295993, 1927054196, 1948038440, + 1969251188, 1990694927, 2012372174, 2034285470, 2056437387, 2078830522, 2101467502, + 2124350982, 2147483648, +}; + +/* 10^(db / 20) as S7.24, for S15.16 decibels from -96 up to +36 dB. */ +static int32_t gain_from_db(int32_t db) +{ + int64_t x = + ((int64_t)db * LOG2_10_OVER_20_Q24) >> 24; /* log2 of the gain, S15.16 */ + int whole = (int)(x >> 16); + uint32_t fraction = (uint32_t)x & 0xffff; + uint32_t i = fraction >> 10, rest = fraction & 0x3ff; + uint32_t v = pow2[i] + (uint32_t)(((uint64_t)(pow2[i + 1] - pow2[i]) * rest) >> 10); + return (int32_t)(v >> (6 - whole)); +} + +/* Rockbox's one-pole coefficient for a 10 dB change over `ms`. */ +static int32_t per_ms_coefficient(unsigned int rate, unsigned int ms) +{ + return (int32_t)(UNITY / rate * PER_TEN_DB / ms); +} + +void compressor_design(struct compressor_design *out, const struct compressor_set *set, + unsigned int rate) +{ + struct compressor_points p; + compressor_points(set, &p); + + out->gain[0] = UNITY; + for (unsigned int i = 1; i < 64; i++) { + int32_t db = -(int32_t)level_db[i], offset; + if (db <= p.db[0]) { + offset = 0; + } else if (set->knee && db <= p.db[2]) { + /* Across the knee: its 6 dB width as a fraction, S15.16. */ + int32_t across = (db - p.db[0]) / 6; + offset = (int32_t)(((int64_t)across * p.offset[2]) >> 16); + } else { + /* From the threshold up to full scale as a fraction, S15.16; the + * threshold is whole decibels, so this is exact. */ + int32_t above = (p.db[1] - db) / set->threshold_db; + offset = (int32_t)(((int64_t)above * p.offset[3]) >> 16); + } + out->gain[i] = gain_from_db(offset); + } + out->gain[64] = gain_from_db(p.offset[3]); + out->gain[65] = gain_from_db(p.offset[4]); + out->makeup = gain_from_db(p.makeup); + + out->release_a = per_ms_coefficient(rate, set->release_ms); + out->release_b = UNITY - out->release_a; + if (set->attack_ms) { + out->attack_a = per_ms_coefficient(rate, set->attack_ms); + out->attack_b = UNITY - out->attack_a; + } else { + out->attack_a = UNITY; + out->attack_b = 0; + } + /* y[n] = a (y[n-1] + x[n] - x[n-1]) with a = rate / (rate + 1/RC). */ + out->hp1 = (int32_t)(UNITY / (rate + HP1_RC) * rate); + out->hp2 = (int32_t)(UNITY / (rate + HP2_RC) * rate); +} diff --git a/extensions/compressor/editor.c b/extensions/compressor/editor.c new file mode 100644 index 0000000..20c67c3 --- /dev/null +++ b/extensions/compressor/editor.c @@ -0,0 +1,271 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Compressor screen: the output level for every input level, as the six + * values shape it, over two rows of the switch and the values. The wheel picks + * a value, Select edits it, holding Select puts it back to its default and + * Menu steps back out. Every change plays at once. */ + +#include "labels.h" +#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_PARAMETER, DEPTH_EDIT, DEPTHS }; + +static const char *const titles[PARAM_COUNT] = {"State", "Threshold", "Ratio", "Knee", + "Makeup", "Attack", "Release"}; +static const uint8_t keys[PARAM_COUNT] = { + KEY_ON, KEY_THRESHOLD, KEY_RATIO, KEY_KNEE, KEY_MAKEUP, KEY_ATTACK, KEY_RELEASE}; +static const uint8_t counts[PARAM_COUNT] = { + ON_LABELS, THRESHOLD_LABELS, RATIO_LABELS, KNEE_LABELS, + MAKEUP_LABELS, ATTACK_LABELS, RELEASE_LABELS}; +static const uint8_t defaults[PARAM_COUNT] = { + ON_DEFAULT, THRESHOLD_DEFAULT, RATIO_DEFAULT, KNEE_DEFAULT, + MAKEUP_DEFAULT, ATTACK_DEFAULT, RELEASE_DEFAULT}; + +enum { + PLOT_POINTS = 259, /* -36 dB to 0 dB of input: 86 px per 12 dB */ + PLOT_RANGE = 360, /* tenths of a decibel on either axis */ + TICK_TOP = 106, + TICK_HEIGHT = 15, + CELL_TOP = 123, /* two rows of cells share the rest of the canvas */ + ROWS = 2, + COLUMNS = 3, /* the first row; the second holds the rest */ +}; + +/* The output level, 0 dB at the top and -36 dB at the bottom: 25 px per 12 dB. */ +static const struct rv_plot plot = { + .left = 44, + .top = 30, + .bottom = 105, + .points = PLOT_POINTS, + .bottom_value = -PLOT_RANGE, +}; + +static struct { + struct rv_editor input; + int parameter; + int on; + /* The curve in tenths of a decibel: input levels, the offset at each and + * the makeup gain added after, from compressor_points. */ + int in[5], offset[5], makeup; +} editor; + +static int value(int parameter) +{ + return rv_clamp(api->setting_get_int(self, keys[parameter]), 0, + counts[parameter] - 1); +} + +static int tenths(int32_t db) +{ + return (int)((db * 10 + (1 << 15)) >> 16); +} + +static void compute_points(void) +{ + struct compressor_set set = { + .on = (uint8_t)value(PARAM_ON), + .threshold_db = (int8_t)threshold_db(value(PARAM_THRESHOLD)), + .makeup = (uint8_t)value(PARAM_MAKEUP), + .ratio = (uint8_t)value(PARAM_RATIO), + .knee = (uint8_t)value(PARAM_KNEE), + }; + struct compressor_points points; + compressor_points(&set, &points); + for (unsigned int i = 0; i < 5; i++) { + editor.in[i] = tenths(points.db[i]); + editor.offset[i] = tenths(points.offset[i]); + } + editor.makeup = tenths(points.makeup); + editor.on = set.on; +} + +/* The output level for an input level, both in tenths of a decibel: straight + * between the points, flat below the first and past the last. */ +static int output_tenths(int in) +{ + const int *at = editor.in, *offset = editor.offset; + int gain = offset[4]; + if (in <= at[0]) { + gain = 0; + } else { + for (unsigned int k = 1; k < 5; k++) { + if (in <= at[k]) { + gain = offset[k - 1] + (offset[k] - offset[k - 1]) * (in - at[k - 1]) / + (at[k] - at[k - 1]); + break; + } + } + } + return in + gain + editor.makeup; +} + +static int plot_x(int in) +{ + return plot.left + + ((in + PLOT_RANGE) * (PLOT_POINTS - 1) + PLOT_RANGE / 2) / PLOT_RANGE; +} + +/* The input level at a plot column, in tenths of a decibel. */ +static int column_in(unsigned int i) +{ + return -PLOT_RANGE + + (int)((i * PLOT_RANGE + (PLOT_POINTS - 1) / 2) / (PLOT_POINTS - 1)); +} + +/* A curve of `thickness` pixels, a column per point stretched to meet the one + * before, as rv_plot_curve draws, but from the level of each column as it + * goes: `compressed` draws the output level, otherwise the input unchanged. */ +static void draw_curve(const struct rv_canvas *c, int compressed, int thickness, + uint8_t color) +{ + int previous = -1; + for (unsigned int i = 0; i < PLOT_POINTS; i++) { + int in = column_in(i); + int y = rv_plot_y(&plot, compressed ? output_tenths(in) : in); + if (previous < 0) + previous = y; + int top = y < previous ? y : previous; + int bottom = y > previous ? y : previous; + rv_canvas_rect(c, plot.left + (int)i, top, 1, bottom - top + thickness, color); + previous = y; + } +} + +static void draw_plot(const struct rv_canvas *c) +{ + static const char *const scale[] = {"0", "-12", "-24", "-36"}; + static const char *const ticks[] = {"-36", "-24", "-12", "0 dB"}; + /* Off plays the input unchanged, so that line takes the accent. */ + const struct rv_canvas_legend legend[] = { + {"Unchanged", editor.on ? RV_CANVAS_INACTIVE : RV_CANVAS_ACCENT}, + {"Compressed", editor.on ? RV_CANVAS_ACCENT : RV_CANVAS_INACTIVE}, + }; + rv_plot_ticks(c, &plot, ticks, 4, TICK_TOP, TICK_HEIGHT); + rv_plot_grid(c, &plot, scale, 4); + rv_canvas_header(c, "Output level", legend, 2); + if (!editor.on) { + draw_curve(c, 0, 2, RV_CANVAS_ACCENT); + return; + } + rv_canvas_rect(c, plot_x(editor.in[1]), plot.top, 1, plot.bottom - plot.top + 1, + RV_CANVAS_BORDER); + draw_curve(c, 0, 1, RV_CANVAS_INACTIVE); + draw_curve(c, 1, 2, RV_CANVAS_ACCENT); +} + +/* The values read inactive while the compressor is off; they still edit. */ +static void draw_parameters(const struct rv_canvas *c) +{ + int row_height = + (c->height - CELL_TOP - (ROWS - 1)) / ROWS; /* a border between rows */ + int first = 0; + for (int row = 0; row < ROWS; row++) { + int top = CELL_TOP + row * (row_height + 1); + int height = row == ROWS - 1 ? c->height - top : row_height; + int count = row == ROWS - 1 ? PARAM_COUNT - first : COLUMNS; + char text[PARAM_COUNT][LABEL_BYTES]; + const char *values[PARAM_COUNT]; + uint8_t states[PARAM_COUNT]; + for (int column = 0; column < count; column++) { + int parameter = first + column; + values[column] = + compressor_label(parameter, value(parameter), text[column]); + states[column] = parameter != editor.parameter ? RV_CELL_IDLE + : editor.input.depth == DEPTH_EDIT ? RV_CELL_EDITING + : RV_CELL_SELECTED; + if (!editor.on && parameter != PARAM_ON) + states[column] |= RV_CELL_MUTED; + } + rv_canvas_cells(c, top, height, titles + first, values, states, + (unsigned int)count); + first += count; + } +} + +static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width, + int height) +{ + struct rv_canvas c; + (void)ctx; + rv_canvas_begin(&c, g, width, height); + draw_plot(&c); + draw_parameters(&c); +} + +static void wheel(int delta) +{ + if (editor.input.depth == DEPTH_PARAMETER) { + editor.parameter = rv_clamp(editor.parameter + delta, 0, PARAM_COUNT - 1); + return; + } + int previous = value(editor.parameter); + int next = rv_clamp(previous + delta, 0, counts[editor.parameter] - 1); + if (next == previous) + return; + /* Main republishes from setting_changed, so the change plays at once. */ + api->setting_set_int(self, keys[editor.parameter], next); + compute_points(); +} + +/* A held Select puts the highlighted value back to its default. */ +static void reset(void) +{ + if (value(editor.parameter) == defaults[editor.parameter]) + return; + /* Main republishes from setting_changed, so the change plays at once. */ + api->setting_set_int(self, keys[editor.parameter], defaults[editor.parameter]); + compute_points(); +} + +static int input(const struct rv_context *ctx, const struct rv_input *input) +{ + (void)ctx; + switch (rv_editor_input(&editor.input, input)) { + case RV_EDITOR_IGNORED: + return 0; + case RV_EDITOR_CONSUMED: + return 1; + case RV_EDITOR_WHEEL: + wheel(input->delta); + break; + case RV_EDITOR_RESET: + reset(); + break; + default: + 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; + compute_points(); +} + +static const struct rv_screen screens[] = { + RV_SCREEN_CANVAS("editor", "Compressor", draw, input, + .transition = RV_TRANSITION_FROM_PANE, .opened = opened), +}; + +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/compressor/labels.c b/extensions/compressor/labels.c new file mode 100644 index 0000000..a48dece --- /dev/null +++ b/extensions/compressor/labels.c @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "labels.h" +#include "rv_libc.h" + +static const char *const ratios[RATIO_LABELS] = {"2:1", "4:1", "6:1", "10:1", "Limit"}; + +const char *compressor_label(int parameter, int index, char out[LABEL_BYTES]) +{ + switch (parameter) { + case PARAM_ON: + return index ? "On" : "Off"; + case PARAM_THRESHOLD: + rv_format_int(out, LABEL_BYTES, threshold_db(index), " dB"); + return out; + case PARAM_RATIO: + return ratios[index]; + case PARAM_KNEE: + return index ? "Soft" : "Hard"; + case PARAM_MAKEUP: + return index ? "Auto" : "Off"; + case PARAM_ATTACK: + rv_format_int(out, LABEL_BYTES, (int)attack_ms(index), " ms"); + return out; + default: + rv_format_int(out, LABEL_BYTES, (int)release_ms(index), " ms"); + return out; + } +} diff --git a/extensions/compressor/labels.h b/extensions/compressor/labels.h new file mode 100644 index 0000000..f556653 --- /dev/null +++ b/extensions/compressor/labels.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef COMPRESSOR_LABELS_H +#define COMPRESSOR_LABELS_H + +#include "shared.h" + +/* The editor's values in wheel order, which is reading order: the switch | + * Threshold | Ratio | Knee, then Makeup | Attack | Release. */ +enum { + PARAM_ON, + PARAM_THRESHOLD, + PARAM_RATIO, + PARAM_KNEE, + PARAM_MAKEUP, + PARAM_ATTACK, + PARAM_RELEASE, + PARAM_COUNT +}; + +enum { LABEL_BYTES = 8 }; /* "1000 ms" */ + +/* Value `index` of `parameter` as the editor shows it: a constant, or + * formatted into `out`. */ +const char *compressor_label(int parameter, int index, char out[LABEL_BYTES]); + +#endif diff --git a/extensions/compressor/listing.toml b/extensions/compressor/listing.toml new file mode 100644 index 0000000..6f38159 --- /dev/null +++ b/extensions/compressor/listing.toml @@ -0,0 +1,5 @@ +details = "Open Settings > Compressor to turn loud passages down so quiet ones stay audible. Threshold, Ratio, Knee, Makeup, Attack and Release sit under the transfer curve." + +[[screenshots]] +file = "screenshots/editor.png" +alt = "The Compressor editor switched on, with the transfer curve above State, Threshold, Ratio, Knee, Makeup, Attack and Release." diff --git a/extensions/compressor/main.c b/extensions/compressor/main.c new file mode 100644 index 0000000..825a097 --- /dev/null +++ b/extensions/compressor/main.c @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Compressor: Settings > Compressor opens the editor screen, which switches + * the compressor on and shapes its six values. The output-stage hook runs what + * is chosen on every buffer. */ + +#include "rv_api.h" +#include "rv_audio.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +static const struct rv_setting settings[] = { + RV_SETTING_INT(KEY_ON, "Compressor", ON_DEFAULT, 0, ON_LABELS - 1), + RV_SETTING_INT(KEY_THRESHOLD, NULL, THRESHOLD_DEFAULT, 0, THRESHOLD_LABELS - 1), + RV_SETTING_INT(KEY_MAKEUP, NULL, MAKEUP_DEFAULT, 0, MAKEUP_LABELS - 1), + RV_SETTING_INT(KEY_RATIO, NULL, RATIO_DEFAULT, 0, RATIO_LABELS - 1), + RV_SETTING_INT(KEY_KNEE, NULL, KNEE_DEFAULT, 0, KNEE_LABELS - 1), + RV_SETTING_INT(KEY_ATTACK, NULL, ATTACK_DEFAULT, 0, ATTACK_LABELS - 1), + RV_SETTING_INT(KEY_RELEASE, NULL, RELEASE_DEFAULT, 0, RELEASE_LABELS - 1), +}; + +/* Leaves what the settings say for the pump task. */ +static void publish(void) +{ + struct compressor_set set = { + .on = (uint8_t)api->setting_get_int(self, KEY_ON), + .threshold_db = (int8_t)threshold_db(api->setting_get_int(self, KEY_THRESHOLD)), + .makeup = (uint8_t)api->setting_get_int(self, KEY_MAKEUP), + .ratio = (uint8_t)api->setting_get_int(self, KEY_RATIO), + .knee = (uint8_t)api->setting_get_int(self, KEY_KNEE), + .attack_ms = (uint16_t)attack_ms(api->setting_get_int(self, KEY_ATTACK)), + .release_ms = (uint16_t)release_ms(api->setting_get_int(self, KEY_RELEASE)), + }; + compressor_publish(&set); +} + +static void setting_changed(uint16_t key) +{ + (void)key; + publish(); +} + +/* The processed output before Apple submits it: (samples, frames, context). + * Only 16-bit stereo at the rates the delay line is sized for is touched. */ +static uint32_t on_output(uint32_t samples, uint32_t frames, uint32_t context, + const void *next) +{ + uint32_t rate; + if (rv_audio_stereo16((const void *)context, frames, 8000, 48000, &rate)) + compressor_process((int16_t *)samples, frames, rate); + return api->hook_next(next, samples, frames, context, 0, 0, 0); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER_AT(RV_SITE_AudioOutputQueue_Get_call, on_output, + RV_AUDIO_STAGE_COMPRESSOR), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_SOUND_CHECK, + RV_ROW_PUSH("Compressor", "editor"), + .pane = RV_PANE(.bitmap = RV_BITMAP("settings-compressor")), + .caption_setting = KEY_ON, .host = "sound-menu", + .host_screen = "sound", .host_after = "sound-check"), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .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; + compressor_start(core); + return &extension; +} diff --git a/extensions/compressor/manifest.toml b/extensions/compressor/manifest.toml new file mode 100644 index 0000000..892fb0e --- /dev/null +++ b/extensions/compressor/manifest.toml @@ -0,0 +1,27 @@ +id = "compressor" +name = "Compressor" +description = "Turn loud passages down so quiet ones can be heard without touching the volume." +version = "0.1.0" +author = "RevolaOS" +note = "Ported from Rockbox" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "effects" + +[libraries] +required = ["dsp"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "editor" +trigger = "screen" +screens = ["editor"] + +[[asset]] +name = "settings-compressor" +file = "assets/settings-compressor.png" +pane = "icon" diff --git a/extensions/compressor/screenshots/editor.png b/extensions/compressor/screenshots/editor.png new file mode 100644 index 0000000000000000000000000000000000000000..86d39bb52eb1a9e08828745c480e429a71be51f3 GIT binary patch literal 15663 zcmajG1yCN*)-BjbZ~_E(3+}<)A-F?uhv2~>Xo5SzonRmC?gS4WoZ#;6KAn4C&CIL$ zUkyby4fNOD$M#-(t#!hb6{S&;2#^2(K$ZC@p$Y&{BH;NM0yKDhQKA>FfUUL35dCds$Zy_FS_W`8WH}dp8BtM4tN|U2k$EUi4I=Pzj{p4M9>u z-}$4cHX}MUp=z!L(oRfp>XGJu58zr`LtRa&&>HYTY@ZOU}~)KtpF(H;mbE->B3z zXY$XaIE|6^wR)@8omGQSNn(0K3rT}-kp}M=rT=Ia6T)*Wun`#Gr;f4xCeuk6|wXFhVls?-I@D!7%T5lE1zK5BW~M6z1nsPR2lgom03ttwW! zqy#caH$5ost|#0;z7_rRnNxhvDU`H=S669KmUAal+m$vMJ_<}?k>o>WRd)SZ!de7A4qw7xD@&o8Mm#a)>BtawUS>0uzD!D4?j z{b}v{r-#~&8dQz(zlnV6*v{@Vm+jd4m3(S7uGF>+6chF06O+;@2jiIquY8$`(VHV> zyn^hgo~%&0&TLKdAbJuSYqtP;6eq7A) zhYZESRL&l5ijv$aM#5%{A4#f5qBLIqk_de#z4?;AJ-c|loHcb4GGG*Ur4`Q^{x~mf z-rm!NLjzVS;bW3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al 0 HcmV?d00001 diff --git a/extensions/compressor/shared.h b/extensions/compressor/shared.h new file mode 100644 index 0000000..54cc914 --- /dev/null +++ b/extensions/compressor/shared.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the two modules of Compressor agree on. */ + +#ifndef COMPRESSOR_SHARED_H +#define COMPRESSOR_SHARED_H + +#include "compressor.h" + +enum { + KEY_ON = 1, /* int: 0 Off, 1 On */ + KEY_THRESHOLD, /* int: indexes into labels.c and the helpers below */ + KEY_MAKEUP, /* int: 0 Off, 1 Auto */ + KEY_RATIO, /* int: RATIO_2 to RATIO_LIMIT */ + KEY_KNEE, /* int: 0 Hard, 1 Soft */ + KEY_ATTACK, + KEY_RELEASE, +}; + +/* Each value is an index; these turn it into Rockbox's units. */ +enum { + ON_LABELS = 2, + THRESHOLD_LABELS = 8, + MAKEUP_LABELS = 2, + RATIO_LABELS = RATIO_COUNT, + KNEE_LABELS = 2, + ATTACK_LABELS = 7, + RELEASE_LABELS = 10, + ON_DEFAULT = 0, /* Off */ + THRESHOLD_DEFAULT = 3, /* -12 dB */ + MAKEUP_DEFAULT = 1, /* Auto */ + RATIO_DEFAULT = RATIO_4, + KNEE_DEFAULT = 1, /* Soft */ + ATTACK_DEFAULT = 1, /* 5 ms */ + RELEASE_DEFAULT = 4, /* 500 ms */ +}; + +static inline int threshold_db(int index) +{ + return -3 * (index + 1); +} + +static inline unsigned int attack_ms(int index) +{ + return 5 * (unsigned int)index; +} + +static inline unsigned int release_ms(int index) +{ + return 100 + 100 * (unsigned int)index; +} + +#endif diff --git a/extensions/compressor/tests/host.c b/extensions/compressor/tests/host.c new file mode 100644 index 0000000..63764c5 --- /dev/null +++ b/extensions/compressor/tests/host.c @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The rv_api the host tests hand compressor.c: interrupt masking that counts. */ + +#include "compressor.h" +#include "rv_api.h" + +static uint32_t irq_calls; + +static uint32_t irq_save(void) +{ + irq_calls++; + return 0; +} + +static void irq_restore(uint32_t state) +{ + (void)state; + irq_calls++; +} + +uint32_t test_irq_calls(void) +{ + return irq_calls; +} + +static const struct rv_api api = { + .size = sizeof api, .irq_save = irq_save, .irq_restore = irq_restore}; + +__attribute__((constructor)) static void start(void) +{ + compressor_start(&api); +} diff --git a/extensions/compressor/tests/run.py b/extensions/compressor/tests/run.py new file mode 100644 index 0000000..5cd3d86 --- /dev/null +++ b/extensions/compressor/tests/run.py @@ -0,0 +1,585 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the host tests with a staged SDK: python3 tests/run.py SDK. + +The reference models follow Rockbox lib/rbcodec/dsp/compressor.c +(Copyright (C) 2009 Jeffrey Goode). Modified by the RevolaOS authors, 2026. +Rockbox is GPL-2.0-or-later; this version is GPL-3.0-only. +""" + +import copy +import ctypes +import math +import sys +import tempfile +from itertools import pairwise +from pathlib import Path + +root = Path(__file__).resolve().parent +dsp = root.parents[1] / "dsp" +sys.path.insert(0, str(dsp / "tests")) +from harness import build, labeller # noqa: E402 +from harness import noise as stereo_noise # noqa: E402 +from model import Limiter # noqa: E402 + +UNITY = 1 << 24 +SHIFT = 13 +RATES = (44100, 48000, 32000, 22050, 8000) +RATIOS = (2, 4, 6, 10, 0) +OVER_DB = 0xC0A8C / 65536 +HEADROOM = 0x4AC4 / 65536 + + +class Set(ctypes.Structure): + _fields_ = [ + ("on", ctypes.c_uint8), + ("threshold", ctypes.c_int8), + ("makeup", ctypes.c_uint8), + ("ratio", ctypes.c_uint8), + ("knee", ctypes.c_uint8), + ("attack", ctypes.c_uint16), + ("release", ctypes.c_uint16), + ] + + +class Points(ctypes.Structure): + _fields_ = [ + ("db", ctypes.c_int32 * 5), + ("offset", ctypes.c_int32 * 5), + ("makeup", ctypes.c_int32), + ] + + +class Design(ctypes.Structure): + _fields_ = [("gain", ctypes.c_int32 * 66), ("makeup", ctypes.c_int32)] + [ + (name, ctypes.c_int32) + for name in ( + "attack_a", + "attack_b", + "release_a", + "release_b", + "hp1", + "hp2", + ) + ] + + +def reference_points(threshold, makeup, ratio, knee): + """Rockbox's curve in floating point: input levels in dB, the gain offset + at each, and the makeup gain.""" + r = RATIOS[ratio] + + def slope(db): + return -db * (r - 1) / r if r else -db + + half = 3 if knee else 0 + at = [threshold - half, threshold, threshold + half, 0, OVER_DB] + top, full = slope(half), slope(-threshold) + offset = [0, top / 2, top, full, slope(OVER_DB) + full] + return at, offset, (-full - HEADROOM) if makeup else 0 + + +def reference_offset(db, points, knee): + """The gain offset in dB for an input level, as Rockbox fills its table.""" + at, offset, _ = points + if db <= at[0]: + return 0 + if knee and db <= at[2]: + return (db - at[0]) / 6 * offset[2] + return (at[1] - db) / at[1] * offset[3] + + +def to_db(gain): + return 20 * math.log10(gain / UNITY) + + +def every_set(): + for threshold in range(1, 9): + for ratio in range(5): + for knee in range(2): + for makeup in range(2): + yield Set( + on=1, + threshold=-3 * threshold, + makeup=makeup, + ratio=ratio, + knee=knee, + attack=5, + release=500, + ) + + +def coefficient(rate, ms): + return UNITY // rate * 1152 // ms + + +def design_tests(dll): + points = dll.compressor_points + points.argtypes = [ctypes.POINTER(Set), ctypes.POINTER(Points)] + points.restype = None + design = dll.compressor_design + design.argtypes = [ctypes.POINTER(Design), ctypes.POINTER(Set), ctypes.c_uint] + design.restype = None + + for chosen in every_set(): + reference = reference_points( + chosen.threshold, chosen.makeup, chosen.ratio, chosen.knee + ) + out = Points() + points(chosen, out) + for i in range(5): + assert abs(out.db[i] / 65536 - reference[0][i]) < 2 / 65536, ( + chosen.threshold, + i, + ) + assert abs(out.offset[i] / 65536 - reference[1][i]) < 2 / 65536, ( + chosen.ratio, + i, + ) + assert abs(out.makeup / 65536 - reference[2]) < 2 / 65536 + + d = Design() + design(d, chosen, 44100) + assert d.gain[0] == UNITY + for i in range(1, 64): + level = 20 * math.log10(i / 64) + expected = reference_offset(level, reference, chosen.knee) + assert abs(to_db(d.gain[i]) - expected) < 0.01, ( + chosen.threshold, + chosen.ratio, + i, + ) + assert d.gain[i] <= UNITY + assert abs(to_db(d.gain[64]) - reference[1][3]) < 0.005 + assert abs(to_db(d.gain[65]) - reference[1][4]) < 0.005 + assert abs(to_db(d.makeup) - reference[2]) < 0.005 + # Monotonic: louder input, no more gain. + assert all(a >= b for a, b in zip(d.gain, d.gain[1:])) + + # Coefficients are Rockbox's integer formulas, and near the real values. + for rate in RATES: + for attack, release in ((0, 100), (5, 500), (30, 1000)): + chosen = Set( + on=1, + threshold=-12, + makeup=1, + ratio=1, + knee=1, + attack=attack, + release=release, + ) + d = Design() + design(d, chosen, rate) + assert d.release_a == coefficient(rate, release) + assert d.release_b == UNITY - d.release_a + assert abs(d.release_a / UNITY - 1152 / (rate * release)) < 0.02 * 1152 / ( + rate * release + ) + if attack: + assert d.attack_a == coefficient(rate, attack) + assert d.attack_b == UNITY - d.attack_a + else: + assert d.attack_a == UNITY and d.attack_b == 0 + assert d.hp1 == UNITY // (rate + 0x3C1) * rate + assert d.hp2 == UNITY // (rate + 0x2065) * rate + assert abs(d.hp1 / UNITY - rate / (rate + 961)) < 3e-3 + assert abs(d.hp2 / UNITY - rate / (rate + 8293)) < 3e-3 + # Makeup Off is exactly unity. + d = Design() + design( + d, + Set(on=1, threshold=-12, makeup=0, ratio=4, knee=0, attack=5, release=500), + 44100, + ) + assert d.makeup == UNITY + + +def label_tests(dll): + labels = labeller(dll.compressor_label) + ON, THRESHOLD, RATIO, KNEE, MAKEUP, ATTACK, RELEASE = range(7) + assert labels(ON, 2) == ["Off", "On"] + assert labels(THRESHOLD, 8) == [f"{-3 * i} dB" for i in range(1, 9)] + assert labels(MAKEUP, 2) == ["Off", "Auto"] + assert labels(RATIO, 5) == ["2:1", "4:1", "6:1", "10:1", "Limit"] + assert labels(KNEE, 2) == ["Hard", "Soft"] + assert labels(ATTACK, 7) == [f"{5 * i} ms" for i in range(7)] + assert labels(RELEASE, 10) == [f"{100 + 100 * i} ms" for i in range(10)] + defaults = (0, 3, 1, 1, 1, 1, 4) + counts = (2, 8, 5, 2, 2, 7, 10) + chosen = [labels(p, c)[d] for p, (c, d) in enumerate(zip(counts, defaults))] + assert chosen == ["Off", "-12 dB", "4:1", "Soft", "Auto", "5 ms", "500 ms"] + + +def wrap(value): + value &= 0xFFFFFFFF + return value - (1 << 32) if value & 0x80000000 else value + + +def scale(a, b): + return wrap((a * b) >> 24) + + +def fracmul(a, b): + return wrap((a * b) >> 31) + + +def magnitude(sample): + return -(sample + 1) if sample < 0 else sample + + +class Reference: + """The ported loop, integer for integer, on S16 raised by SHIFT bits, with + its output wide for the limiter.""" + + def __init__(self, rate): + self.length = 3 * rate // 1000 + self.delay = [(0, 0)] * self.length + self.index = 0 + self.gain = UNITY + self.holdoff = self.length + self.x1 = self.y1 = self.y2 = 0 + + def curve_gain(self, design, level): + gain = design.gain + level = magnitude(level) >> SHIFT + if level < 1 << 15: + i = level >> 9 + return wrap(gain[i] - fracmul((level & 0x1FF) << 22, gain[i] - gain[i + 1])) + if level < 1 << 17: + return wrap( + gain[64] + - fracmul(((level - (1 << 15)) // 3) << 16, gain[64] - gain[65]) + ) + return -1 + + def process(self, design, frames): + out = [] + for s0, s1 in frames: + left, right = s0 << SHIFT, s1 << SHIFT + x = (left + right) >> 1 + self.y1 = scale(design.hp1, x - self.x1 + self.y1) + self.y2 = scale(design.hp2, x - self.x1 + self.y2) + self.x1 = x + level = wrap((x >> 1) + self.y1 + self.y2 * 2) + level >>= 1 + level = wrap(level + (level >> 1)) + wanted = self.curve_gain(design, level) + if wanted <= self.gain and wanted > 0: + if design.attack_a == UNITY: + self.gain = wanted + else: + self.gain = wrap( + scale(self.gain, design.attack_b) + + scale(wanted, design.attack_a) + ) + self.holdoff = self.length + elif self.holdoff > 0: + self.holdoff -= 1 + else: + self.gain = wrap( + scale(self.gain, design.release_b) + scale(wanted, design.release_a) + ) + total = scale(self.gain, design.makeup) + d0, d1 = self.delay[self.index] + self.delay[self.index] = (s0, s1) + self.index = (self.index + 1) % self.length + if total != UNITY: + out.append( + ( + wrap((total * d0 + (1 << 23)) >> 24), + wrap((total * d1 + (1 << 23)) >> 24), + ) + ) + else: + out.append((d0, d1)) + return out + + +def noise(count, seed, scale_bits=0): + return [ + (left >> scale_bits, right >> scale_bits) + for left, right in stereo_noise(count, seed) + ] + + +def sine(count, hz, rate, amplitude): + return [ + (round(amplitude * math.sin(2 * math.pi * hz * i / rate)),) * 2 + for i in range(count) + ] + + +FADE = 128 + + +def process_tests(dll): + publish = dll.compressor_publish + publish.argtypes = [ctypes.POINTER(Set)] + publish.restype = None + process = dll.compressor_process + process.argtypes = [ + ctypes.POINTER(ctypes.c_int16), + ctypes.c_uint32, + ctypes.c_uint32, + ] + process.restype = None + design = dll.compressor_design + design.argtypes = [ctypes.POINTER(Design), ctypes.POINTER(Set), ctypes.c_uint] + design.restype = None + count = 512 + + def designed(chosen, rate): + d = Design() + design(d, chosen, rate) + return d + + class Player: + """One instance as the engine keeps it: a set at a rate over a Reference, + or a pass-through while Off.""" + + def __init__(self, rate, chosen): + self.rate, self.chosen, self.on = rate, chosen, chosen.on != 0 + self.reference = Reference(rate) + self.design = designed(chosen, rate) if self.on else None + + def play(self, frames): + return ( + self.reference.process(self.design, frames) if self.on else list(frames) + ) + + # What plays, what fades out and the frames left of that fade, a set left + # while an on/off fade lasts, and the limiter behind both. + engine = { + "new": Player(44100, Set(on=0, threshold=-12)), + "old": None, + "remaining": 0, + } + engine["pending"] = None + limiter = Limiter() + + def switching(): + old = engine["old"] + return bool( + engine["remaining"] and old is not None and old.on != engine["new"].on + ) + + def take(chosen, rate): + """At the same rate the engine fades from what played, and new values + while on keep the state; turning on rests the limiter and fills both + delay lines first; a new rate starts over without a fade.""" + old, new = engine["new"], Player(rate, chosen) + if rate == old.rate and old.on and new.on: + new.reference = copy.deepcopy(old.reference) + turns_on = new.on and not old.on + if turns_on: + limiter.rest() + engine["new"] = new + if rate == old.rate: + lead = new.reference.length + Limiter.FRAMES if turns_on else 0 + engine["old"], engine["remaining"] = old, FADE + lead + else: + engine["old"], engine["remaining"] = None, 0 + + def switch(chosen): + """Publishes a set, which the next process call takes.""" + publish(chosen) + engine["pending"] = chosen + + def expected(frames, rate): + """One process call: a pending set is taken unless an on/off fade + lasts, a new rate takes it at once, then rv_fade_run_limited's blend.""" + pending = engine["pending"] + if (pending is not None and not switching()) or rate != engine["new"].rate: + take(pending if pending is not None else engine["new"].chosen, rate) + engine["pending"] = None + new, old = engine["new"], engine["old"] + new_out = new.play(frames) if new.on else None + running = old is not None and engine["remaining"] and old.on + old_out = old.play(frames) if running else None + out = [] + for i, frame in enumerate(frames): + remaining = engine["remaining"] + if not remaining: + out.append(frame if new_out is None else limiter.run(new_out[i])) + continue + weight = 0 if remaining > FADE else FADE + 1 - remaining + if old_out is not None and new_out is not None: + mixed = tuple( + (Limiter.clamp(a) * (FADE - weight) + Limiter.clamp(b) * weight) + >> 7 + for a, b in zip(old_out[i], new_out[i], strict=True) + ) + out.append(limiter.run(mixed)) + elif old_out is not None or new_out is not None: + alone = limiter.run(old_out[i] if old_out is not None else new_out[i]) + if old_out is not None: + weight = FADE - weight + out.append( + tuple( + (x * (FADE - weight) + y * weight) >> 7 + for x, y in zip(frame, alone, strict=True) + ) + ) + else: + out.append(frame) + engine["remaining"] -= 1 + if not engine["remaining"]: + engine["old"] = None + return out + + def run(frames, rate, *splits): + """Processes the frames in one buffer, or in buffers cut at the splits. + A rate the engine has not seen starts its state over without a fade.""" + buffer = (ctypes.c_int16 * (2 * len(frames)))( + *[s for frame in frames for s in frame] + ) + edges = [0, *splits, len(frames)] + for first, last in pairwise(edges): + process( + ctypes.cast(ctypes.byref(buffer, 4 * first), process.argtypes[0]), + last - first, + rate, + ) + return [(buffer[2 * i], buffer[2 * i + 1]) for i in range(len(frames))] + + def play(frames, rate, *splits): + """Runs the frames and checks them against the model, returning them.""" + got = run(frames, rate, *splits) + edges = [0, *splits, len(frames)] + model = [f for a, b in pairwise(edges) for f in expected(frames[a:b], rate)] + assert got == model, (rate, splits) + return got + + def interrupts(): + dll.test_irq_calls.restype = ctypes.c_uint32 + return dll.test_irq_calls() + + def turned_off(): + """Off, with the fade out of the delayed samples over.""" + switch(Set(on=0, threshold=-12)) + play(noise(FADE, 1), 44100) + + # Off leaves the stream alone. + switch(Set(on=0, threshold=-12)) + frames = noise(count, 1) + assert play(frames, 44100) == frames + assert interrupts() == 2 + + # On at three rates, bit for bit against the model across blocks. The + # first look-ahead's worth of frames is the silence the delay line held; + # turning on at the rate that plays hides it under the input, and fades in + # the delayed samples after it. + chosen = Set(on=1, threshold=-12, makeup=1, ratio=1, knee=1, attack=5, release=500) + for rate in (44100, 48000, 8000): + switch(chosen) + length = 3 * rate // 1000 # the look-ahead + for block in range(3): + frames = noise(count, block + rate) + got = play(frames, rate) + if block == 0 and rate == 44100: + assert got[:length] == frames[:length] + elif block == 0: + # The limiter plays out what it held from the old rate first. + late = got[Limiter.FRAMES :] + assert all(frame == (0, 0) for frame in late[:length]) + assert late[length] != (0, 0) + + # New values keep the state and fade in; Off fades the delayed samples out + # into the input; on again fills the line, then fades in; a new rate during + # a fade ends it and starts over. + switch(chosen) + play(noise(count, 20), 44100) + louder = Set(on=1, threshold=-6, makeup=0, ratio=4, knee=0, attack=0, release=100) + switch(louder) + play(noise(count, 21), 44100) + switch(Set(on=0, threshold=-12)) + frames = noise(count, 22) + got = play(frames, 44100) + assert got[FADE:] == frames[FADE:] and got[:FADE] != frames[:FADE] + switch(louder) + play(noise(64, 23), 44100) + play(noise(count, 24), 32000) + + # The lead and the fade span buffer edges and end after their frames + # whatever their size; a set taken during a fade restarts the fade from + # the set that plays. + turned_off() + switch(chosen) + play(noise(count, 25), 32000, 17, 100, 300) + switch(louder) + play(noise(64, 26), 32000) + switch(chosen) + play(noise(count, 27), 32000) + + # A set left while an on/off fade lasts waits for its end: on, then new + # values 50 frames into the lead, which wait for the blend to end, across a + # buffer edge, and are taken on the buffer after it. + turned_off() + switch(chosen) + play(noise(50, 28), 44100) + assert switching() + switch(louder) + play(noise(count, 29), 44100, 200) + assert engine["pending"] is not None and not switching() + play(noise(count, 30), 44100) + assert engine["pending"] is None and engine["new"].chosen is louder + + # Attack 0 ms, every ratio and both knees: the model agrees at the edges. + for ratio in range(5): + for knee in range(2): + chosen = Set( + on=1, + threshold=-24, + makeup=1, + ratio=ratio, + knee=knee, + attack=0, + release=1000, + ) + turned_off() + switch(chosen) + frames = noise(count, 30 + ratio) + noise(count, 40 + ratio, 6) + play(frames, 44100) + + # A full-scale tone above a Limit threshold comes out well below full scale. + chosen = Set(on=1, threshold=-24, makeup=0, ratio=4, knee=0, attack=0, release=100) + turned_off() + switch(chosen) + for _ in range(10): + got = play(sine(4410, 1000, 44100, 32767), 44100) + peak = max(abs(s) for frame in got for s in frame) + assert 0 < peak < 0.3 * 32767, peak + + # Auto makeup over a quiet start then full scale: the makeup lifts the + # first loud frames past full scale, and the limiter holds them there. + chosen = Set(on=1, threshold=-24, makeup=1, ratio=4, knee=1, attack=30, release=500) + turned_off() + switch(chosen) + frames = noise(count, 50, 8) + noise(count, 51) + wide = Player(44100, chosen).play(frames) + assert max(abs(s) for frame in wide for s in frame) > 40000 + got = play(frames, 44100) + assert all(-32767 <= s <= 32767 for frame in got for s in frame) + + +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="compressor-tests-") as name: + work = Path(name) + dll = build( + work, + "compressor.so", + [ + root / "host.c", + sdk / "rv_libc.c", + dsp / "limiter.c", + root.parent / "compressor.c", + root.parent / "curve.c", + root.parent / "design.c", + root.parent / "labels.c", + ], + [sdk, dsp, root.parent], + ) + design_tests(dll) + label_tests(dll) + process_tests(dll) +print("Compressor tests passed") diff --git a/extensions/fatigue-reduction/Makefile b/extensions/fatigue-reduction/Makefile new file mode 100644 index 0000000..3a14eef --- /dev/null +++ b/extensions/fatigue-reduction/Makefile @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: GPL-3.0-only +# The per-sample work is the dsp library's cascade, built as ARM there. +main_SOURCES := main.c design.c modes.c ../shared/bank.c +editor_SOURCES := editor.c design.c modes.c +EXTRA_CFLAGS := -I../shared -DBANK_STAGES=4 +include $(SDK)/rv.mk diff --git a/extensions/fatigue-reduction/README.md b/extensions/fatigue-reduction/README.md new file mode 100644 index 0000000..e1779c6 --- /dev/null +++ b/extensions/fatigue-reduction/README.md @@ -0,0 +1,26 @@ +# Fatigue Reduction + +Ported from Rockbox's auditory fatigue reduction (`lib/rbcodec/dsp/afr.c`) by Chiwen Chang, GPL-2.0-or-later. + +Takes the edge off the upper mids and treble with four fixed filters, for long listening: a bell at 8 kHz with a shelf above it, a bell at 3.15 kHz and a low shelf below 200 Hz. Runs at its own stage of the shared [output stage](https://github.com/paviro/revola/blob/main/docs/sdk/audio.md), after Bass Enhancement and before Surround. + +Settings > Fatigue Reduction plots the response of the chosen strength, with the strength below. The wheel picks a strength, holding Select resets it to Off, Menu goes back. Changes apply immediately and are saved. + +The cut each filter is set to: + +| Strength | 8 kHz bell | 3.15 kHz bell | Low shelf | +|---|---|---|---| +| Off | nothing changes | | | +| Weak | -2.9 dB | -1.3 dB | 0 dB | +| Moderate | -5.8 dB | -2.9 dB | -0.5 dB | +| Strong | -7.2 dB | -4.8 dB | -0.5 dB | + +The filters are designed for 44.1 and 48 kHz; at other rates the audio passes through. Every filter is a cut, but the cuts can ring a little over full scale on hard transients, so a look-ahead limiter catches what still goes over and delays the output by about 0.7 ms. + +The Fatigue Reduction row sits after Sound Check, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise, with the strength as its caption. Off costs nothing per sample. + +| | | +|---|---| +| Default | off | +| Memory | image only | +| Settings | strength | diff --git a/extensions/fatigue-reduction/assets/LICENSE.cupertino-icons b/extensions/fatigue-reduction/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/fatigue-reduction/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/fatigue-reduction/assets/render.py b/extensions/fatigue-reduction/assets/render.py new file mode 100644 index 0000000..da088af --- /dev/null +++ b/extensions/fatigue-reduction/assets/render.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render settings-fatigue-reduction.png, the Settings pane icon: Cupertino +Icons' ear fitted into the art box of a 78 x 121 gray coverage mask in the +style of the stock Settings icons, lit from the top and mirrored in a fading +reflection below. Drawing uses ImageMagick's `magick`; the font +(CupertinoIcons.ttf from the Flutter `cupertino_icons` package, MIT, see +LICENSE.cupertino-icons) is not in the repository. + + python3 assets/render.py --font CupertinoIcons.ttf + python3 assets/render.py --font CupertinoIcons.ttf --check +""" + +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import ART_BOTTOM, ART_TOP, glyph, icon, main + +OUT = HERE / "settings-fatigue-reduction.png" +# The glyph's code point in the font, and its reach: the longer side of the +# box it is fitted into, centred on the art box. +EAR, REACH = 0xF642, 52 + + +def render(out, work, font): + icon(out, work, glyph(work, font, EAR, REACH), ART_TOP, ART_BOTTOM) + + +if __name__ == "__main__": + main(__doc__, {OUT: render}, font=True) diff --git a/extensions/fatigue-reduction/assets/settings-fatigue-reduction.png b/extensions/fatigue-reduction/assets/settings-fatigue-reduction.png new file mode 100644 index 0000000000000000000000000000000000000000..03301c48bcadf2b5980a5530875413c76bfbbd82 GIT binary patch literal 2009 zcmZ{lc{CJy8^?b`jL1!>sZq99xQ!`WcGIXK+e|2TEZIV18CeFC48~GsP^j$2pld0m zB7;byjj|SHD>2#kAq_EH=e*~<=e&R1Kc4URJm2Sh&iBuUZi723E(#X~0EkML)In-!AT@L^ zXy_Vf=ox70Ak@_j)YVG}ThRXl0s_5!FGu`4&}(4Uumh<6uOZYoz?&565fJq6O#BIg z7XZR9EHEY)e1_+9T!@G9`&+ijmkH!~{?fvrMes$$ZY*uXqXBpGHf{NHsj{UgZL#!d z2H@H%NQlt0j6eiBZn^sbO;I6TQs2JlLb3Gz8to!+tZ$m4VU4p&dM(b$PzU$LHIT#4 z%~_fB=yMD-@b4m`8|U1jmyGee+Q|Za(quto>0_e-&VLF?-&-8t~qA z=gftTI-#l}XPvg~+6v_Ov){K|bURKL6fuu(Rxf@R(cTEy6Jt`g=TiBlf9W zO7p!zrls5vff)4xqzqeCxsH4c=Nj~oJv)1j~+p)U{lECppI7kmROXE zr#sqn%SQO!nGIFjy=V1Ltf$~Zm)uf09n_rBnYyJ{C3xezRaxm;SvLev{w_0BO~NsL?Dh$T;Abe^|7 zQXo{yZ$>ZA<=G!8Q+|&XK43TI#H&j)|A0|a)@*Y4oL(U9D_;CWUNZQNKFTq^RnjCr zyJF$VCk&g)P}#%N6Ct8aY#y>mPU=jkYGLGIs~Dx{zkEP;9?C6ul{xeyvASCjGi;0l z0us#(a^{`^F2R)rthX>HKy$hKa0Pkf^X~gLf%uj}ads7WrcC>jS64-re)9A34E5=W z^%=YEiSnhC$^PBkPsyUxBypmtJCD9x{C6M}W;T;ES09t9Rwlc^ez!)v|1k_2tUOI4 zS$pn-fFw2K7p+Cwt~|?aXp_YLjq;Vg@S}?f`06&8Qqs86*Hs11&)~Wi3;o4oh_Q*) zxM^)r$b(?p37=$xGWs)KBuD96H)aY_WnSjU-;#}oUVPus{+4zTfHk=}seF_GpeO3= zHY-rQ)|}Cp7fGBY{)yp5$C=AnLukTJhkFPeKx2M#D6gTeTZU{}zR%h$#!NpnLEOlKBxtp@L1r;ZoP=0B?BFZeca;_$e~W+dF*!-p!i7g=yrT?Q9?yxgsB1Ptyi0~j{-Whd|zWS{9KNBb}q(FFs*HD z)#d^;%|LJF#$Wd&Muw_}p=+m+9}5N2jK-=&D{L_Xgfc}BhLVN_i^p)}CdD(p%@V1gTb1PDm-Vp0?M-t@&%RbK)hQkcs z@tQVGFTMJrj+fu=0K=wdF2yt(dQX9nETV~Goo1&79OEWE7pzQQ znqDIfL@ZV{2xnVDL)(liDQ+GW6^Rd$?CP^Mi~ORPc= FATIGUE_STRENGTHS) + return 0; + const struct gains *g = &strengths[strength]; + return rv_dsp_bishelf(out[0], 8000, 20000, 0, g->treble / 2, 0, rate) && + rv_dsp_biquad(out[1], RV_DSP_PEAKING, 8000, 28, g->treble, 0, rate) && + rv_dsp_biquad(out[2], RV_DSP_PEAKING, 3150, 28, g->presence, 0, rate) && + rv_dsp_bishelf(out[3], 200, 1280, g->bass, 0, 0, rate); +} diff --git a/extensions/fatigue-reduction/editor.c b/extensions/fatigue-reduction/editor.c new file mode 100644 index 0000000..e9ead51 --- /dev/null +++ b/extensions/fatigue-reduction/editor.c @@ -0,0 +1,146 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Fatigue Reduction screen: the response of the chosen strength as a + * curve over the strength itself. The wheel picks the strength, holding Select + * puts it back to Off and Menu steps back out. Every change plays at once. */ + +#include "rv_canvas.h" +#include "rv_dsp.h" +#include "rv_libc.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +enum { DEPTHS = 1 }; /* the wheel edits the one value */ + +enum { + PLOT_POINTS = 261, + PLOT_TOP = 36, + TICK_GAP = 6, /* plot bottom to the tick labels */ + TICK_HEIGHT = 22, + FIELD_GAP = 5, /* tick labels to the field row */ + FIELD_HEIGHT = 27, /* Strength, title left and value right, at the bottom */ +}; + +/* 0 dB at the top, -8 dB at the bottom, just under Strong's deepest cut; the + * plot runs down to the tick labels above the field row, which sits on the + * bottom edge. */ +static struct rv_plot plot_for(int height) +{ + struct rv_plot plot = { + .left = 44, .top = PLOT_TOP, .points = PLOT_POINTS, .bottom_value = -80}; + plot.bottom = (int16_t)(height - FIELD_HEIGHT - FIELD_GAP - TICK_HEIGHT - TICK_GAP); + return plot; +} + +static struct { + struct rv_editor input; + int16_t curve[PLOT_POINTS]; +} editor; + +static int strength(void) +{ + return rv_clamp(api->setting_get_int(self, KEY_STRENGTH), FATIGUE_OFF, + FATIGUE_STRONG); +} + +/* The chosen strength's curve, drawn for 44.1 kHz, the rate nearly everything + * plays at; it barely moves at 48 kHz. Off is the zero line. */ +static void compute_curve(void) +{ + int32_t coefficients[FATIGUE_STAGES][5]; + int chosen = strength(); + if (chosen != FATIGUE_OFF && + fatigue_design(coefficients, (unsigned int)chosen, 44100)) + rv_dsp_response(coefficients, FATIGUE_STAGES, 44100, editor.curve, PLOT_POINTS); + else + memset(editor.curve, 0, sizeof editor.curve); +} + +static void draw_plot(const struct rv_canvas *c, const struct rv_plot *plot) +{ + static const char *const ticks[] = {"20", "200", "2k", "20k Hz"}; + static const char *const scale[] = {"0", "-4", "-8"}; + + rv_plot_ticks(c, plot, ticks, 4, plot->bottom + TICK_GAP, TICK_HEIGHT); + rv_plot_grid(c, plot, scale, 3); + rv_canvas_header(c, "Response", NULL, 0); + rv_plot_curve(c, plot, editor.curve, 2, RV_CANVAS_ACCENT); +} + +static void draw_strength(const struct rv_canvas *c, int height) +{ + static const char *const title = "Strength"; + const char *value = strength_labels[strength()]; + uint8_t state = RV_CELL_EDITING; + rv_canvas_fields(c, height - FIELD_HEIGHT, FIELD_HEIGHT, &title, &value, &state, 1); +} + +static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width, + int height) +{ + struct rv_canvas c; + (void)ctx; + struct rv_plot plot = plot_for(height); + rv_canvas_begin(&c, g, width, height); + draw_plot(&c, &plot); + draw_strength(&c, height); +} + +/* Main republishes from setting_changed, so a change plays at once. */ +static void set_strength(int next) +{ + if (next == strength()) + return; + api->setting_set_int(self, KEY_STRENGTH, next); + compute_curve(); +} + +static int input(const struct rv_context *ctx, const struct rv_input *input) +{ + (void)ctx; + switch (rv_editor_input(&editor.input, input)) { + case RV_EDITOR_IGNORED: + return 0; + case RV_EDITOR_CONSUMED: + return 1; + case RV_EDITOR_WHEEL: + set_strength(rv_clamp(strength() + input->delta, FATIGUE_OFF, FATIGUE_STRONG)); + break; + case RV_EDITOR_RESET: + set_strength(STRENGTH_DEFAULT); + break; + default: + 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; + compute_curve(); +} + +static const struct rv_screen screens[] = { + RV_SCREEN_CANVAS("editor", "Fatigue Reduction", draw, input, + .transition = RV_TRANSITION_FROM_PANE, .opened = opened), +}; + +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/fatigue-reduction/fatigue.h b/extensions/fatigue-reduction/fatigue.h new file mode 100644 index 0000000..8bc4951 --- /dev/null +++ b/extensions/fatigue-reduction/fatigue.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef FATIGUE_H +#define FATIGUE_H + +enum { + FATIGUE_OFF, + FATIGUE_WEAK, + FATIGUE_MODERATE, + FATIGUE_STRONG, + FATIGUE_STRENGTHS, +}; + +enum { FATIGUE_STAGES = 4 }; + +#endif diff --git a/extensions/fatigue-reduction/listing.toml b/extensions/fatigue-reduction/listing.toml new file mode 100644 index 0000000..7c1f2e2 --- /dev/null +++ b/extensions/fatigue-reduction/listing.toml @@ -0,0 +1,5 @@ +details = "Open Settings > Fatigue Reduction to take the edge off the upper mids and treble in three strengths for long listening. The plot shows the response." + +[[screenshots]] +file = "screenshots/editor.png" +alt = "The Fatigue Reduction editor at Moderate, with the response plot above Strength." diff --git a/extensions/fatigue-reduction/main.c b/extensions/fatigue-reduction/main.c new file mode 100644 index 0000000..d2986ef --- /dev/null +++ b/extensions/fatigue-reduction/main.c @@ -0,0 +1,82 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Fatigue Reduction: Settings > Fatigue Reduction opens the editor screen, + * which holds the strength, Off, Weak, Moderate or Strong. The output-stage + * hook runs what is chosen on every buffer. */ + +#include "rv_api.h" +#include "bank.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; +static struct bank bank; +_Static_assert(BANK_STAGES == FATIGUE_STAGES, "the Makefile's BANK_STAGES"); + +static const struct rv_setting settings[] = { + RV_SETTING_LABELLED(KEY_STRENGTH, "Fatigue Reduction", STRENGTH_DEFAULT, + strength_labels), +}; + +/* Designs the filters of the chosen strength for both banks and leaves them for + * the pump task. */ +static void publish(void) +{ + unsigned int strength = (unsigned int)api->setting_get_int(self, KEY_STRENGTH); + struct bank_set set = {.on = strength != FATIGUE_OFF}; + for (unsigned int b = 0; b < BANKS; b++) + if (!fatigue_design(set.coefficients[b], strength, bank_rate(b))) + set.on = 0; + bank_publish(&bank, &set); +} + +static void setting_changed(uint16_t key) +{ + (void)key; + publish(); +} + +/* The processed output before Apple submits it: (samples, frames, context). + * Only 16-bit stereo is touched. */ +static uint32_t on_output(uint32_t samples, uint32_t frames, uint32_t context, + const void *next) +{ + uint32_t rate; + if (rv_audio_stereo16((const void *)context, frames, 0, UINT32_MAX, &rate)) + bank_process(&bank, (int16_t *)samples, frames, rate); + return api->hook_next(next, samples, frames, context, 0, 0, 0); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER_AT(RV_SITE_AudioOutputQueue_Get_call, on_output, + RV_AUDIO_STAGE_FATIGUE_REDUCTION), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_SOUND_CHECK, + RV_ROW_PUSH("Fatigue Reduction", "editor"), + .pane = RV_PANE(.bitmap = RV_BITMAP("settings-fatigue-reduction")), + .caption_setting = KEY_STRENGTH, .host = "sound-menu", + .host_screen = "sound", .host_after = "sound-check"), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .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; + bank.effect.api = core; + return &extension; +} diff --git a/extensions/fatigue-reduction/manifest.toml b/extensions/fatigue-reduction/manifest.toml new file mode 100644 index 0000000..9c7916c --- /dev/null +++ b/extensions/fatigue-reduction/manifest.toml @@ -0,0 +1,27 @@ +id = "fatigue-reduction" +name = "Fatigue Reduction" +description = "Take the edge off the upper mids and treble with four fixed filters, in three strengths, for long listening." +version = "0.1.0" +author = "RevolaOS" +note = "Ported from Rockbox" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "effects" + +[libraries] +required = ["dsp"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "editor" +trigger = "screen" +screens = ["editor"] + +[[asset]] +name = "settings-fatigue-reduction" +file = "assets/settings-fatigue-reduction.png" +pane = "icon" diff --git a/extensions/fatigue-reduction/modes.c b/extensions/fatigue-reduction/modes.c new file mode 100644 index 0000000..1428c07 --- /dev/null +++ b/extensions/fatigue-reduction/modes.c @@ -0,0 +1,6 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "shared.h" + +const char *const strength_labels[FATIGUE_STRENGTHS] = {"Off", "Weak", "Moderate", + "Strong"}; diff --git a/extensions/fatigue-reduction/screenshots/editor.png b/extensions/fatigue-reduction/screenshots/editor.png new file mode 100644 index 0000000000000000000000000000000000000000..8a81457e67364b995eb5b4601e06abb150511d87 GIT binary patch literal 8475 zcma)ibyQT}*Y_nHM!J;lE&=I=QKUl}X;6?Dx{(2ul#*@`6wslh8wTlCxDk#;-GjGE04$GY6YV0C8v36iLxUs+`%kBMN?q?+`vuXGIv0;C+>K;jOLZFEk#HvD;sK2Df(v z6K`M$y!Vw)Vr?)YS5j1bnd#zE6)wGhSQmCaw|$JXN`xf7fN$G*EyPMaQS^PPSND9O zuxp~`gh3-iXoY3$ZxkH9LBBaSkXCgeC{4wjbE0VpM32^-i>R8=uP-EFVW=#3y<@5y zxf=2^Z^RnEPhmQCV|K0Gb`m`P49WZHRC&q2K~>cUb*o9cVYY9AX3G5BJi7i~HkXP; z)2HtJ-ZIsOaqDu|CD+g=9Vp{v5%4amtkb`tSz->s=J>GPWN)RMb}i0SPO)nM zHUsy_MTkgULA&#f&n>VK>M1DCa{JfODL#ZuSxY0Z3F9C0U%=(K2B$@>z0lOeCzQWfg>eG{N5N1VR*n4T#hv6q|>U$2t z(p0tG6H=IF|0jqz~?LWWR$Sreb+m*+nUp{gMWu=qop4cuZQM4I2<`0T`5hW zeH$d0%fCk9%qI}MRuqXym)~2UEIA=OG7@fm*a>EW!$%i_$rUS%L6~+}Q%g^6@kBi@r|zgCturan3T`po!=8Ti(w#lJ8>yBELn!e)N~X%gAE zKFRvhrfLhr&umzx|9v?2$b*(nJoa(nAYc$%!0K|*9VT)=vx!$TClsgQF}IiHz0}t- zsawgnxPOe)Z)w%ZzwF~+V!c~5-%Yy`<;x~#c2Qg-kO+{I5)>rK0*4KUrx=b-$<=F0 zvz~j+3gA1wvBeD1iD;v+i!KndS0ILL?r6b{8(#9HDkpuLmJ(bKO)&1$RL6#F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Tx@;HhtEmxQAcVev&|0Xp$#BDu^+EG1VHQ&hszq|Xkz6!5?OAB}QQw1MHQzUxU5D0Z%xmKh ze=MPEf$uiH&*ac;jJR=y-Y)523Pr}XS13Kz5Ys^{_Ami7Y;2-C9n<$1->T1MAeJBg4I1Do)Bpeg literal 0 HcmV?d00001 diff --git a/extensions/fatigue-reduction/shared.h b/extensions/fatigue-reduction/shared.h new file mode 100644 index 0000000..6bfd2de --- /dev/null +++ b/extensions/fatigue-reduction/shared.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the two modules of Fatigue Reduction agree on. */ + +#ifndef FATIGUE_SHARED_H +#define FATIGUE_SHARED_H + +#include "fatigue.h" +#include + +enum { + KEY_STRENGTH = 1, /* int: FATIGUE_OFF to FATIGUE_STRONG */ +}; + +enum { STRENGTH_DEFAULT = FATIGUE_OFF }; + +/* design.c: the four filters of `strength` at `rate`, 44100 or 48000 Hz, in + * rv_dsp_biquad's format; Off is flat. 0 when a filter is not stable. */ +int fatigue_design(int32_t out[FATIGUE_STAGES][5], unsigned int strength, + unsigned int rate); + +/* modes.c: the strengths by name, for the Settings caption and the editor. */ +extern const char *const strength_labels[FATIGUE_STRENGTHS]; + +#endif diff --git a/extensions/fatigue-reduction/tests/host.c b/extensions/fatigue-reduction/tests/host.c new file mode 100644 index 0000000..2cadefa --- /dev/null +++ b/extensions/fatigue-reduction/tests/host.c @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The engine as the tone test drives it: the shared bank over interrupt + * masking that does nothing, fed the set layout the test builds. */ + +#include "fatigue.h" +#include "bank.h" +#include "rv_libc.h" + +static uint32_t irq_save(void) +{ + return 0; +} + +static void irq_restore(uint32_t state) +{ + (void)state; +} + +static const struct rv_api api = { + .size = sizeof api, .irq_save = irq_save, .irq_restore = irq_restore}; + +static struct bank bank = {.effect.api = &api}; + +struct test_set { + uint8_t strength; + int32_t coefficients[BANKS][FATIGUE_STAGES][5]; +}; + +void fatigue_publish(const struct test_set *chosen) +{ + struct bank_set set = {.on = chosen->strength != 0}; + memcpy(set.coefficients[0], chosen->coefficients[0], + sizeof chosen->coefficients[0]); + memcpy(set.coefficients[1], chosen->coefficients[1], + sizeof chosen->coefficients[1]); + bank_publish(&bank, &set); +} + +void fatigue_process(int16_t *samples, uint32_t frames, uint32_t rate) +{ + bank_process(&bank, samples, frames, rate); +} diff --git a/extensions/fatigue-reduction/tests/run.py b/extensions/fatigue-reduction/tests/run.py new file mode 100644 index 0000000..cb5302c --- /dev/null +++ b/extensions/fatigue-reduction/tests/run.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the host tests with a staged SDK: python3 tests/run.py SDK. + +The reference filters follow Rockbox lib/rbcodec/dsp/afr.c (Copyright (C) +2014 by Chiwen Chang). Modified by the RevolaOS authors, 2026. Rockbox is +GPL-2.0-or-later; this version is GPL-3.0-only. +""" + +import ctypes +import math +import sys +import tempfile +from itertools import pairwise +from pathlib import Path + +root = Path(__file__).resolve().parent +dsp = root.parents[1] / "dsp" +shared = root.parents[1] / "shared" +sys.path.insert(0, str(dsp / "tests")) +from harness import build, strings # noqa: E402 +from model import SCALE, bishelf, peaking, power # noqa: E402 + +RATES = (44100, 48000) +STAGES, BANKS, STRENGTHS = 4, 2, 4 +OFF, WEAK, MODERATE, STRONG = range(4) +# hs, ls, drop3k in afr.c, tenths of a decibel. +GAINS = {WEAK: (-29, 0, -13), MODERATE: (-58, -5, -29), STRONG: (-72, -5, -48)} +Biquad = ctypes.c_int32 * 5 +Bank = Biquad * STAGES + + +class Set(ctypes.Structure): + _fields_ = [("strength", ctypes.c_uint8), ("coefficients", Bank * BANKS)] + + +def reference(strength, rate): + """afr.c's four filters at a strength, b0, b1, b2, a1, a2 over a0.""" + if strength == OFF: + return [[1, 0, 0, 0, 0]] * STAGES + hs, ls, drop3k = GAINS[strength] + return [ + bishelf(8000, 20000, 0, int(hs / 2), 0, rate), + peaking(8000, 28, hs, rate), + peaking(3150, 28, drop3k, rate), + bishelf(200, 1280, ls, 0, 0, rate), + ] + + +def designed(dll, strength, rate): + out = Bank() + assert dll.fatigue_design(out, strength, rate) == 1 + return out + + +def design_tests(dll): + design = dll.fatigue_design + design.argtypes = [ctypes.POINTER(Biquad), ctypes.c_uint, ctypes.c_uint] + for rate in RATES: + curves = {} + for strength in range(STRENGTHS): + out = designed(dll, strength, rate) + expected = reference(strength, rate) + for stage, ref in zip(out, expected, strict=True): + for a, b in zip(stage, ref, strict=True): + assert abs(a / SCALE - b) <= 2 / SCALE, ( + rate, + strength, + list(stage), + ref, + ) + scaled = [[c / SCALE for c in stage] for stage in out] + curves[strength] = [ + 100 * math.log10(power(scaled, hz, rate)) + for hz in (50, 1000, 3150, 8000) + ] + # Off is flat; the cuts deepen with the strength at 3.15 and 8 kHz, and + # the bass shelf's cut shows at 50 Hz from Moderate. + assert curves[OFF] == [0, 0, 0, 0] + for a, b in pairwise(range(STRENGTHS)): + assert curves[b][2] < curves[a][2] - 5 and curves[b][3] < curves[a][3] - 5 + assert abs(curves[WEAK][0]) < 1 and -8 < curves[MODERATE][0] < -3 + assert abs(curves[MODERATE][2] - GAINS[MODERATE][2]) < 5 + assert all(abs(curves[s][1]) < 20 for s in range(STRENGTHS)) + assert design(Bank(), STRENGTHS, 44100) == 0 + assert design(Bank(), WEAK, 32000) == 0 + + +def label_tests(dll): + labels = strings(dll, "strength_labels", STRENGTHS) + assert labels == ["Off", "Weak", "Moderate", "Strong"] + + +def tone_tests(dll): + """A quiet tone at Strong comes out quieter by the design at 3.15 kHz, once + the filters and the limiter have settled.""" + publish = dll.fatigue_publish + publish.argtypes = [ctypes.POINTER(Set)] + publish.restype = None + process = dll.fatigue_process + process.argtypes = [ctypes.POINTER(ctypes.c_int16)] + [ctypes.c_uint32] * 2 + process.restype = None + chosen = Set(strength=STRONG) + for bank, rate in enumerate(RATES): + bank_out = designed(dll, STRONG, rate) + ctypes.memmove(chosen.coefficients[bank], bank_out, ctypes.sizeof(Bank)) + publish(chosen) + frames = 8192 + tone = [ + round(8000 * math.sin(2 * math.pi * 3150 * i / 44100)) for i in range(frames) + ] + buffer = (ctypes.c_int16 * (2 * frames))(*[s for s in tone for _ in range(2)]) + process(buffer, frames, 44100) + peak = max(abs(buffer[2 * i]) for i in range(frames // 2, frames)) + scaled = [[c / SCALE for c in stage] for stage in designed(dll, STRONG, 44100)] + designed_tenths = 100 * math.log10(power(scaled, 3150, 44100)) + assert abs(200 * math.log10(peak / 8000) - designed_tenths) < 3, ( + peak, + designed_tenths, + ) + + +def response_tests(dll): + """The editor's curve of each strength is the design's response.""" + response = dll.rv_dsp_response + response.argtypes = [ctypes.POINTER(Biquad), ctypes.c_uint, ctypes.c_uint] + response.argtypes += [ctypes.POINTER(ctypes.c_int16), ctypes.c_uint] + response.restype = None + points = 261 + hertz = [20 * 1000 ** (i / (points - 1)) for i in range(points)] + for strength in (WEAK, MODERATE, STRONG): + bank = designed(dll, strength, 44100) + curve = (ctypes.c_int16 * points)() + response(bank, STAGES, 44100, curve, points) + expected = reference(strength, 44100) + for hz, tenths in zip(hertz, curve, strict=True): + assert abs(tenths - 100 * math.log10(power(expected, hz, 44100))) <= 1, ( + hz, + tenths, + ) + assert min(curve) >= -120 and max(curve) <= 0 + + +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="fatigue-reduction-tests-") as name: + work = Path(name) + sources = ( + [root / "host.c", sdk / "rv_libc.c"] + + [dsp / name for name in ("math.c", "limiter.c", "filter.c", "cascade.c")] + + [shared / "bank.c"] + + [root.parent / name for name in ("design.c", "modes.c")] + ) + includes = [sdk, dsp, shared, root.parent] + dll = build(work, "fatigue-reduction.so", sources, includes, "-DBANK_STAGES=4") + design_tests(dll) + label_tests(dll) + response_tests(dll) + tone_tests(dll) +print("Fatigue Reduction tests passed") diff --git a/extensions/surround/Makefile b/extensions/surround/Makefile new file mode 100644 index 0000000..755f155 --- /dev/null +++ b/extensions/surround/Makefile @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c design.c labels.c +# The loop multiplies 32 by 32 to 64 bits six times per frame: one ARM +# instruction each, a library call each in Thumb. +main_ARM_SOURCES := surround.c +editor_SOURCES := editor.c response.c design.c labels.c +EXTRA_CFLAGS := -I../shared +include $(SDK)/rv.mk diff --git a/extensions/surround/README.md b/extensions/surround/README.md new file mode 100644 index 0000000..9d9c1a3 --- /dev/null +++ b/extensions/surround/README.md @@ -0,0 +1,29 @@ +# Surround + +Based on Rockbox's Haas surround (`lib/rbcodec/dsp/surround.c`) by Chiwen Chang, GPL-2.0-or-later. + +Widens the stage for headphones with the Haas effect: the right channel arrives a few milliseconds after the left, which the ear reads as space, while a band you choose, where voices sit, stays in place. Runs at its own stage of the shared [output stage](https://github.com/paviro/revola/blob/main/docs/sdk/audio.md), after Fatigue Reduction and before Channels. + +Settings > Surround plots what the right ear hears, the band kept in place and what arrives late, with the switch, Delay and Mix below and the four shape values under them. The wheel picks a value, Select edits it, holding Select resets it, Menu goes back. Changes apply immediately and are saved; switching off keeps every value, and the shape values stay as they are when the delay changes. + +| Value | Range | Default | +|---|---|---| +| State | Off or On | Off | +| Delay | 5, 8, 10, 15 or 30 ms | 10 ms | +| Mix | 0 to 100 % in 5 % steps | 50 % | +| Emphasis | 0 to 99 % | 35 % | +| Low | 40 to 400 Hz in 40 Hz steps | 320 Hz | +| High | 600 to 8000 Hz in 200 Hz steps | 3400 Hz | +| Side only | Off or On | Off | + +The right channel is split at Low and High: the band between them stays where it is, and what lies below and above it is delayed by the Delay, at the sample rate that plays. The delay pulls the image towards the left ear; Emphasis moves that much level from the leading channel to the lagging one, which brings it back. Side only applies all of this to the side signal alone, so anything in the centre of the mix stays put in both ears. Mix blends the result with the original; at 0 % nothing plays through the effect, which costs nothing per sample, as does Off. + +The lagging channel can go up to 3.5 dB over at full Emphasis, and the delayed and kept bands can add up over full scale near the cutoffs; a look-ahead limiter catches what goes over and delays the output by about 0.7 ms. + +The Surround row sits after Sound Check, in Settings > Sound while the Sound Menu extension runs and in Settings otherwise. It says Off or On. + +| | | +|---|---| +| Default | off | +| Memory | two delay lines of 30 ms, about 6 KB | +| Settings | the switch, delay, mix, emphasis, low, high and side only | diff --git a/extensions/surround/assets/render.py b/extensions/surround/assets/render.py new file mode 100644 index 0000000..9c73021 --- /dev/null +++ b/extensions/surround/assets/render.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render settings-surround.png, the Settings pane icon: a listener between two +arcs of sound at each side under an arch that joins the outer pair, on a +78 x 121 gray coverage mask in the style of the stock Settings icons, lit from +the top and mirrored in a fading reflection below. Drawing uses ImageMagick's +`magick`. + + python3 assets/render.py + python3 assets/render.py --check +""" + +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import icon, main, supersampled + +OUT = HERE / "settings-surround.png" +# The listener: a disc of HEAD radius at CENTRE. The sound: two arcs about the +# same centre at each side, ARCS radii, each SPAN degrees wide, and an arch at +# the outer radius over the head between ARCH_FROM and ARCH_TO degrees, all +# STROKE wide. +CENTRE = (39, 37) +HEAD = 6 +ARCS = (16, 27) +SPAN = 70 +ARCH_FROM, ARCH_TO = 200, 340 +STROKE = 4.5 +ART_TOP, ART_BOTTOM = CENTRE[1] - 18, CENTRE[1] + 18 + + +def shapes(k): + """magick -draw arguments for the listener, the arcs and the arch, white on + black, with every coordinate scaled by k.""" + cx, cy = (v * k for v in CENTRE) + draw = [ + "-fill", + "none", + "-stroke", + "white", + "-strokewidth", + str(STROKE * k), + ] + for radius in ARCS: + r = radius * k + for middle in (180, 0): + start, end = middle - SPAN / 2, middle + SPAN / 2 + box = f"{cx - r},{cy - r} {cx + r},{cy + r}" + draw += ["-draw", f"stroke-linecap round arc {box} {start},{end}"] + r = ARCS[-1] * k + box = f"{cx - r},{cy - r} {cx + r},{cy + r}" + draw += ["-draw", f"stroke-linecap round arc {box} {ARCH_FROM},{ARCH_TO}"] + draw += [ + "-stroke", + "none", + "-fill", + "white", + "-draw", + f"circle {cx},{cy} {cx + HEAD * k},{cy}", + ] + return draw + + +def render(out, work): + icon(out, work, supersampled(work, shapes), ART_TOP, ART_BOTTOM) + + +if __name__ == "__main__": + main(__doc__, {OUT: render}) diff --git a/extensions/surround/assets/settings-surround.png b/extensions/surround/assets/settings-surround.png new file mode 100644 index 0000000000000000000000000000000000000000..d7ebb40fc469324f34e4b0cfd3032023e4e9c3b2 GIT binary patch literal 2506 zcmZ{mcQ73K7RP^9S<6OriJpi=1hMK`i^Jd=6`{T};bH3+%&wS?md*Y1m>0MwGWCH+P!0BU6&-LDU z2C<$O@UB&V^jyRp^-YZc`29Kn#D4;Ccy1Aw00@u=U0E$1>0wIe~HIr9F z$*ZB{5x3;!QS$O8V*4xq2Y7lvadQs(dqDgS=HWRY^}h=QH%}*jf`g~e-!p+04sigm zR^zbRX0Frg*}(~4&G|mIEl$s97XN$7E%3d;a-?3Dj#S+oSCAX4nVoLzbEZy-tK7=1 zo42_V5vTu9(xvGunQ+#oTf(K7Qdl7jGTe|$u2xTO%1mk2cmC{q`ZRs&^}*DR#wnsk zvCY9{Qu}NxNiEzkZ0D7~*4|hDL5)3SjP>b#>?0E{Ry@m*z3(?#?O}iX&}nc^1^|pF zEiDS_{;n?onnUk55|0?ssU-Y3VQwsxgUF}g-BLRrh2|^^#oO=_*{fSOT>XC@j5rbcuCQ=E3#it5?b8auup89wpu0`@3-fab6#k+j}t5x%Sz)az8z zKI#Sy^9inDnTUsmDQIY9y~@dLJxhhO>+tykpIwcSkq7j$ufH}#LJVrx>3yT`>1%~9 z46z{{VZJFqi0V?4RTfFVks+3~NQ}9@cV9FU?ZY@LRC>hPaNOU+n0j>Mj2?U~7wkFj zI`2B=(!m6FA{dU&r03Byg04oW%M8rN@XVjbzlBlR9sz)AwD$Uo;-7z=*jjmOQ}SBW zNOy-MR4qr^p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5b!108Zx~w)ze};y<1md%6Gs literal 0 HcmV?d00001 diff --git a/extensions/surround/design.c b/extensions/surround/design.c new file mode 100644 index 0000000..528c0b7 --- /dev/null +++ b/extensions/surround/design.c @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The crossover coefficient, integer throughout so the pump task designs it + * for whatever rate plays: with t = tan(pi hz / rate), the bilinear one-pole + * low-pass y += k ((x + x1) / 2 - y) with k = 2 t / (1 + t) has its -3 dB point + * at the cutoff. The angle's sine and cosine come from a short series and + * k = 2 sin / (sin + cos) from one shift-and-subtract division. */ + +#include "surround.h" +#include "q31.h" + +uint32_t surround_coefficient(unsigned int hz, unsigned int rate) +{ + if (rate == 0) + return 0; + /* pi hz / rate as a quarter in Q31, so the series' angle stays small. */ + int32_t ratio = (int32_t)q31_ratio(hz < rate ? hz : rate - 1, rate); + uint32_t quarter = (uint32_t)((int64_t)ratio * Q31_QUARTER_PI >> 29); + if (quarter > Q31_QUARTER_LIMIT) + quarter = Q31_QUARTER_LIMIT; + int32_t s, c; + q31_sin_cos(quarter, &s, &c); + /* 2 sin / (sin + cos) in Q30: below 2 while the cosine is positive. */ + return q31_divide((uint64_t)(uint32_t)s << 31, (uint32_t)(s + c)); +} diff --git a/extensions/surround/editor.c b/extensions/surround/editor.c new file mode 100644 index 0000000..b062a25 --- /dev/null +++ b/extensions/surround/editor.c @@ -0,0 +1,211 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Surround screen: what happens to the right channel, as two curves over + * the switch, the delay and the five values that shape the stage. One curve is + * the band that stays in place, between Low and High, the other what arrives + * late. The wheel picks a value, Select edits it, holding Select puts it back + * to its default and Menu steps back out. Every change plays at once. */ + +#include "labels.h" +#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_PARAMETER, DEPTH_EDIT, DEPTHS }; + +static const char *const titles[PARAM_COUNT] = { + "State", "Delay", "Mix", "Emphasis", "Low", "High", "Side only"}; +static const uint8_t keys[PARAM_COUNT] = { + KEY_ON, KEY_DELAY, KEY_MIX, KEY_EMPHASIS, KEY_LOW, KEY_HIGH, KEY_SIDE_ONLY}; +static const uint8_t counts[PARAM_COUNT] = {ON_LABELS, DELAY_LABELS, MIX_LABELS, + EMPHASIS_LABELS, LOW_LABELS, HIGH_LABELS, + SIDE_ONLY_LABELS}; +static const uint8_t defaults[PARAM_COUNT] = { + ON_DEFAULT, DELAY_DEFAULT, MIX_DEFAULT, EMPHASIS_DEFAULT, + LOW_DEFAULT, HIGH_DEFAULT, SIDE_ONLY_DEFAULT}; + +enum { + PLOT_POINTS = 261, + TICK_TOP = 114, + TICK_HEIGHT = 22, + INLINE_TOP = 141, /* State | Delay | Mix, title left and value right */ + INLINE_HEIGHT = 27, + INLINE_COUNT = PARAM_EMPHASIS, + CELL_TOP = INLINE_TOP + INLINE_HEIGHT + + 1, /* the cells run to the bottom of the canvas */ + CELL_COUNT = PARAM_COUNT - INLINE_COUNT, +}; + +/* 0 dB at the top, -24 dB at the bottom: 3 px per decibel. */ +static const struct rv_plot plot = { + .left = 44, + .top = 36, + .bottom = 108, + .points = PLOT_POINTS, + .bottom_value = -240, +}; + +static struct { + struct rv_editor input; + int parameter; + int16_t kept[PLOT_POINTS], delayed[PLOT_POINTS]; +} editor; + +static int value(int parameter) +{ + return rv_clamp(api->setting_get_int(self, keys[parameter]), 0, + counts[parameter] - 1); +} + +static void compute_curves(void) +{ + struct surround_set set = { + .on = (uint8_t)value(PARAM_ON), + .delay_ms = (uint8_t)delay_ms(value(PARAM_DELAY)), + .emphasis = (uint8_t)value(PARAM_EMPHASIS), + .side_only = (uint8_t)value(PARAM_SIDE_ONLY), + .mix = (uint8_t)mix_percent(value(PARAM_MIX)), + .low_hz = (uint16_t)low_hz(value(PARAM_LOW)), + .high_hz = (uint16_t)high_hz(value(PARAM_HIGH)), + }; + /* Drawn for 44.1 kHz, the rate nearly everything plays at; the crossovers + * barely move at the others. */ + surround_response(&set, 44100, editor.kept, editor.delayed, PLOT_POINTS); +} + +/* The curve the highlighted value shapes draws in the accent, over the other: + * the band kept in place for Low and High, what arrives late otherwise. Off + * has no late path, so that curve and its swatch stay inactive. */ +static void draw_plot(const struct rv_canvas *c) +{ + static const char *const ticks[] = {"20", "200", "2k", "20k Hz"}; + static const char *const scale[] = {"0", "-12", "-24"}; + int off = editor.delayed[0] == SURROUND_NO_PATH; + int kept_side = + off || editor.parameter == PARAM_LOW || editor.parameter == PARAM_HIGH; + uint8_t kept_color = kept_side ? RV_CANVAS_ACCENT : RV_CANVAS_INACTIVE; + uint8_t late_color = kept_side ? RV_CANVAS_INACTIVE : RV_CANVAS_ACCENT; + const struct rv_canvas_legend legend[] = {{"In place", kept_color}, + {"Arrives late", late_color}}; + + rv_plot_ticks(c, &plot, ticks, 4, TICK_TOP, TICK_HEIGHT); + rv_plot_grid(c, &plot, scale, 3); + rv_canvas_header(c, "The right ear hears", legend, 2); + if (kept_side) { + if (!off) + rv_plot_curve(c, &plot, editor.delayed, 2, late_color); + rv_plot_curve(c, &plot, editor.kept, 2, kept_color); + } else { + rv_plot_curve(c, &plot, editor.kept, 2, kept_color); + rv_plot_curve(c, &plot, editor.delayed, 2, late_color); + } +} + +/* The shape values read inactive while nothing plays through the effect, Off + * or a Mix of 0; they still edit. */ +static void draw_parameters(const struct rv_canvas *c) +{ + char text[PARAM_COUNT][LABEL_BYTES]; + const char *values[PARAM_COUNT]; + uint8_t states[PARAM_COUNT]; + int on = value(PARAM_ON) && value(PARAM_MIX) != 0; + for (int parameter = 0; parameter < PARAM_COUNT; parameter++) { + values[parameter] = + surround_label(parameter, value(parameter), text[parameter]); + states[parameter] = parameter != editor.parameter ? RV_CELL_IDLE + : editor.input.depth == DEPTH_EDIT ? RV_CELL_EDITING + : RV_CELL_SELECTED; + if (!on && parameter != PARAM_ON && parameter != PARAM_MIX) + states[parameter] |= RV_CELL_MUTED; + } + 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, CELL_COUNT); +} + +static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width, + int height) +{ + struct rv_canvas c; + (void)ctx; + rv_canvas_begin(&c, g, width, height); + draw_plot(&c); + draw_parameters(&c); +} + +static void wheel(int delta) +{ + if (editor.input.depth == DEPTH_PARAMETER) { + editor.parameter = rv_clamp(editor.parameter + delta, 0, PARAM_COUNT - 1); + return; + } + int previous = value(editor.parameter); + int next = rv_clamp(previous + delta, 0, counts[editor.parameter] - 1); + if (next == previous) + return; + /* Main republishes from setting_changed, so the change plays at once. */ + api->setting_set_int(self, keys[editor.parameter], next); + compute_curves(); +} + +/* A held Select puts the highlighted value back to its default. */ +static void reset(void) +{ + if (value(editor.parameter) == defaults[editor.parameter]) + return; + /* Main republishes from setting_changed, so the change plays at once. */ + api->setting_set_int(self, keys[editor.parameter], defaults[editor.parameter]); + compute_curves(); +} + +static int input(const struct rv_context *ctx, const struct rv_input *input) +{ + (void)ctx; + switch (rv_editor_input(&editor.input, input)) { + case RV_EDITOR_IGNORED: + return 0; + case RV_EDITOR_CONSUMED: + return 1; + case RV_EDITOR_WHEEL: + wheel(input->delta); + break; + case RV_EDITOR_RESET: + reset(); + break; + default: + 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; + compute_curves(); +} + +static const struct rv_screen screens[] = { + RV_SCREEN_CANVAS("editor", "Surround", draw, input, + .transition = RV_TRANSITION_FROM_PANE, .opened = opened), +}; + +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/surround/labels.c b/extensions/surround/labels.c new file mode 100644 index 0000000..4175b33 --- /dev/null +++ b/extensions/surround/labels.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "labels.h" +#include "rv_libc.h" + +const char *surround_label(int parameter, int index, char out[LABEL_BYTES]) +{ + switch (parameter) { + case PARAM_ON: + case PARAM_SIDE_ONLY: + return index ? "On" : "Off"; + case PARAM_DELAY: + rv_format_int(out, LABEL_BYTES, (int)delay_ms(index), " ms"); + return out; + case PARAM_MIX: + rv_format_int(out, LABEL_BYTES, (int)mix_percent(index), " %"); + return out; + case PARAM_EMPHASIS: + rv_format_int(out, LABEL_BYTES, index, " %"); + return out; + case PARAM_LOW: + rv_format_hz(out, LABEL_BYTES, low_hz(index)); + return out; + default: + rv_format_hz(out, LABEL_BYTES, high_hz(index)); + return out; + } +} diff --git a/extensions/surround/labels.h b/extensions/surround/labels.h new file mode 100644 index 0000000..8c2a3c7 --- /dev/null +++ b/extensions/surround/labels.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef SURROUND_LABELS_H +#define SURROUND_LABELS_H + +#include "shared.h" + +/* The editor's values in wheel order, which is reading order: the switch | + * Delay | Mix, then Emphasis | Low | High | Side only. */ +enum { + PARAM_ON, + PARAM_DELAY, + PARAM_MIX, + PARAM_EMPHASIS, + PARAM_LOW, + PARAM_HIGH, + PARAM_SIDE_ONLY, + PARAM_COUNT, +}; + +enum { LABEL_BYTES = 8 }; /* "7.8k Hz" */ + +/* Value `index` of `parameter` as the editor shows it: a constant, or + * formatted into `out`. */ +const char *surround_label(int parameter, int index, char out[LABEL_BYTES]); + +#endif diff --git a/extensions/surround/listing.toml b/extensions/surround/listing.toml new file mode 100644 index 0000000..aef06f0 --- /dev/null +++ b/extensions/surround/listing.toml @@ -0,0 +1,5 @@ +details = "Open Settings > Surround to widen the stage for headphones: the right channel arrives a few milliseconds late outside a band that stays in place. State, Delay and Mix sit under the plot, with Emphasis, Low, High and Side only below them." + +[[screenshots]] +file = "screenshots/editor.png" +alt = "The Surround editor switched on, with the plot above State, Delay, Mix and the shape values." diff --git a/extensions/surround/main.c b/extensions/surround/main.c new file mode 100644 index 0000000..f4f30eb --- /dev/null +++ b/extensions/surround/main.c @@ -0,0 +1,89 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Surround: Settings > Surround opens the editor screen, which switches the + * effect on and holds the delay, 5 to 30 ms, and the five values that shape + * the stage. The output-stage hook runs what is chosen on every buffer. */ + +#include "rv_api.h" +#include "rv_audio.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +static const struct rv_setting settings[] = { + RV_SETTING_INT(KEY_ON, "Surround", ON_DEFAULT, 0, ON_LABELS - 1), + RV_SETTING_INT(KEY_DELAY, NULL, DELAY_DEFAULT, 0, DELAY_LABELS - 1), + RV_SETTING_INT(KEY_EMPHASIS, NULL, EMPHASIS_DEFAULT, 0, EMPHASIS_LABELS - 1), + RV_SETTING_INT(KEY_LOW, NULL, LOW_DEFAULT, 0, LOW_LABELS - 1), + RV_SETTING_INT(KEY_HIGH, NULL, HIGH_DEFAULT, 0, HIGH_LABELS - 1), + RV_SETTING_INT(KEY_SIDE_ONLY, NULL, SIDE_ONLY_DEFAULT, 0, SIDE_ONLY_LABELS - 1), + RV_SETTING_INT(KEY_MIX, NULL, MIX_DEFAULT, 0, MIX_LABELS - 1), +}; + +/* Leaves what the settings say for the pump task. */ +static void publish(void) +{ + struct surround_set set = { + .on = (uint8_t)api->setting_get_int(self, KEY_ON), + .delay_ms = (uint8_t)delay_ms(api->setting_get_int(self, KEY_DELAY)), + .emphasis = (uint8_t)api->setting_get_int(self, KEY_EMPHASIS), + .side_only = (uint8_t)api->setting_get_int(self, KEY_SIDE_ONLY), + .mix = (uint8_t)mix_percent(api->setting_get_int(self, KEY_MIX)), + .low_hz = (uint16_t)low_hz(api->setting_get_int(self, KEY_LOW)), + .high_hz = (uint16_t)high_hz(api->setting_get_int(self, KEY_HIGH)), + }; + surround_publish(&set); +} + +static void setting_changed(uint16_t key) +{ + (void)key; + publish(); +} + +/* The processed output before Apple submits it: (samples, frames, context). + * Only 16-bit stereo at the rates the delay line is sized for is touched. */ +static uint32_t on_output(uint32_t samples, uint32_t frames, uint32_t context, + const void *next) +{ + uint32_t rate; + if (rv_audio_stereo16((const void *)context, frames, 8000, SURROUND_MAX_RATE, + &rate)) + surround_process((int16_t *)samples, frames, rate); + return api->hook_next(next, samples, frames, context, 0, 0, 0); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER_AT(RV_SITE_AudioOutputQueue_Get_call, on_output, + RV_AUDIO_STAGE_SURROUND), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_SOUND_CHECK, + RV_ROW_PUSH("Surround", "editor"), + .pane = RV_PANE(.bitmap = RV_BITMAP("settings-surround")), + .caption_setting = KEY_ON, .host = "sound-menu", + .host_screen = "sound", .host_after = "sound-check"), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .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; + surround_start(core); + return &extension; +} diff --git a/extensions/surround/manifest.toml b/extensions/surround/manifest.toml new file mode 100644 index 0000000..05e32a7 --- /dev/null +++ b/extensions/surround/manifest.toml @@ -0,0 +1,27 @@ +id = "surround" +name = "Surround" +description = "A wider stage for headphones: the right channel arrives a few milliseconds late outside a band you keep in place, with the image recentred." +version = "0.1.0" +author = "RevolaOS" +note = "Based on Rockbox's Haas surround" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "effects" + +[libraries] +required = ["dsp"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "editor" +trigger = "screen" +screens = ["editor"] + +[[asset]] +name = "settings-surround" +file = "assets/settings-surround.png" +pane = "icon" diff --git a/extensions/surround/response.c b/extensions/surround/response.c new file mode 100644 index 0000000..144e0b4 --- /dev/null +++ b/extensions/surround/response.c @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the processing does to the right channel, or the side, for the + * editor's plot: the one-pole low-passes of design.c in double precision + * without a math library, then |H| along a log frequency axis. Only the editor + * module carries this. */ + +#include "rv_dsp.h" +#include "shared.h" + +/* The one-pole coefficient as design.c has it, from the same tangent. */ +static double coefficient(unsigned int hz, unsigned int rate) +{ + double x = 3.141592653589793238 * hz / rate; + if (x > 0.45 * 3.141592653589793238) + x = 0.45 * 3.141592653589793238; + double s, c; + rv_sin_cos(x, &s, &c); + double t = s / c; + return 2.0 * t / (1.0 + t); +} + +/* H = (k / 2) (1 + z^-1) / (1 - (1 - k) z^-1) at the angle with cosine c and + * sine s, as its real and imaginary parts. */ +static void one_pole(double k, double c, double s, double *re, double *im) +{ + double p = 1.0 - k; + double nr = 1.0 + c, ni = -s; /* 1 + e^-jw */ + double dr = 1.0 - p * c, di = p * s; /* 1 - p e^-jw */ + double d = dr * dr + di * di; + *re = 0.5 * k * (nr * dr + ni * di) / d; + *im = 0.5 * k * (ni * dr - nr * di) / d; +} + +static int16_t to_tenths(double re, double im) +{ + double power = re * re + im * im; + if (power < 1e-9) + return SURROUND_NO_PATH; + double db = rv_log(power) * 43.42944819032518; + return (int16_t)(db + (db < 0.0 ? -0.5 : 0.5)); +} + +void surround_response(const struct surround_set *set, unsigned int rate, int16_t *kept, + int16_t *delayed, unsigned int points) +{ + /* 20 Hz to 20 kHz is three decades; each point is one step of that. */ + double ratio = rv_exp(6.907755278982137052 / (points - 1)); + if (!set->on || set->mix == 0) { + for (unsigned int i = 0; i < points; i++) { + kept[i] = 0; + delayed[i] = SURROUND_NO_PATH; + } + return; + } + double k_low = coefficient(set->low_hz, rate), + k_high = coefficient(set->high_hz, rate); + double hz = 20.0; + for (unsigned int i = 0; i < points; i++) { + double s, c, low_re, low_im, high_re, high_im; + rv_sin_cos(6.283185307179586477 * hz / rate, &s, &c); + one_pole(k_low, c, s, &low_re, &low_im); + one_pole(k_high, c, s, &high_re, &high_im); + double kept_re = high_re - low_re, kept_im = high_im - low_im; + kept[i] = to_tenths(kept_re, kept_im); + delayed[i] = to_tenths(1.0 - kept_re, -kept_im); + hz *= ratio; + } +} diff --git a/extensions/surround/screenshots/editor.png b/extensions/surround/screenshots/editor.png new file mode 100644 index 0000000000000000000000000000000000000000..d71081a4a4990229d6e69204e4924ef599cdb541 GIT binary patch literal 15132 zcmaKTWl$VZyXN5T7A&|04<4KZ2=4A71b255+zIZ^V8Pu9&fxBD!66K8+qu7X?|%1I zQB)Vz-Sjzq&ig*r;mV5A7^ozuAP@*c=JO|25C}#LIKDuJ1%AIMy%Pd~C_yrx#MM1A zPqTb2@RnX)MIUL5QpE`AC(-aqs_Pg}@X-`?Oz`GKqwWyY+KnU7cu#srw6tfKe~l5? zWvqy{ml8cS8eZ@kIFJ)1erldZW|nHMoe^!NMU#~-ae?p0VHxcvd|&;YY*EbLKQmP^ zVff0~+Yo_bI>jkecR(n;IA*k>3!GL7zlezE=Dm_ArR=;m&ff=B%U=5|i zmwe}=ide`VxM&+?&fZEh#u?f8U>KZalN5JMi)3smuP#jApD7MPkmagN8BTg)R0_nZ zNKCFLiFRQdp?i-63V;MJb*tHQ#*`m}ix{+;+v$R9%jw!q608DRYbz0#wIq3}NaV6C zxkk*<#4xc>PMrAQ%WCLKi^odY19hj!>PqlPb6?4oWrzIEF5n0&0&Hoppuk6ti3BRK3hvao=t*wm{TpHpThJ;b|DB75BZ}L)Yb%kf@{MkH#rb z?(xIw_7C7)Jx+f6ciEki#aB2hO?-s=}0d;|JftHq#jZi&`uvYLaoiXfRmC`D}jlW0_`EVu@{7ScD(`{!RC;5#zfV!Z;%)FR24h zkq1*3S6hu_v%?m3?xOF1T~}k^TVq@2HfHA<=JFNN!GS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PVg>!aqOK3Q8%hwGK51wC!mFcd_djw&GPoGs{W_XOoPw9B?9{;=r& zUTIblQ0JIsa7AE17v`hJ)$;MLKg%r&IFP1iYI_v{2j$?vQ;!khBlZl}O!T#!LMdGl zh~xF#6Ob9(c(w8v06MgxC899%2j&AX7Bj`R6_l#r9)=h2t?Sb;kc(^%Jbhh`#g5OG z#h2Vlp1*IYvrrnbjHV>R482Vx>e2~ci^d>-L-Ohbs0?R2XDkpPu`<~AT z+B7Dk*K!L28`1y*?m)Zg!T5oq2B{fD~(|8r%lF zY8SX3W6Zhd>dN1rFhw#VKmXOT%Jmfz4hy;uJ`vpMm8wX7%R-z&U2W5ORcg13)awD& zTikfFjpuj+VFB@HjRzmI)@2&<6iGR#CFshaG$Cv?2B1|o<^e|qfv|F+jrvV2OFM<%WTTJ4qI_nCJU&QXKV1xY3a~Y2H02rVS}9VLW;(uJ&RFxT#BrP2h%NR2cQ7qZdATtLQIM>F!$f{u5?__h3&%63UXG@N&tqlwZHSl?-0N$C_##?;+uz1Ls zGUEXKLI5}3V*sbR3!h|95qu)L>=Nh1`I?2*XQPbSf zw(&a!iw$B7JEn!DY}{rA`R)ZQBVQsD(!nbDJi=Vj6z>#f0BpiF1O#Yu!j?k-Y7|V0 zmXyK`WbIeOg4jYG)+Ck~w~)Sr5Bqw9+UW(e#xLXpnW=T-OCaS$AWCk6p7UYV(!|C* z;C}ADm0Ox673zwXTma+nz|WE`@*1NtF_nMy_42YJLDN`p{biVJR^VQcrB9> SAMPLE_SHIFT; +} + +/* Takes over the set the UI task left, fading from what played when the rate is + * the same. A set left meanwhile moves the generation again, and the next call + * takes that one; a set left while an on/off fade or a lead lasts waits for + * its end, which surround_process checks. The delay line starts over when the + * delay, Side Only or the rate changes, and the fade waits for the new line to + * fill; the filters start over with it except for a new delay alone, and new + * cutoffs, emphasis or mix continue everything. A rate change comes with a + * track, so it ends a fade instead of starting one. */ +static void take(uint32_t rate) +{ + struct surround_set was = playing.set; + unsigned int was_on = playing.on, same_rate = rate == effect.rate; + if (same_rate) + fading = playing; + rv_handoff_take(&effect.handoff, &playing.set, &next, sizeof playing.set); + const struct surround_set *set = &playing.set; + playing.on = set->on && set->mix != 0; + playing.k_low = (int32_t)surround_coefficient(set->low_hz, rate); + playing.k_high = (int32_t)surround_coefficient(set->high_hz, rate); + playing.lead = UNITY - (int32_t)(UNITY * (uint32_t)set->emphasis / 200); + playing.lag = UNITY + (int32_t)(UNITY * (uint32_t)set->emphasis / 200); + playing.wet = (int32_t)(UNITY * (uint32_t)set->mix / 100); + uint32_t length = set->delay_ms * rate / 1000; + if (length > SURROUND_DELAY_FRAMES) + length = SURROUND_DELAY_FRAMES; + int new_input = !was_on || !same_rate || set->side_only != was.side_only; + int restart = new_input || set->delay_ms != was.delay_ms; + if (new_input) + playing.low = playing.high = playing.previous = 0; + if (restart) { + memset(playing.delay, 0, sizeof playing.delay); + playing.delay_index = 0; + playing.delay_length = length; + } + /* Turning on, the limiter starts empty and the line fills while the old + * state plays alone; a new line while on waits for the fill too. Turning + * on with a new rate has no fade, so its first frames are silence. */ + int turns_on = playing.on && !was_on; + if (turns_on) + rv_limiter_rest(&limiter); + rv_effect_taken(&effect, rate, + turns_on ? length + RV_LIMITER_FRAMES + : restart && playing.on ? length + : 0); +} + +static int run(void *state, const int16_t *in, int32_t *out, uint32_t frames) +{ + struct surround_state *s = state; + if (!s->on) + return 0; + const int32_t k_low = s->k_low, k_high = s->k_high, lead = s->lead, lag = s->lag, + wet = s->wet, side_only = s->set.side_only; + int32_t low = s->low, high = s->high, previous = s->previous; + int16_t *delay = s->delay, *di = delay + s->delay_index; + const int16_t *end_of_line = delay + s->delay_length; + for (const int16_t *end = in + frames * 2; in < end; in += 2, out += 2) { + int32_t l = (int32_t)in[0] * (1 << SAMPLE_SHIFT); + int32_t r = (int32_t)in[1] * (1 << SAMPLE_SHIFT); + int32_t u = side_only ? (l - r) >> 1 : r; + + /* The band between the cutoffs stays; the rest goes down the line. + * Each low-pass is the bilinear one: the pole from the coefficient, + * the zero at Nyquist from the mean of this input and the last. */ + int32_t half = (u + previous) >> 1; + previous = u; + low += (int32_t)(((int64_t)k_low * (half - low)) >> 30); + high += (int32_t)(((int64_t)k_high * (half - high)) >> 30); + int32_t kept = high - low, band = u - kept; + int32_t late = (int32_t)*di * (1 << SAMPLE_SHIFT); + *di = rv_saturate16(output(band)); + if (++di >= end_of_line) + di = delay; + int32_t processed = kept + late; + + int32_t wet_l, wet_r; + if (side_only) { + /* The emphasis moves the side parts only; the mid stays put. */ + int32_t mid = (l + r) >> 1; + wet_l = mid + (int32_t)(((int64_t)u * lead) >> 15); + wet_r = mid - (int32_t)(((int64_t)processed * lag) >> 15); + } else { + wet_l = (int32_t)(((int64_t)l * lead) >> 15); + wet_r = (int32_t)(((int64_t)processed * lag) >> 15); + } + out[0] = output(l + (int32_t)(((int64_t)(wet_l - l) * wet) >> 15)); + out[1] = output(r + (int32_t)(((int64_t)(wet_r - r) * wet) >> 15)); + } + s->low = low; + s->high = high; + s->previous = previous; + s->delay_index = (uint32_t)(di - delay); + return 1; +} + +/* A set waits while an on/off fade lasts and while a lead runs, so a fade + * never carries over a line that is still filling. */ +void surround_process(int16_t *samples, uint32_t frames, uint32_t rate) +{ + int lead = effect.fade.remaining > RV_FADE_FRAMES; + if ((rv_effect_pending(&effect, rate) && !lead) || rate != effect.rate) + take(rate); + rv_fade_run_limited(&effect.fade, &limiter, run, &playing, &fading, samples, + frames); +} diff --git a/extensions/surround/surround.h b/extensions/surround/surround.h new file mode 100644 index 0000000..5c101dc --- /dev/null +++ b/extensions/surround/surround.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef SURROUND_H +#define SURROUND_H + +#include + +struct rv_api; + +/* What the settings say, in the units the engine uses: whether it plays, the + * delay in milliseconds, the emphasis in percent, the two cutoffs in hertz, + * side only and the wet share of the mix in percent. */ +struct surround_set { + uint8_t on; + uint8_t delay_ms; + uint8_t emphasis; + uint8_t side_only; + uint8_t mix; + uint16_t low_hz, high_hz; +}; + +enum { + SURROUND_MAX_DELAY_MS = 30, + SURROUND_MAX_RATE = 48000, + /* The delay line, one channel, at the longest delay and the highest rate. */ + SURROUND_DELAY_FRAMES = SURROUND_MAX_DELAY_MS * SURROUND_MAX_RATE / 1000, +}; + +/* design.c: the coefficient of the bilinear one-pole low-pass for a cutoff at + * `rate` as Q30, 2 t / (1 + t) with t = tan(pi hz / rate), the cutoff held + * below 0.45 of the rate; integer throughout, for the pump task. */ +uint32_t surround_coefficient(unsigned int hz, unsigned int rate); + +/* surround.c: `publish` leaves a set for the pump task from any task; + * `process` runs the set that plays on `frames` interleaved stereo S16 frames in + * place, on the pump task only. */ +void surround_start(const struct rv_api *core); +void surround_publish(const struct surround_set *set); +void surround_process(int16_t *samples, uint32_t frames, uint32_t rate); + +#endif diff --git a/extensions/surround/tests/host.c b/extensions/surround/tests/host.c new file mode 100644 index 0000000..426890a --- /dev/null +++ b/extensions/surround/tests/host.c @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The rv_api the host tests hand surround.c: interrupt masking that counts. */ + +#include "surround.h" +#include "rv_api.h" + +static uint32_t irq_calls; + +static uint32_t irq_save(void) +{ + irq_calls++; + return 0; +} + +static void irq_restore(uint32_t state) +{ + (void)state; + irq_calls++; +} + +uint32_t test_irq_calls(void) +{ + return irq_calls; +} + +static const struct rv_api api = { + .size = sizeof api, .irq_save = irq_save, .irq_restore = irq_restore}; + +__attribute__((constructor)) static void start(void) +{ + surround_start(&api); +} diff --git a/extensions/surround/tests/run.py b/extensions/surround/tests/run.py new file mode 100644 index 0000000..573800a --- /dev/null +++ b/extensions/surround/tests/run.py @@ -0,0 +1,418 @@ +#!/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 cmath +import ctypes +import math +import sys +import tempfile +from itertools import pairwise +from pathlib import Path + +root = Path(__file__).resolve().parent +dsp = root.parents[1] / "dsp" +shared = root.parents[1] / "shared" +sys.path.insert(0, str(dsp / "tests")) +from harness import build, labeller # noqa: E402 +from harness import noise as stereo_noise # noqa: E402 +from model import Limiter, saturate # noqa: E402 + +SHIFT = 12 +Q30 = 1 << 30 +UNITY = 1 << 15 +RATES = (44100, 48000, 32000, 22050, 8000) +DELAYS = (5, 8, 10, 15, 30) +MAX_FRAMES = 30 * 48000 // 1000 +FADE = 128 + + +class Set(ctypes.Structure): + _fields_ = [ + ("on", ctypes.c_uint8), + ("delay_ms", ctypes.c_uint8), + ("emphasis", ctypes.c_uint8), + ("side_only", ctypes.c_uint8), + ("mix", ctypes.c_uint8), + ("low_hz", ctypes.c_uint16), + ("high_hz", ctypes.c_uint16), + ] + + +def coefficient_reference(hz, rate): + """2 tan(pi f / rate) / (1 + tan), the cutoff held below 0.45 of the rate.""" + x = min(math.pi * min(hz, rate - 1) / rate, 0.45 * math.pi) + t = math.tan(x) + return 2 * t / (1 + t) + + +def coefficient_tests(dll): + coefficient = dll.surround_coefficient + for rate in RATES: + for hz in list(range(40, 401, 40)) + list(range(600, 8001, 200)): + got = coefficient(hz, rate) / Q30 + expected = coefficient_reference(hz, rate) + assert abs(got - expected) <= 1e-4 * expected, (rate, hz, got, expected) + # The -3 dB point of the one-pole sits at the cutoff. + for hz in (320, 3400): + if hz * 2.5 > rate: + continue + k = coefficient(hz, rate) / Q30 + z = cmath.exp(-2j * math.pi * hz / rate) + h = k / 2 * (1 + z) / (1 - (1 - k) * z) + assert abs(20 * math.log10(abs(h)) + 3.01) < 0.02, (rate, hz, abs(h)) + assert coefficient(8000, 8000) == coefficient(7999, 8000) + assert coefficient(100, 0) == 0 + + +def label_tests(dll): + labels = labeller(dll.surround_label) + ON, DELAY, MIX, EMPHASIS, LOW, HIGH, SIDE = range(7) + + assert labels(ON, 2) == ["Off", "On"] + assert labels(DELAY, 5) == ["5 ms", "8 ms", "10 ms", "15 ms", "30 ms"] + assert labels(MIX, 21) == [f"{5 * i} %" for i in range(21)] + assert labels(EMPHASIS, 100) == [f"{i} %" for i in range(100)] + assert labels(LOW, 10) == [f"{40 + 40 * i} Hz" for i in range(10)] + highs = labels(HIGH, 38) + assert highs[0] == "600 Hz" and highs[14] == "3.4k Hz" and highs[-1] == "8k Hz" + assert labels(SIDE, 2) == ["Off", "On"] + + +def response_tests(dll): + """The editor's curves: the band between Low and High near 0 dB and falling + off either side, the late part the complement, nothing late while Off.""" + response = dll.surround_response + response.argtypes = [ctypes.POINTER(Set), ctypes.c_uint] + response.argtypes += [ctypes.POINTER(ctypes.c_int16)] * 2 + [ctypes.c_uint] + response.restype = None + points = 261 + hertz = [20 * 1000 ** (i / (points - 1)) for i in range(points)] + + def curves(chosen): + kept = (ctypes.c_int16 * points)() + late = (ctypes.c_int16 * points)() + response(chosen, 44100, kept, late, points) + return list(kept), list(late) + + def model(low_hz, high_hz, hz): + out = [] + for cutoff in (low_hz, high_hz): + k = coefficient_reference(cutoff, 44100) + z = cmath.exp(-2j * math.pi * hz / 44100) + out.append(k / 2 * (1 + z) / (1 - (1 - k) * z)) + kept = out[1] - out[0] + return kept, 1 - kept + + for low_hz, high_hz in ((320, 3400), (40, 600), (400, 8000)): + chosen = Set(1, 10, 35, 0, 50, low_hz, high_hz) + kept, late = curves(chosen) + for hz, k, d in zip(hertz, kept, late, strict=True): + mk, md = model(low_hz, high_hz, hz) + assert abs(k - 200 * math.log10(abs(mk))) <= 1, (hz, k, mk) + assert abs(d - 200 * math.log10(abs(md))) <= 1, (hz, d, md) + middle = next( + i for i, hz in enumerate(hertz) if hz >= math.sqrt(low_hz * high_hz) + ) + assert kept[middle] > -40 + assert kept[0] < -60 and kept[-1] < kept[middle] + assert late[0] > -15 and late[-1] > -10 + kept, late = curves(Set(0, 10, 35, 0, 50, 320, 3400)) + assert kept == [0] * points and late == [-32768] * points + kept, late = curves(Set(1, 10, 35, 0, 0, 320, 3400)) + assert kept == [0] * points and late == [-32768] * points + + +def output(sample): + return (sample + (1 << (SHIFT - 1))) >> SHIFT + + +class Reference: + """surround.c's loop in Python integers: one state at one rate.""" + + def __init__(self, dll, chosen, rate): + self.chosen = chosen + self.on = chosen.on != 0 and chosen.mix != 0 + self.k_low = dll.surround_coefficient(chosen.low_hz, rate) + self.k_high = dll.surround_coefficient(chosen.high_hz, rate) + self.lead = UNITY - UNITY * chosen.emphasis // 200 + self.lag = UNITY + UNITY * chosen.emphasis // 200 + self.wet = UNITY * chosen.mix // 100 + self.length = min(chosen.delay_ms * rate // 1000, MAX_FRAMES) + self.low = self.high = self.previous = 0 + self.delay = [0] * max(self.length, 1) + self.index = 0 + + def copy_filters(self, other): + self.low, self.high, self.previous = other.low, other.high, other.previous + + def copy_line(self, other): + self.delay, self.index = list(other.delay), other.index + + def play(self, frames): + out = [] + side_only = self.chosen.side_only + for left, right in frames: + left <<= SHIFT + right <<= SHIFT + u = (left - right) >> 1 if side_only else right + half = (u + self.previous) >> 1 + self.previous = u + self.low += (self.k_low * (half - self.low)) >> 30 + self.high += (self.k_high * (half - self.high)) >> 30 + kept = self.high - self.low + band = u - kept + late = self.delay[self.index] << SHIFT + self.delay[self.index] = saturate(output(band)) + self.index = (self.index + 1) % self.length + processed = kept + late + if side_only: + mid = (left + right) >> 1 + wet_l = mid + ((u * self.lead) >> 15) + wet_r = mid - ((processed * self.lag) >> 15) + else: + wet_l = (left * self.lead) >> 15 + wet_r = (processed * self.lag) >> 15 + out.append( + ( + output(left + (((wet_l - left) * self.wet) >> 15)), + output(right + (((wet_r - right) * self.wet) >> 15)), + ) + ) + return out + + +def noise(count, seed, panned=False): + frames = stereo_noise(count, seed) + if panned: + frames = [(left, 0) for left, _ in frames] + frames[0] = (0, 32767) + return frames + + +def process_tests(dll): + publish = dll.surround_publish + publish.argtypes = [ctypes.POINTER(Set)] + publish.restype = None + process = dll.surround_process + process.argtypes = [ctypes.POINTER(ctypes.c_int16)] + [ctypes.c_uint32] * 2 + process.restype = None + dll.test_irq_calls.restype = ctypes.c_uint32 + count = 512 + + def make( + on=1, delay_ms=10, emphasis=35, side_only=0, mix=50, low_hz=320, high_hz=3400 + ): + return Set(on, delay_ms, emphasis, side_only, mix, low_hz, high_hz) + + engine = {"new": Reference(dll, make(on=0), 44100), "rate": 44100} + engine.update(old=None, remaining=0, pending=None) + limiter = Limiter() + + def switching(): + old = engine["old"] + return bool( + engine["remaining"] and old is not None and old.on != engine["new"].on + ) + + def take(chosen, rate): + old, new = engine["new"], Reference(dll, chosen, rate) + same_rate = rate == engine["rate"] + was = old.chosen + new_input = not old.on or not same_rate or chosen.side_only != was.side_only + restart = new_input or chosen.delay_ms != was.delay_ms + if not new_input: + new.copy_filters(old) + if not restart: + new.copy_line(old) + turns_on = new.on and not old.on + if turns_on: + limiter.rest() + engine["new"] = new + engine["rate"] = rate + if same_rate: + if turns_on: + lead = new.length + Limiter.FRAMES + elif restart and new.on: + lead = new.length + else: + lead = 0 + engine["old"], engine["remaining"] = old, FADE + lead + else: + engine["old"], engine["remaining"] = None, 0 + + def switch(chosen): + publish(chosen) + engine["pending"] = chosen + + def expected(frames, rate): + pending = engine["pending"] + lead = engine["remaining"] > FADE + held = switching() or lead + if (pending is not None and not held) or rate != engine["rate"]: + take(pending if pending is not None else engine["new"].chosen, rate) + engine["pending"] = None + new, old = engine["new"], engine["old"] + new_out = new.play(frames) if new.on else None + running = old is not None and engine["remaining"] and old.on + old_out = old.play(frames) if running else None + out = [] + for i, frame in enumerate(frames): + remaining = engine["remaining"] + if not remaining: + out.append(frame if new_out is None else limiter.run(new_out[i])) + continue + weight = 0 if remaining > FADE else FADE + 1 - remaining + if old_out is not None and new_out is not None: + mixed = tuple( + (Limiter.clamp(a) * (FADE - weight) + Limiter.clamp(b) * weight) + >> 7 + for a, b in zip(old_out[i], new_out[i], strict=True) + ) + out.append(limiter.run(mixed)) + elif old_out is not None or new_out is not None: + alone = limiter.run(old_out[i] if old_out is not None else new_out[i]) + if old_out is not None: + weight = FADE - weight + out.append( + tuple( + (x * (FADE - weight) + y * weight) >> 7 + for x, y in zip(frame, alone, strict=True) + ) + ) + else: + out.append(frame) + engine["remaining"] -= 1 + if not engine["remaining"]: + engine["old"] = None + return out + + def run(frames, rate, *splits): + buffer = (ctypes.c_int16 * (2 * len(frames)))( + *[s for frame in frames for s in frame] + ) + edges = [0, *splits, len(frames)] + for first, last in pairwise(edges): + process( + ctypes.cast(ctypes.byref(buffer, 4 * first), process.argtypes[0]), + last - first, + rate, + ) + return [(buffer[2 * i], buffer[2 * i + 1]) for i in range(len(frames))] + + def play(frames, rate, *splits): + got = run(frames, rate, *splits) + edges = [0, *splits, len(frames)] + model = [f for a, b in pairwise(edges) for f in expected(frames[a:b], rate)] + assert got == model, (rate, splits) + return got + + # Off and Mix 0 leave the stream alone; one publish masks interrupts once. + switch(make(on=0)) + frames = noise(count, 1) + assert play(frames, 44100) == frames + assert dll.test_irq_calls() == 2 + switch(make(mix=0)) + frames = noise(count, 2) + assert play(frames, 44100) == frames + + # Every delay at every rate, bit for bit, across buffer edges; a right-only + # impulse never reaches the left ear at Emphasis 0, its kept band passes at + # once and its late part arrives after the line. + for rate in RATES: + for delay in DELAYS: + chosen = make(delay_ms=delay, emphasis=0, mix=100) + switch(chosen) + for block in range(2): + play(noise(count, block + rate + delay, panned=True), rate, 17, 100) + alone = Reference(dll, chosen, rate) + frames = [(0, 32767)] + [(0, 0)] * (MAX_FRAMES + 8) + out = alone.play(frames) + length = delay * rate // 1000 + assert all(left == 0 for left, _ in out) + assert out[0][1] != 0 + assert abs(out[length][1]) > abs(out[length - 1][1]) + 100, (rate, delay) + + # Mono input in Side Only comes out unchanged at any Emphasis: it moves + # the side parts only. + for emphasis in (0, 99): + chosen = make(side_only=1, emphasis=emphasis, mix=100) + switch(chosen) + frames = [(s, s) for s, _ in noise(count, 9 + emphasis)] + play(frames, 44100) + assert Reference(dll, chosen, 44100).play(frames) == frames + + # New cutoffs, emphasis or mix keep the line and filters and fade; a new + # delay or Side Only starts them over behind a fade as long as the line. + switch(make(low_hz=80, high_hz=6000)) + play(noise(count, 20), 44100) + switch(make(low_hz=80, high_hz=6000, emphasis=99)) + play(noise(count, 21), 44100) + switch(make(low_hz=80, high_hz=6000, emphasis=99, mix=25)) + play(noise(count, 22), 44100, 50) + switch(make(delay_ms=30)) + play(noise(4 * count, 23), 44100) + switch(make(delay_ms=30, side_only=1)) + play(noise(4 * count, 24), 44100, 33) + + # A rate change ends a fade and starts over; a set left during an on/off + # fade waits for its end. + switch(make(delay_ms=5)) + play(noise(64, 25), 44100) + play(noise(count, 26), 48000) + switch(make(on=0)) + play(noise(count, 27), 48000) + switch(make(delay_ms=8)) + play(noise(50, 28), 48000) + assert switching() + switch(make(delay_ms=15)) + play(noise(2 * count, 29), 48000, 40) + assert engine["pending"] is not None and not switching() + play(noise(2 * count, 30), 48000) + assert engine["pending"] is None + + # A set left while a new line fills waits for the fill, so a fade never + # carries over a half-filled line. + switch(make(delay_ms=10)) + play(noise(count, 31), 44100) + switch(make(delay_ms=30)) + play(noise(100, 32), 44100) + assert not switching() and engine["remaining"] > FADE + switch(make(delay_ms=30, mix=100)) + play(noise(count, 33), 44100) + assert engine["pending"] is not None + play(noise(2 * count, 34), 44100, 300) + assert engine["pending"] is not None and not engine["remaining"] + play(noise(count, 35), 44100) + assert engine["pending"] is None and engine["new"].chosen.mix == 100 + + # A full-scale anti-phase square at Emphasis 99 goes over, which the limiter + # holds at full scale instead of wrapping. + chosen = make(emphasis=99, mix=100) + switch(chosen) + square = [ + (32767, -32767) if i // 50 % 2 else (-32767, 32767) for i in range(4 * count) + ] + wide = Reference(dll, chosen, 48000).play(square) + assert max(abs(s) for frame in wide for s in frame) > 32767 + got = play(square, 48000) + assert 32000 < max(abs(s) for frame in got for s in frame) <= 32767 + + +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="surround-tests-") as name: + work = Path(name) + sources = [root / "host.c", sdk / "rv_libc.c"] + sources += [dsp / file for file in ("math.c", "limiter.c")] + sources += [ + root.parent / file + for file in ("surround.c", "design.c", "labels.c", "response.c") + ] + dll = build(work, "surround.so", sources, [sdk, dsp, shared, root.parent]) + dll.surround_coefficient.argtypes = [ctypes.c_uint, ctypes.c_uint] + dll.surround_coefficient.restype = ctypes.c_uint32 + coefficient_tests(dll) + label_tests(dll) + response_tests(dll) + process_tests(dll) +print("Surround tests passed") diff --git a/themes/docs/extension-bitmaps.md b/themes/docs/extension-bitmaps.md index 0fa66ca..04b4191 100644 --- a/themes/docs/extension-bitmaps.md +++ b/themes/docs/extension-bitmaps.md @@ -20,10 +20,15 @@ Regenerate this page with `python3 tools/extension_bitmaps_doc.py`. | `appearance` | `settings-moon` | 78x121 | mask8 | - | yes | | `appearance` | `settings-theme` | 78x121 | mask8 | - | yes | | `balance` | `settings-balance` | 78x121 | mask8 | - | yes | +| `bass-enhancement` | `settings-bass-enhancement` | 78x121 | mask8 | - | yes | +| `channels` | `settings-channels` | 78x121 | mask8 | - | yes | +| `compressor` | `settings-compressor` | 78x121 | mask8 | - | yes | | `crossfeed` | `settings-crossfeed` | 78x121 | mask8 | - | yes | | `equalizer` | `settings-eq` | 78x121 | mask8 | - | yes | +| `fatigue-reduction` | `settings-fatigue-reduction` | 78x121 | mask8 | - | yes | | `homebrew` | `apps` | 142x87 | bgra8888 | - | no | | `night-shift` | `settings-night-shift` | 78x121 | mask8 | - | yes | | `playback-log` | `settings-playback-log` | 78x121 | mask8 | - | yes | | `reprise` | `settings-info` | 78x121 | mask8 | - | yes | | `sound-menu` | `settings-sound` | 78x121 | mask8 | - | yes | +| `surround` | `settings-surround` | 78x121 | mask8 | - | yes | diff --git a/themes/rvt/data/extensions.json b/themes/rvt/data/extensions.json index e67f600..1b33544 100644 --- a/themes/rvt/data/extensions.json +++ b/themes/rvt/data/extensions.json @@ -5,10 +5,15 @@ {"asset": "settings-moon", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "appearance", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-theme", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "appearance", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-balance", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "balance", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} +{"asset": "settings-bass-enhancement", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "bass-enhancement", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} +{"asset": "settings-channels", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "channels", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} +{"asset": "settings-compressor", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "compressor", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-crossfeed", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "crossfeed", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-eq", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "equalizer", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} +{"asset": "settings-fatigue-reduction", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "fatigue-reduction", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "apps", "bytes": 49444, "depth": 32, "format": 6280, "height": 87, "id": "homebrew", "menu": false, "palette_colors": 0, "preload": "optional", "stride": 568, "width": 142} {"asset": "settings-night-shift", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "night-shift", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-playback-log", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "playback-log", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-info", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "reprise", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} {"asset": "settings-sound", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "sound-menu", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78} +{"asset": "settings-surround", "bytes": 9708, "depth": 8, "format": 8, "height": 121, "id": "surround", "menu": true, "palette_colors": 0, "preload": "optional", "stride": 80, "width": 78}