perf(theme): extract cover palettes with native quantization

Port the pinned Material quantizer and Dart RNG compatibility to Rust while keeping Material Score and final color schemes in Dart. Include exact palette fixtures, licenses, and Kotlin worker ABI coverage.
This commit is contained in:
zarzet committed 2026-10-06 23:27:38 +07:00
1 parent 927fd033cd
commit d693e1a479
13 files changed
+1077 -6

No files matched your search

@@ -0,0 +1,150 @@
package com.zarz.spotiflac
import com.spotiflac.backend.NativeDataJobException
import com.spotiflac.backend.RequestLease
import java.io.File
import java.nio.file.Files
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.BeforeClass
import org.junit.Test
/** Exercises the actual generated Kotlin ABI against the host Rust library.
* Set SPOTIFLAC_NATIVE_HOST_LIBRARY to the host dylib/so and optionally
* SPOTIFLAC_JNA_HOST_DIRECTORY to desktop JNA's native dispatch directory.
* Ordinary Android-only checkouts skip these host ABI tests.
*/
class NativeDataJobsTest {
companion object {
@BeforeClass @JvmStatic
fun configureHostLibrary() {
val library = System.getenv("SPOTIFLAC_NATIVE_HOST_LIBRARY")
assumeTrue("Build the Rust host library for ABI tests", !library.isNullOrBlank())
require(File(library!!).isFile) { "Native host library does not exist" }
System.setProperty("uniffi.component.spotiflac_mobile.libraryOverride", library)
System.getenv("SPOTIFLAC_JNA_HOST_DIRECTORY")?.let {
System.setProperty("jna.boot.library.path", it)
}
}
}
private fun <T> withLease(id: String, block: (RequestLease) -> T): T {
val lease = NativeDataJobs.acquire(id)
return try { block(lease) } finally { NativeDataJobs.release(id, lease) }
}
@Test fun pureJobsWorkBeforeExtensionInitializationAndCancelledLeasesRejectWork() {
val id = UUID.randomUUID().toString()
withLease(id) { lease ->
val request = JSONObject().put("operation", "palette")
val pixels = byteArrayOf(255.toByte(), 0, 0, 255.toByte())
val result = JSONObject(RustCoreBackend.runDataJob(request, pixels, lease))
val color = result.getJSONArray("colors").getJSONArray(0)
assertEquals(0xff0000ffL, color.getLong(0))
assertEquals(1, color.getInt(1))
NativeDataJobs.cancel(id)
assertTrue(lease.isCancelled())
val error = assertThrows(NativeDataJobException.Operation::class.java) {
RustCoreBackend.runDataJob(request, pixels, lease)
}
assertTrue(error.message!!.contains("cancelled"))
}
}
@Test fun cancellationCannotLeakIntoAnotherRequestOrAnIdleReplacement() {
val cancelledId = UUID.randomUUID().toString()
val otherId = UUID.randomUUID().toString()
withLease(cancelledId) { cancelled ->
withLease(otherId) { other ->
NativeDataJobs.cancel(cancelledId)
assertTrue(cancelled.isCancelled())
assertFalse(other.isCancelled())
}
}
withLease(cancelledId) { replacement ->
assertFalse(replacement.isCancelled())
}
}
@Test fun unknownAndFinishedCancellationCannotPoisonLaterWork() {
val id = UUID.randomUUID().toString()
NativeDataJobs.cancel(id)
withLease(id) { lease -> assertFalse(lease.isCancelled()) }
NativeDataJobs.cancel(id)
withLease(id) { lease -> assertFalse(lease.isCancelled()) }
}
@Test fun sharedIdRetainsCancellationUntilEveryLeaseHasFinished() {
val id = UUID.randomUUID().toString()
val first = NativeDataJobs.acquire(id)
val second = NativeDataJobs.acquire(id)
try {
NativeDataJobs.release(id, first)
NativeDataJobs.release(id, first)
NativeDataJobs.cancel(id)
assertTrue(second.isCancelled())
} finally {
NativeDataJobs.release(id, first)
NativeDataJobs.release(id, second)
}
NativeDataJobs.cancel(id)
withLease(id) { lease -> assertFalse(lease.isCancelled()) }
}
@Test fun acquiredJobCanBeCancelledWhileStillQueuedForIo() {
val id = UUID.randomUUID().toString()
val executor = Executors.newSingleThreadExecutor()
val occupied = CountDownLatch(1)
val proceed = CountDownLatch(1)
val lease = NativeDataJobs.acquire(id)
try {
executor.submit {
occupied.countDown()
check(proceed.await(5, TimeUnit.SECONDS))
}
assertTrue(occupied.await(5, TimeUnit.SECONDS))
val queued = executor.submit<String> {
RustCoreBackend.runDataJob(
JSONObject().put("operation", "palette"),
byteArrayOf(255.toByte(), 0, 0, 255.toByte()),
lease,
)
}
NativeDataJobs.cancel(id)
proceed.countDown()
val error = assertThrows(ExecutionException::class.java) {
queued.get(5, TimeUnit.SECONDS)
}
assertTrue(error.cause is NativeDataJobException.Operation)
assertTrue(error.cause!!.message!!.contains("cancelled"))
} finally {
proceed.countDown()
executor.shutdownNow()
NativeDataJobs.release(id, lease)
}
}
@Test fun streamedHashJobUsesTheGeneratedByteArrayAndLeaseABI() {
val path = Files.createTempFile("native-job-hash-", ".bin")
try {
Files.write(path, "abc".toByteArray())
withLease(UUID.randomUUID().toString()) { lease ->
val request = JSONObject().put("operation", "hash_file").put("path", path.toString())
val result = JSONObject(RustCoreBackend.runDataJob(request, byteArrayOf(), lease))
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
result.getString("sha256"))
}
} finally {
Files.deleteIfExists(path)
}
}
}
+244
View File
@@ -0,0 +1,244 @@
Native palette quantization
Derived from Material Color Utilities 0.13.0 (QuantizerCelebi, QuantizerWu,
QuantizerWsmeans and color conversion), Copyright 2021 Google LLC.
Source: https://github.com/material-foundation/material-color-utilities
The deterministic random generator reproduces Dart SDK 3.13.4 Random.
Copyright (c) 2012, the Dart project authors.
Source: https://github.com/dart-lang/sdk/tree/3.13.4
Material Color Utilities license
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dart SDK license
Copyright 2012, the Dart project authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+4
View File
@@ -51,6 +51,10 @@ void main() {
yield LicenseEntryWithLineBreaks(const [
'libsmb2',
], await rootBundle.loadString('assets/licenses/libsmb2.txt'));
yield LicenseEntryWithLineBreaks(const [
'Material Color Utilities (native palette)',
'Dart SDK (native Random compatibility)',
], await rootBundle.loadString('assets/licenses/native_palette.txt'));
yield LicenseEntryWithLineBreaks(const [
'rusqlite',
'roxmltree',
+106 -4
View File
@@ -3,9 +3,37 @@ import 'dart:io';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_color_utilities/quantize/quantizer_celebi.dart';
import 'package:material_color_utilities/score/score.dart';
import 'package:spotiflac_android/services/platform_bridge.dart';
import 'package:spotiflac_android/widgets/cached_cover_image.dart';
Future<List<List<int>>> _quantizePaletteInIsolate(Uint8List bytes) async {
final result = await QuantizerCelebi().quantize(
bytes.buffer.asUint32List(bytes.offsetInBytes, bytes.lengthInBytes ~/ 4),
128,
);
return [
for (final entry in result.colorToCount.entries) [entry.key, entry.value],
];
}
/// Score remains pinned to Flutter's Material implementation. Quantization
/// runs on the native worker; the byte-order conversion matches ColorScheme.
int paletteSeedFromColorCounts(List<List<int>> colors) {
final populations = <int, int>{};
for (final pair in colors) {
final abgr = pair[0];
final argb =
(abgr & 0xff00ff00) | ((abgr & 255) << 16) | ((abgr >> 16) & 255);
populations[argb] = pair[1];
}
return Score.score(populations, desired: 1).first;
}
/// Colour scheme derived from cover art, used to theme detail-screen headers.
///
/// The generated scheme follows app brightness and supplies contrasting
@@ -129,10 +157,7 @@ class CoverPalette {
height: 112,
policy: ResizeImagePolicy.fit,
);
final scheme = await ColorScheme.fromImageProvider(
provider: sample,
brightness: brightness,
);
final scheme = await _schemeFromSample(sample, brightness);
final sourceColor = await _sampleSourceColor(sample);
if (sourceColor != null) _sourceColors[key] = sourceColor;
_cache[key] = scheme;
@@ -150,6 +175,83 @@ class CoverPalette {
}
}
static Future<ColorScheme> _schemeFromSample(
ImageProvider provider,
Brightness brightness,
) async {
final result = Completer<Uint8List>();
final stream = provider.resolve(
const ImageConfiguration(size: Size(112, 112)),
);
late ImageStreamListener listener;
late Timer loadFailureTimeout;
listener = ImageStreamListener(
(info, _) async {
loadFailureTimeout.cancel();
stream.removeListener(listener);
ui.Picture? picture;
ui.Image? image;
try {
final source = info.image;
// Mirror Flutter's image-to-palette canvas/readback. Decoding,
// filtering and premultiplied alpha remain with Flutter's renderer.
final recorder = ui.PictureRecorder();
paintImage(
canvas: Canvas(recorder),
rect: Rect.fromLTWH(
0,
0,
source.width.toDouble(),
source.height.toDouble(),
),
image: source,
filterQuality: FilterQuality.none,
);
picture = recorder.endRecording();
image = await picture.toImage(source.width, source.height);
final data = await image.toByteData();
if (data == null) throw StateError('Palette readback failed');
result.complete(
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
);
} catch (error, stack) {
result.completeError(error, stack);
} finally {
image?.dispose();
picture?.dispose();
info.dispose();
}
},
onError: (Object error, StackTrace? stack) {
loadFailureTimeout.cancel();
stream.removeListener(listener);
result.completeError(error, stack);
},
);
loadFailureTimeout = Timer(const Duration(seconds: 5), () {
stream.removeListener(listener);
result.completeError(TimeoutException('Palette image loading timed out'));
});
stream.addListener(listener);
final bytes = await result.future;
late final List<List<int>> colors;
try {
final response = await PlatformBridge.runNativeDataJob({
'operation': 'palette',
}, bytes: bytes);
colors = [
for (final pair in response['colors'] as List)
[for (final value in pair as List) (value as num).toInt()],
];
} on MissingPluginException {
// Desktop tests and unsupported hosts retain exact Material output,
// with the same expensive quantizer moved off the UI isolate.
colors = await compute(_quantizePaletteInIsolate, bytes);
}
final seed = await compute(paletteSeedFromColorCounts, colors);
return ColorScheme.fromSeed(seedColor: Color(seed), brightness: brightness);
}
static Future<Color?> _sampleSourceColor(ImageProvider provider) {
final result = Completer<Color?>();
final stream = provider.resolve(ImageConfiguration.empty);
+1 -1
View File
@@ -883,7 +883,7 @@ packages:
source: hosted
version: "1.1.3"
material_color_utilities:
dependency: transitive
dependency: "direct main"
description:
name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
+2
View File
@@ -50,6 +50,7 @@ dependencies:
dynamic_color: ^2.1.0
material_ui: ^1.4.0
material_3_expressive: ^1.1.3
material_color_utilities: 0.13.0
# Permissions
permission_handler: ^13.0.1
@@ -130,6 +131,7 @@ flutter:
- assets/licenses/oboe.txt
- assets/licenses/wavpack.txt
- assets/licenses/libsmb2.txt
- assets/licenses/native_palette.txt
- assets/licenses/native_data_jobs.txt
fonts:
+4 -1
View File
@@ -1,6 +1,9 @@
# Third-party notices
The native SQLite/TTML data jobs use
`crates/core/src/native_palette.rs` ports Material Color Utilities 0.13.0
quantization (Google LLC, Apache-2.0) and Dart SDK Random compatibility
(The Dart Authors, BSD-3-Clause). Full notices and licenses are packaged in
`assets/licenses/native_palette.txt`. The native SQLite/TTML data jobs use
rusqlite 0.40.2 and roxmltree 0.21.1 under their MIT licenses, packaged in
`assets/licenses/native_data_jobs.txt`.
+1
View File
@@ -12,6 +12,7 @@ pub mod lyrics;
pub mod matching;
pub mod media;
pub mod metadata;
pub mod native_palette;
pub mod progress;
pub mod resolver;
pub mod tags;
@@ -0,0 +1,521 @@
// Copyright 2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Exact Celebi/Wu/Wsmeans port from material_color_utilities 0.13.0.
//! Pixel order, alpha behavior, numeric order and the pinned Dart VM RNG are
//! preserved. Flutter retains Score and dynamic ColorScheme semantics.
use std::collections::HashMap;
const MAX_PIXELS: usize = 112 * 112;
const COLORS: usize = 128;
const SIDE: usize = 33;
const SIZE: usize = SIDE * SIDE * SIDE;
/// Input is the same premultiplied RGBA readback supplied to Flutter Celebi.
/// Output is ordered ABGR/population pairs, exactly like colorToCount.
pub fn quantize_rgba(
bytes: &[u8],
check: &dyn Fn() -> Result<(), String>,
) -> Result<Vec<(u32, usize)>, String> {
check()?;
if bytes.is_empty() || !bytes.len().is_multiple_of(4) || bytes.len() / 4 > MAX_PIXELS {
return Err("invalid palette pixel buffer".into());
}
let mut lookup = HashMap::new();
let mut colors = Vec::new();
let mut counts = Vec::new();
for pixel in bytes.as_chunks::<4>().0 {
let color = u32::from_le_bytes([pixel[0], pixel[1], pixel[2], pixel[3]]);
let index = *lookup.entry(color).or_insert_with(|| {
colors.push(color);
counts.push(0_usize);
colors.len() - 1
});
counts[index] += 1;
}
let starts = Wu::new(&colors, &counts).quantize(check)?;
wsmeans(&colors, &counts, starts, check)
}
#[derive(Clone, Copy, Default)]
struct Cube {
low: [usize; 3],
high: [usize; 3],
volume: usize,
}
fn index(r: usize, g: usize, b: usize) -> usize {
r * SIDE * SIDE + g * SIDE + b
}
struct Wu {
weights: Vec<i64>,
moments: [Vec<i64>; 3],
squares: Vec<f64>,
}
impl Wu {
fn new(colors: &[u32], counts: &[usize]) -> Self {
let mut result = Self {
weights: vec![0; SIZE],
moments: std::array::from_fn(|_| vec![0; SIZE]),
squares: vec![0.0; SIZE],
};
for (&color, &count) in colors.iter().zip(counts) {
if color >> 24 < 255 {
continue;
}
let rgb = [
((color >> 16) & 255) as i64,
((color >> 8) & 255) as i64,
(color & 255) as i64,
];
let location = index(
(rgb[0] as usize >> 3) + 1,
(rgb[1] as usize >> 3) + 1,
(rgb[2] as usize >> 3) + 1,
);
result.weights[location] += count as i64;
for (channel, value) in rgb.iter().enumerate() {
result.moments[channel][location] += value * count as i64;
}
result.squares[location] +=
(count as i64 * (rgb[0] * rgb[0] + rgb[1] * rgb[1] + rgb[2] * rgb[2])) as f64;
}
result
}
fn prefix(&mut self, check: &dyn Fn() -> Result<(), String>) -> Result<(), String> {
for r in 1..SIDE {
check()?;
let mut areas = [[0_i64; SIDE]; 4];
let mut area_square = [0.0; SIDE];
for g in 1..SIDE {
let mut lines = [0_i64; 4];
let mut line_square = 0.0;
for b in 1..SIDE {
let location = index(r, g, b);
let previous = index(r - 1, g, b);
lines[0] += self.weights[location];
for channel in 0..3 {
lines[channel + 1] += self.moments[channel][location];
}
line_square += self.squares[location];
for channel in 0..4 {
areas[channel][b] += lines[channel];
}
area_square[b] += line_square;
self.weights[location] = self.weights[previous] + areas[0][b];
for channel in 0..3 {
self.moments[channel][location] =
self.moments[channel][previous] + areas[channel + 1][b];
}
self.squares[location] = self.squares[previous] + area_square[b];
}
}
}
Ok(())
}
fn quantize(mut self, check: &dyn Fn() -> Result<(), String>) -> Result<Vec<u32>, String> {
self.prefix(check)?;
let mut cubes = vec![Cube::default(); COLORS];
cubes[0].high = [32; 3];
let mut variances = [0.0; COLORS];
let (mut next, mut count, mut i) = (0, COLORS, 1);
while i < COLORS {
check()?;
if let Some((one, two)) = self.cut(cubes[next]) {
cubes[next] = one;
cubes[i] = two;
variances[next] = if one.volume > 1 {
self.variance(one)
} else {
0.0
};
variances[i] = if two.volume > 1 {
self.variance(two)
} else {
0.0
};
} else {
variances[next] = 0.0;
i -= 1;
}
next = 0;
let mut maximum = variances[0];
for (candidate, value) in variances.iter().enumerate().take(i + 1).skip(1) {
if *value > maximum {
maximum = *value;
next = candidate;
}
}
if maximum <= 0.0 {
count = i + 1;
break;
}
i += 1;
}
let mut result = Vec::new();
for cube in cubes.into_iter().take(count) {
let weight = volume(cube, &self.weights);
if weight > 0 {
let rgb = self
.moments
.each_ref()
.map(|values| (volume(cube, values) as f64 / weight as f64).round() as u32);
let color = 0xff000000 | rgb[0] << 16 | rgb[1] << 8 | rgb[2];
// Dart's Map.fromEntries removes duplicate keys, in first order.
if !result.contains(&color) {
result.push(color);
}
}
}
Ok(result)
}
fn variance(&self, cube: Cube) -> f64 {
let rgb = self.moments.each_ref().map(|values| volume(cube, values));
volume_float(cube, &self.squares)
- (rgb[0] * rgb[0] + rgb[1] * rgb[1] + rgb[2] * rgb[2]) as f64
/ volume(cube, &self.weights) as f64
}
fn cut(&self, cube: Cube) -> Option<(Cube, Cube)> {
let mut best = [(0.0, None); 3];
let whole = [
volume(cube, &self.moments[0]),
volume(cube, &self.moments[1]),
volume(cube, &self.moments[2]),
volume(cube, &self.weights),
];
for (direction, best_cut) in best.iter_mut().enumerate() {
for position in cube.low[direction] + 1..cube.high[direction] {
let mut half = cube;
half.high[direction] = position;
let first = [
volume(half, &self.moments[0]),
volume(half, &self.moments[1]),
volume(half, &self.moments[2]),
volume(half, &self.weights),
];
if first[3] == 0 || whole[3] - first[3] == 0 {
continue;
}
let second = std::array::from_fn::<_, 4, _>(|i| whole[i] - first[i]);
let score = (first[0] * first[0] + first[1] * first[1] + first[2] * first[2])
as f64
/ first[3] as f64
+ (second[0] * second[0] + second[1] * second[1] + second[2] * second[2])
as f64
/ second[3] as f64;
if score > best_cut.0 {
*best_cut = (score, Some(position));
}
}
}
let direction = if best[0].0 >= best[1].0 && best[0].0 >= best[2].0 {
0
} else if best[1].0 >= best[0].0 && best[1].0 >= best[2].0 {
1
} else {
2
};
let position = best[direction].1?;
let (mut one, mut two) = (cube, cube);
one.high[direction] = position;
two.low[direction] = position;
one.volume =
(one.high[0] - one.low[0]) * (one.high[1] - one.low[1]) * (one.high[2] - one.low[2]);
two.volume =
(two.high[0] - two.low[0]) * (two.high[1] - two.low[1]) * (two.high[2] - two.low[2]);
Some((one, two))
}
}
fn volume(c: Cube, v: &[i64]) -> i64 {
v[index(c.high[0], c.high[1], c.high[2])]
- v[index(c.high[0], c.high[1], c.low[2])]
- v[index(c.high[0], c.low[1], c.high[2])]
+ v[index(c.high[0], c.low[1], c.low[2])]
- v[index(c.low[0], c.high[1], c.high[2])]
+ v[index(c.low[0], c.high[1], c.low[2])]
+ v[index(c.low[0], c.low[1], c.high[2])]
- v[index(c.low[0], c.low[1], c.low[2])]
}
fn volume_float(c: Cube, v: &[f64]) -> f64 {
v[index(c.high[0], c.high[1], c.high[2])]
- v[index(c.high[0], c.high[1], c.low[2])]
- v[index(c.high[0], c.low[1], c.high[2])]
+ v[index(c.high[0], c.low[1], c.low[2])]
- v[index(c.low[0], c.high[1], c.high[2])]
+ v[index(c.low[0], c.high[1], c.low[2])]
+ v[index(c.low[0], c.low[1], c.high[2])]
- v[index(c.low[0], c.low[1], c.low[2])]
}
fn lab(color: u32) -> [f64; 3] {
let linear = |value: u32| {
let n = value as f64 / 255.0;
if n <= 0.040449936 {
n / 12.92 * 100.0
} else {
((n + 0.055) / 1.055).powf(2.4) * 100.0
}
};
let (r, g, b) = (
linear(color >> 16 & 255),
linear(color >> 8 & 255),
linear(color & 255),
);
let f = |t: f64| {
if t > 216.0 / 24389.0 {
t.powf(1.0 / 3.0)
} else {
((24389.0 / 27.0) * t + 16.0) / 116.0
}
};
let x = f((0.41233895 * r + 0.35762064 * g + 0.18051042 * b) / 95.047);
let y = f((0.2126 * r + 0.7152 * g + 0.0722 * b) / 100.0);
let z = f((0.01932141 * r + 0.11916382 * g + 0.95034478 * b) / 108.883);
[116.0 * y - 16.0, 500.0 * (x - y), 200.0 * (y - z)]
}
fn color(point: [f64; 3]) -> u32 {
let fy = (point[0] + 16.0) / 116.0;
let inverse = |ft: f64| {
let cube = ft * ft * ft;
if cube > 216.0 / 24389.0 {
cube
} else {
(116.0 * ft - 16.0) / (24389.0 / 27.0)
}
};
let x = inverse(point[1] / 500.0 + fy) * 95.047;
let y = inverse(fy) * 100.0;
let z = inverse(fy - point[2] / 200.0) * 108.883;
let channel = |linear: f64| {
let n = linear / 100.0;
let v = if n <= 0.0031308 {
n * 12.92
} else {
1.055 * n.powf(1.0 / 2.4) - 0.055
};
(v * 255.0).round().clamp(0.0, 255.0) as u32
};
let r = channel(3.2413774792388685 * x + -1.5376652402851851 * y + -0.49885366846268053 * z);
let g = channel(-0.9691452513005321 * x + 1.8758853451067872 * y + 0.04156585616912061 * z);
let b = channel(0.05562093689691305 * x + -0.20395524564742123 * y + 1.0571799111220335 * z);
0xff000000 | r << 16 | g << 8 | b
}
fn distance(one: [f64; 3], two: [f64; 3]) -> f64 {
let l = one[0] - two[0];
let a = one[1] - two[1];
let b = one[2] - two[2];
l * l + a * a + b * b
}
fn wsmeans(
colors: &[u32],
counts: &[usize],
starting: Vec<u32>,
check: &dyn Fn() -> Result<(), String>,
) -> Result<Vec<(u32, usize)>, String> {
let points: Vec<_> = colors.iter().map(|value| lab(*value)).collect();
let cluster_count = COLORS.min(points.len());
let mut clusters: Vec<_> = starting.into_iter().map(lab).collect();
if clusters.len() < cluster_count {
let mut random = DartRandom::new(0x42688);
let mut chosen = Vec::new();
while chosen.len() < cluster_count - clusters.len() {
let candidate = random.next_int(points.len());
if !chosen.contains(&candidate) {
chosen.push(candidate);
}
}
clusters.extend(chosen.into_iter().map(|i| points[i]));
}
let mut indices: Vec<_> = (0..points.len()).map(|i| i % cluster_count).collect();
let mut distances = vec![vec![0.0_f64; cluster_count]; cluster_count];
let mut sums = vec![0_usize; cluster_count];
for iteration in 0..5 {
check()?;
for i in 0..cluster_count {
for j in i + 1..cluster_count {
let value = distance(clusters[i], clusters[j]);
distances[j][i] = value;
distances[i][j] = value;
}
// Match pinned Dart's in-place row sorting, including subsequent
// updates to this already-sorted matrix. Its index matrix is unused.
distances[i].sort_by(f64::total_cmp);
}
let mut moved = 0;
for (i, point) in points.iter().enumerate() {
if i.is_multiple_of(256) {
check()?;
}
let previous = indices[i];
let previous_distance = distance(*point, clusters[previous]);
let mut minimum = previous_distance;
let mut new = None;
for j in 0..cluster_count {
if distances[previous][j] >= 4.0 * previous_distance {
continue;
}
let value = distance(*point, clusters[j]);
if value < minimum {
minimum = value;
new = Some(j);
}
}
if let Some(new) = new {
moved += 1;
indices[i] = new;
}
}
if moved == 0 && iteration > 0 {
break;
}
let mut component_sums = vec![[0.0; 3]; cluster_count];
sums.fill(0);
for (i, point) in points.iter().enumerate() {
let cluster = indices[i];
sums[cluster] += counts[i];
for channel in 0..3 {
component_sums[cluster][channel] += point[channel] * counts[i] as f64;
}
}
for i in 0..cluster_count {
clusters[i] = if sums[i] == 0 {
[0.0; 3]
} else {
component_sums[i].map(|value| value / sums[i] as f64)
};
}
}
let mut result = Vec::new();
for i in 0..cluster_count {
if sums[i] == 0 {
continue;
}
let rgb = color(clusters[i]);
if !result.iter().any(|(key, _)| *key == rgb) {
result.push((rgb, sums[i]));
}
}
check()?;
Ok(result)
}
// Multiply-with-carry and Thomas Wang seed mixing mirror the pinned Dart VM
// Random implementation (Dart SDK, Copyright the Dart project authors, BSD).
struct DartRandom(u64);
impl DartRandom {
fn new(mut n: u64) -> Self {
n = (!n).wrapping_add(n << 21);
n ^= n >> 24;
n = n.wrapping_mul(265);
n ^= n >> 14;
n = n.wrapping_mul(21);
n ^= n >> 28;
n = n.wrapping_add(n << 31);
if n == 0 {
n = 0x5a17;
}
let mut value = Self(n);
for _ in 0..4 {
value.next();
}
value
}
fn next(&mut self) {
self.0 = 0xffffda61 * (self.0 & 0xffffffff) + (self.0 >> 32);
}
fn next_int(&mut self, maximum: usize) -> usize {
loop {
self.next();
let random = self.0 & 0xffffffff;
if maximum.is_power_of_two() {
return random as usize & (maximum - 1);
}
let result = random % maximum as u64;
if random - result + maximum as u64 <= 1_u64 << 32 {
return result as usize;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn solid_pixels_and_invalid_or_cancelled_requests() {
assert_eq!(
quantize_rgba(&[51, 102, 153, 255].repeat(100), &|| Ok(())).unwrap(),
vec![(0xff996633, 100)]
);
assert!(quantize_rgba(&[0; 3], &|| Ok(())).is_err());
assert_eq!(
quantize_rgba(&[0; 4], &|| Err("cancelled".into())).unwrap_err(),
"cancelled"
);
}
#[test]
fn ordered_populations_match_pinned_material_dart_vectors() {
let fixture: serde_json::Value =
serde_json::from_str(include_str!("native_palette/fixtures.json")).unwrap();
for f in fixture["fixtures"].as_array().unwrap() {
let kind = f["kind"].as_str().unwrap();
let mut state = f["seed"].as_u64().unwrap() as u32;
let count = f["count"].as_u64().unwrap() as usize;
let mut bytes = Vec::new();
for i in 0..count {
state = state.wrapping_mul(1664525).wrapping_add(1013904223);
let mut rgb = state & 0xffffff;
let mut alpha = 255;
if kind == "transparent" {
alpha = 0;
}
if kind == "mixed_alpha" {
alpha = state >> 24 & 255;
}
if kind == "single_bin" {
rgb = 0x606060 | (rgb & 0x070707);
}
if kind == "gradient" {
rgb = (((i % 112) as u32 * 255 / 111) << 16)
| (((i / 112) as u32 * 255 / 111) << 8)
| 90;
}
if kind == "ties" {
rgb = [0xff0000, 0x00ff00, 0x0000ff, 0x444444][i % 4];
}
bytes.extend_from_slice(&(alpha << 24 | rgb).to_le_bytes());
}
let actual = quantize_rgba(&bytes, &|| Ok(())).unwrap();
assert_eq!(
serde_json::to_value(actual).unwrap(),
f["colors"],
"{kind} seed {}",
f["seed"]
);
}
let mut random = DartRandom::new(0x42688);
let actual: Vec<_> = (0..20).map(|_| random.next_int(1024)).collect();
assert_eq!(serde_json::to_value(actual).unwrap(), fixture["rng1024"]);
}
}
@@ -0,0 +1,10 @@
`fixtures.json` was generated by the pinned Dart material_color_utilities
0.13.0 `QuantizerCelebi.quantize(pixels, 128)` implementation. It preserves
ordered color/population pairs and final Flutter Score seeds, not approximate
RGB tolerances. Each input is generated from its kind/count/LCG seed, avoiding
large raw artwork fixtures. Cases cover opaque noise, transparent pixels,
mixed alpha, colors sharing one Wu histogram bin (Dart seeded RNG fallback),
112×112 gradients and repeated equal-population colors.
The Rust port retains the upstream Apache-2.0 attribution. The seeded MWC
helper matches the Dart SDK VM's Random implementation (BSD-3-Clause).
@@ -0,0 +1 @@
{"fixtures":[{"kind":"noise","seed":1,"count":1024,"colors":[[4280952889,14],[4280526892,14],[4283470502,19],[4281931952,16],[4288582700,13],[4287701273,9],[4288132492,17],[4288948401,20],[4288618321,12],[4288463136,9],[4293469885,10],[4281764816,14],[4282443816,16],[4293110195,8],[4281233166,7],[4281812628,14],[4288664929,14],[4287849570,16],[4289162928,20],[4281919890,15],[4284716068,10],[4292485660,10],[4284290627,12],[4293675670,9],[4288802462,10],[4281652825,8],[4283428303,9],[4281290720,8],[4292711457,18],[4292660899,14],[4281033049,6],[4280226027,6],[4291488799,11],[4293578586,13],[4290714188,7],[4282494134,11],[4287241437,8],[4292701712,11],[4280911721,14],[4280294011,12],[4291515971,7],[4288386529,8],[4284539031,6],[4291452902,10],[4286529522,5],[4283424984,7],[4288501487,5],[4285144469,5],[4293405146,10],[4283016024,12],[4284868415,5],[4283556631,7],[4293059036,6],[4287271758,12],[4289063113,11],[4284487024,5],[4285043425,4],[4282735995,6],[4284038561,10],[4293299171,8],[4284175137,3],[4292908389,10],[4286661919,9],[4283769054,9],[4293521199,8],[4288539736,8],[4287637621,11],[4289024101,10],[4280785470,7],[4288306383,3],[4285966240,10],[4280959508,3],[4293350869,6],[4290063086,11],[4292242565,7],[4285033698,13],[4287750696,11],[4280202670,4],[4287738834,9],[4284472041,3],[4290489787,6],[4280165284,5],[4281854037,9],[4293867795,12],[4279710565,7],[4281631980,5],[4293733216,6],[4288554393,7],[4289432892,2],[4289519853,4],[4282095851,8],[4285164953,4],[4292683681,7],[4286294881,5],[4291678755,8],[4285130683,6],[4279815578,6],[4293144818,8],[4280965690,5],[4292240945,5],[4285461628,11],[4280073572,4],[4285816427,2],[4283705081,6],[4284790320,7],[4290690898,3],[4291093938,3],[4285986316,6],[4288247819,2],[4283312484,6],[4292306337,4],[4280865004,8],[4284820017,3],[4293833188,6],[4289868611,1],[4280924957,5],[4281866812,2],[4294635773,1],[4289491834,2],[4291483478,2],[4294421700,4],[4288704817,4],[4285736895,4],[4294595433,3],[4288576210,6],[4280405157,2],[4284708401,4]],"seed_argb":4280870976},{"kind":"noise","seed":7,"count":1024,"colors":[[4279113764,7],[4287700508,11],[4289574188,15],[4281276815,11],[4286980753,4],[4286030490,8],[4281639722,11],[4280389261,13],[4288174371,12],[4290077592,14],[4290113063,10],[4292191670,13],[4281168792,9],[4280060012,10],[4280642087,12],[4281382353,20],[4292299030,8],[4292751426,13],[4292990498,9],[4280312155,13],[4288029924,8],[4281983556,10],[4292064235,12],[4281345483,9],[4287446224,6],[4289057439,16],[4288453207,10],[4281451139,12],[4282734751,7],[4282291434,5],[4284194842,14],[4284420653,8],[4286668924,7],[4287961699,13],[4292237238,12],[4283125007,6],[4291175586,13],[4283948907,14],[4293170716,10],[4288663764,10],[4292272209,6],[4284623756,7],[4283001049,12],[4281134798,9],[4291089138,7],[4283550123,7],[4288341106,8],[4284651945,7],[4292287082,11],[4291479982,6],[4293665258,5],[4293085029,6],[4283442906,8],[4282555978,4],[4286944725,9],[4291123418,10],[4281078610,9],[4283190385,10],[4284309225,7],[4285000488,8],[4283293404,7],[4289499770,7],[4280861215,15],[4288180018,12],[4284950388,5],[4283648311,11],[4280677022,6],[4293336735,6],[4282751322,8],[4289022298,10],[4291110176,5],[4287551556,10],[4279742957,8],[4293096641,7],[4288944451,6],[4292113713,3],[4282302385,8],[4293762790,6],[4284202257,6],[4289667803,12],[4280349302,11],[4286538662,8],[4294106709,7],[4281737710,14],[4282585134,7],[4293582311,5],[4293564060,9],[4289326049,7],[4292188529,6],[4281135128,5],[4281606836,7],[4288326206,5],[4281488920,6],[4286047310,4],[4290074392,7],[4293255839,7],[4283854691,5],[4279660717,5],[4293456935,5],[4292702310,6],[4289629655,6],[4284985319,7],[4284625841,7],[4289279131,5],[4288145050,8],[4289255259,4],[4284969939,9],[4293678313,2],[4284169455,10],[4290030496,5],[4293598490,8],[4293598300,3],[4287917791,9],[4289893189,5],[4292520485,4],[4281823469,3],[4285234210,5],[4289489490,3],[4292496183,5],[4279810897,2],[4290112336,6],[4286216613,5],[4291961046,3],[4289932148,8],[4280555636,5],[4281452979,4],[4281328610,5],[4286585391,3]],"seed_argb":4279824428},{"kind":"noise","seed":77,"count":1024,"colors":[[4279902748,9],[4288619544,10],[4287573438,15],[4280820139,12],[4287933222,11],[4288584091,18],[4280322314,7],[4284329648,10],[4291270947,8],[4291984784,12],[4288816498,13],[4288112809,6],[4281004831,11],[4280511523,9],[4284029329,7],[4281457547,13],[4288256606,8],[4290681713,13],[4291272926,12],[4285962443,12],[4293076048,9],[4282047833,9],[4288900393,7],[4291504304,12],[4283395742,5],[4282619778,9],[4281095509,8],[4280232780,9],[4292699569,8],[4282181316,16],[4281997550,11],[4280725056,8],[4286834782,6],[4292204323,10],[4293792025,9],[4289491032,12],[4291809436,11],[4288070808,10],[4283643098,13],[4283187273,13],[4287129545,11],[4291020773,7],[4291290225,13],[4279920798,10],[4284995136,4],[4287483687,5],[4293400823,3],[4291778384,8],[4283470048,11],[4283747610,8],[4286240747,6],[4286314193,5],[4285279080,8],[4281494502,9],[4282692330,11],[4282717972,11],[4284389949,8],[Line truncated
@@ -80,6 +80,10 @@ fn execute(
check,
),
"parse_network_listing" => crate::native_listing::execute(request, Some(bytes)),
"palette" => {
let colors = spotiflac_core::native_palette::quantize_rgba(bytes, check)?;
Ok(json!({"colors": colors}))
}
_ => Err(format!("Unknown native data operation: {operation}")),
}
}
+29
View File
@@ -0,0 +1,29 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:spotiflac_android/theme/cover_palette.dart';
void main() {
test('native ordered counts retain the pinned Material palette seeds', () {
final fixtures =
jsonDecode(
File(
'rust_backend/crates/core/src/native_palette/fixtures.json',
).readAsStringSync(),
)
as Map;
for (final value in fixtures['fixtures'] as List) {
final fixture = value as Map<String, dynamic>;
final colors = [
for (final pair in fixture['colors'] as List)
[for (final value in pair as List) (value as num).toInt()],
];
expect(
paletteSeedFromColorCounts(colors),
fixture['seed_argb'],
reason: '${fixture['kind']} seed ${fixture['seed']}',
);
}
});
}