#![allow(dead_code)] use image::{imageops::FilterType, ImageBuffer, Rgb, RgbImage, Rgba, RgbaImage}; use std::path::{Path, PathBuf}; use std::sync::OnceLock; use yandex_music_rs::api::demo_data; use yandex_music_rs::api::models::{ ArtistSummary as ArtistRef, MetatagLeaf, MetatagTree, Track, TrackFilterChip, UserAccount, VibeStationSummary, }; use yandex_music_rs::app::{AppState, Route}; use yandex_music_rs::config::{AppConfig, Language, PinnedItem, ThemeMode}; use yandex_music_rs::covers::CoverCache; use yandex_music_rs::engine::Vec2; use yandex_music_rs::views::YandexMusicShell; use yandex_music_rs::vulkan::headless::HeadlessVulkanRenderer; pub const NATIVE_W: u32 = 1280; pub const NATIVE_H: u32 = 800; pub const REF_W: u32 = 1024; pub const REF_H: u32 = 640; #[derive(Debug, Clone, Copy)] pub struct Region { pub x: u32, pub y: u32, pub w: u32, pub h: u32, } impl Region { pub const fn new(x: u32, y: u32, w: u32, h: u32) -> Self { Self { x, y, w, h } } pub const fn full() -> Self { Self { x: 0, y: 0, w: REF_W, h: REF_H, } } pub fn x2(&self) -> u32 { (self.x + self.w).min(REF_W) } pub fn y2(&self) -> u32 { (self.y + self.h).min(REF_H) } } #[derive(Debug, Clone, Copy)] pub struct BBox { pub x1: u32, pub y1: u32, pub x2: u32, pub y2: u32, pub pixel_count: usize, } impl BBox { pub fn width(&self) -> u32 { self.x2.saturating_sub(self.x1) + 1 } pub fn height(&self) -> u32 { self.y2.saturating_sub(self.y1) + 1 } pub fn cx(&self) -> f32 { (self.x1 + self.x2) as f32 * 0.5 } pub fn cy(&self) -> f32 { (self.y1 + self.y2) as f32 * 0.5 } } #[derive(Debug, Clone, Copy)] pub struct ShellGeometry { pub card_left: u32, pub card_right: u32, pub card_top: u32, pub card_bottom: u32, pub player_bar_top: Option, pub player_bar_bottom: Option, pub gap_y: Option, pub right_margin: u32, pub bottom_margin: Option, } #[derive(Debug, Clone)] pub struct PageCapture { pub name: &'static str, pub reference: RgbImage, pub actual: RgbImage, pub actual_native: RgbImage, } pub struct VisualSuiteData { pub gpu_name: String, pub favorites: PageCapture, pub for_you: PageCapture, pub search: PageCapture, pub my_vibe: PageCapture, } static SUITE_DATA: OnceLock = OnceLock::new(); pub fn fixture_dir() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")) .join("tests") .join("fixtures") .join("reference") } pub fn output_dir() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")) .join("target") .join("visual_tests") } fn load_reference(name: &str) -> RgbImage { let path = fixture_dir().join(format!("{}.jpg", name)); let img = image::open(&path) .unwrap_or_else(|e| panic!("Failed to load reference image {}: {}", path.display(), e)) .to_rgb8(); assert_eq!( img.dimensions(), (REF_W, REF_H), "Reference image {} must be {}x{}", name, REF_W, REF_H ); img } fn crop_rgba(img: &RgbImage, x: u32, y: u32, w: u32, h: u32) -> (Vec, usize, usize) { let cw = w.min(img.width().saturating_sub(x)); let ch = h.min(img.height().saturating_sub(y)); let mut out = Vec::with_capacity((cw * ch * 4) as usize); for row in y..(y + ch) { for col in x..(x + cw) { let p = img.get_pixel(col, row).0; out.extend_from_slice(&[p[0], p[1], p[2], 255]); } } (out, cw as usize, ch as usize) } /// Crop a top-visible rectangular slice and pad it down to a `w x w` square /// so square `media_card` widgets display the top slice 1:1 with zero vertical stretching. fn crop_rgba_pad_square(img: &RgbImage, x: u32, y: u32, w: u32, h: u32) -> (Vec, usize, usize) { let cw = w.min(img.width().saturating_sub(x)); let ch = h.min(img.height().saturating_sub(y)); let sq = cw.max(ch); let mut out = Vec::with_capacity((sq * sq * 4) as usize); for row in 0..sq { let src_y = y + row.min(ch.saturating_sub(1)); for col in 0..sq { let src_x = x + col.min(cw.saturating_sub(1)); let p = if row < ch { img.get_pixel(src_x, src_y).0 } else { [18, 18, 18] }; out.extend_from_slice(&[p[0], p[1], p[2], 255]); } } (out, sq as usize, sq as usize) } fn make_artist(id: &str, name: &str) -> ArtistRef { ArtistRef { id: id.into(), name: name.into(), cover_uri: None, genres: Vec::new(), } } fn make_track( id: &str, title: &str, version: Option<&str>, artists: Vec, duration_ms: u64, cover_uri: Option<&str>, is_explicit: bool, ) -> Track { Track { id: id.into(), title: title.into(), version: version.map(String::from), artists, album_id: Some(format!("alb_{}", id)), album_title: Some(title.into()), duration_ms, cover_uri: cover_uri.map(String::from), is_explicit, has_lossless: true, has_lyrics: true, chart_position: None, chart_progress: None, preview_url: None, r128_i: None, r128_tp: None, derived_average_hex: None, derived_accent_hex: None, } } /// Build deterministic offline test shell whose data matches the 4 official English screenshots /// (same user "Marwy", same current track "MONTAGEM TENTA", same liked tracks, same pinned playlists, /// same artist promo cards, same mixes & wheel items, and real artwork cropped from the reference screenshots). fn build_reference_matched_shell( rt_handle: tokio::runtime::Handle, gpu_name: String, ref_fav: &RgbImage, ref_fy: &RgbImage, ref_search: &RgbImage, ref_vibe: &RgbImage, ) -> YandexMusicShell { let mut config = AppConfig::default(); config.theme = ThemeMode::Dark; config.language = Language::En; config.sidebar_collapsed = false; config.show_perf_hud = false; config.muted = false; config.volume = 0.78; config.max_cover_cache = 256; config.pinned_items = vec![ PinnedItem { id: "likes".into(), kind: "likes".into(), title: "My Favorites".into(), subtitle: "Playlist".into(), cover_uri: None, owner_uid: None, }, PinnedItem { id: "likes_2".into(), kind: "likes".into(), title: "My Favorites".into(), subtitle: "Playlist".into(), cover_uri: None, owner_uid: None, }, PinnedItem { id: "my_2025".into(), kind: "playlist".into(), title: "My 2025".into(), subtitle: "Playlist".into(), cover_uri: Some("test.local/pin_2025/%%".into()), owner_uid: Some("marwy".into()), }, PinnedItem { id: "my_2024".into(), kind: "playlist".into(), title: "My 2024".into(), subtitle: "Playlist".into(), cover_uri: Some("test.local/pin_2024/%%".into()), owner_uid: Some("marwy".into()), }, PinnedItem { id: "custom_5".into(), kind: "playlist".into(), title: "пиздец".into(), subtitle: "Playlist".into(), cover_uri: Some("test.local/pin_5/%%".into()), owner_uid: Some("marwy".into()), }, ]; let liked_tracks = vec![ make_track( "fav_1", "Can't Hold Us X Bad Piggies", None, vec![make_artist("a_ss", "SuperSolar")], 116_000, Some("test.local/fav_1/%%"), false, ), make_track( "fav_2", "BANG A RANG", None, vec![make_artist("a_gs", "GSTRNM")], 100_000, Some("test.local/fav_2/%%"), false, ), make_track( "fav_3", "#хлопай", None, vec![ make_artist("a_el", "ЭЛЕВЕН ЭЙТ"), make_artist("a_fm", "формула"), ], 98_000, Some("test.local/fav_3/%%"), true, ), make_track( "fav_4", "BOSS BITCH TEKK", None, vec![make_artist("a_wh", "wharoxmane")], 107_000, Some("test.local/fav_4/%%"), false, ), ]; let mut current_track = make_track( "curr_1", "MONTAGEM TENTA", Some("Hardstyle Remix"), vec![ make_artist("a_me", "merunes"), make_artist("a_ly", "LYKYOR"), ], 132_000, Some("test.local/curr_1/%%"), false, ); // Match reference favorites.jpg where Lyrics icon is disabled (#4D4D4D) current_track.has_lyrics = false; let mut landing = demo_data::demo_landing(); landing.vibe_tracks = vec![ make_track( "fy_1", "Vibe Pick 1", None, vec![make_artist("fy_a1", "SEREBRO")], 140_000, Some("test.local/fy_av1/%%"), false, ), make_track( "fy_2", "Vibe Pick 2", None, vec![make_artist("fy_a2", "SLAVA MARLOW")], 150_000, Some("test.local/fy_av2/%%"), false, ), ]; let make_artist_with_cover = |id: &str, name: &str, cov: &str| ArtistRef { id: id.into(), name: name.into(), cover_uri: Some(cov.into()), genres: Vec::new(), }; landing.chart_tracks = vec![ make_track( "promo_1", "ПОТОМ", None, vec![make_artist_with_cover("p1", "GATASKI", "test.local/promo_1/%%")], 145_000, Some("test.local/promo_1_cov/%%"), true, ), make_track( "promo_2", "Он – дракон", None, vec![make_artist_with_cover("p2", "Вайолет", "test.local/promo_2/%%")], 168_000, Some("test.local/promo_2_cov/%%"), false, ), make_track( "promo_3", "SKILL", None, vec![make_artist_with_cover("p3", "OG BLESS", "test.local/promo_3/%%")], 152_000, Some("test.local/promo_3_cov/%%"), true, ), ]; for (idx, pl) in landing.popular_playlists.iter_mut().take(5).enumerate() { pl.cover_uri = Some(format!("test.local/disc_{}/%%", idx + 1)); } let account = Some(UserAccount { uid: 42, login: "marwy".into(), display_name: "Marwy".into(), has_plus: true, avatar_uri: Some("test.local/avatar_marwy/%%".into()), }); let mut app = AppState::new_visual_test( rt_handle.clone(), gpu_name, Route::LikedTracks, config, landing, account, liked_tracks, vec![current_track], 63_360, // ~48% playback progress matching original screenshots! 132_000, 108.0, // Fixed My Vibe shader timestamp matching my_vibe.jpg orb phase (orb SSIM 0.7641!) ); app.is_vibe_active = true; // Matches reference favorites.jpg where Shuffle is disabled in My Vibe context app.favorite_filters = vec![ TrackFilterChip { id: "all".into(), name: "All".into(), track_ids: Default::default() }, TrackFilterChip { id: "cheerful".into(), name: "Cheerful".into(), track_ids: Default::default() }, TrackFilterChip { id: "electronic".into(), name: "Electronic".into(), track_ids: Default::default() }, TrackFilterChip { id: "happy".into(), name: "Happy".into(), track_ids: Default::default() }, TrackFilterChip { id: "dance".into(), name: "Dance".into(), track_ids: Default::default() }, TrackFilterChip { id: "rap".into(), name: "Rap and Hip-Hop".into(), track_ids: Default::default() }, TrackFilterChip { id: "pop".into(), name: "Pop".into(), track_ids: Default::default() }, TrackFilterChip { id: "calm".into(), name: "Calm".into(), track_ids: Default::default() }, ]; // Populate recent history mini cover & artists matching for_you.jpg ("5sta Family, Fyex, friganya") app.play_history = vec![ make_track( "hist_1", "Track 1", None, vec![make_artist("h_1", "5sta Family")], 132_000, Some("test.local/fy_hist_mini/%%"), false, ), make_track( "hist_2", "Track 2", None, vec![make_artist("h_2", "Fyex")], 132_000, None, false, ), make_track( "hist_3", "Track 3", None, vec![make_artist("h_3", "friganya")], 132_000, None, false, ), ]; // Populate Search Mixes cards with reference covers app.metatags = vec![MetatagTree { navigation_id: "mixes".into(), title: "Mixes".into(), leaves: vec![ MetatagLeaf { id: "autumn".into(), title: "Autumn".into(), cover_uri: Some("test.local/mix_autumn/%%".into()), color_hex: Some("#6E523C".into()), }, MetatagLeaf { id: "mood".into(), title: "Mood".into(), cover_uri: Some("test.local/mix_mood/%%".into()), color_hex: Some("#A39028".into()), }, MetatagLeaf { id: "activity".into(), title: "Activity".into(), cover_uri: Some("test.local/mix_activity/%%".into()), color_hex: Some("#5BADD6".into()), }, MetatagLeaf { id: "genres".into(), title: "Genres".into(), cover_uri: Some("test.local/mix_genres/%%".into()), color_hex: Some("#A37528".into()), }, MetatagLeaf { id: "era".into(), title: "Era".into(), cover_uri: Some("test.local/mix_era/%%".into()), color_hex: Some("#937038".into()), }, ], }]; // Populate My Vibe wheel stations with cropped reference station artwork app.wheel_stations = vec![ VibeStationSummary { id: "wb_0".into(), title: "For party animals".into(), subtitle: None, seeds: vec!["mood:energetic".into()], cover_uri: Some("test.local/vibe_bub_0/%%".into()), color_hex: None, is_artist: false, has_link_arrow: false, item_type: "WAVE".into(), promo_url: None, is_reshuffle: false, }, VibeStationSummary { id: "wb_1".into(), title: "Only in Portuguese".into(), subtitle: None, seeds: vec!["activity:workout".into()], cover_uri: Some("test.local/vibe_bub_1/%%".into()), color_hex: None, is_artist: false, has_link_arrow: false, item_type: "WAVE".into(), promo_url: None, is_reshuffle: false, }, VibeStationSummary { id: "wb_2".into(), title: "формула".into(), subtitle: Some("Artist".into()), seeds: vec!["artist:a_fm".into()], cover_uri: Some("test.local/vibe_bub_2/%%".into()), color_hex: None, is_artist: true, has_link_arrow: false, item_type: "ARTIST".into(), promo_url: None, is_reshuffle: false, }, VibeStationSummary { id: "wb_3".into(), title: "Latino flavored".into(), subtitle: None, seeds: vec!["user:onyourwave".into()], cover_uri: Some("test.local/vibe_bub_3/%%".into()), color_hex: None, is_artist: false, has_link_arrow: false, item_type: "WAVE".into(), promo_url: None, is_reshuffle: false, }, VibeStationSummary { id: "wb_4".into(), title: "SuperSolar".into(), subtitle: Some("Artist".into()), seeds: vec!["artist:a_ss".into()], cover_uri: Some("test.local/vibe_bub_4/%%".into()), color_hex: None, is_artist: true, has_link_arrow: false, item_type: "ARTIST".into(), promo_url: None, is_reshuffle: false, }, VibeStationSummary { id: "wb_5".into(), title: "Кого наградили на «Распаковке 2026»".into(), subtitle: None, seeds: vec!["user:onyourwave".into()], cover_uri: Some("test.local/vibe_bub_5/%%".into()), color_hex: None, is_artist: false, has_link_arrow: true, item_type: "PROMO_LINK".into(), promo_url: Some("/collection".into()), is_reshuffle: false, }, VibeStationSummary { id: "wb_6".into(), title: "Jogging without getting tired".into(), subtitle: None, seeds: vec!["mood:calm".into()], cover_uri: Some("test.local/vibe_bub_6/%%".into()), color_hex: None, is_artist: false, has_link_arrow: false, item_type: "WAVE".into(), promo_url: None, is_reshuffle: false, }, ]; let covers = CoverCache::new(256, rt_handle); let mut shell = YandexMusicShell::new_visual_test(app, covers); // Preload exact cover thumbnails cropped from the original reference screenshots // so pixel comparisons isolate pure UI/layout/styling/color fidelity! let crops: &[(&str, &RgbImage, u32, u32, u32, u32)] = &[ // Crop strictly inside the avatar circle (22, 585, 27x27) so we don't bake the reference's outer Plus ring inside our own Plus ring! ("test.local/avatar_marwy/%%", ref_fav, 22, 585, 27, 27), ("test.local/curr_1/%%", ref_fav, 186, 573, 51, 51), ("test.local/fav_1/%%", ref_fav, 198, 378, 34, 34), ("test.local/fav_2/%%", ref_fav, 198, 423, 34, 34), ("test.local/fav_3/%%", ref_fav, 198, 469, 34, 34), ("test.local/fav_4/%%", ref_fav, 198, 514, 34, 34), ("test.local/pin_2025/%%", ref_fav, 19, 436, 32, 32), ("test.local/pin_2024/%%", ref_fav, 19, 482, 32, 32), ("test.local/pin_5/%%", ref_fav, 19, 527, 32, 32), ("test.local/fy_av1/%%", ref_fy, 212, 100, 28, 28), ("test.local/fy_av2/%%", ref_fy, 233, 100, 28, 28), ("test.local/tr_av1/%%", ref_fy, 435, 100, 28, 28), ("test.local/tr_av2/%%", ref_fy, 456, 100, 28, 28), ("test.local/fy_fav_mini/%%", ref_fy, 528, 180, 47, 47), ("test.local/fy_hist_mini/%%", ref_fy, 925, 180, 47, 47), ("test.local/promo_1/%%", ref_fy, 199, 303, 257, 172), ("test.local/promo_2/%%", ref_fy, 468, 303, 257, 172), ("test.local/promo_3/%%", ref_fy, 737, 303, 257, 172), ("test.local/promo_1_cov/%%", ref_fy, 209, 401, 64, 64), ("test.local/promo_2_cov/%%", ref_fy, 478, 401, 64, 64), ("test.local/promo_3_cov/%%", ref_fy, 747, 401, 64, 64), ("test.local/mix_autumn/%%", ref_search, 229, 273, 94, 93), ("test.local/mix_mood/%%", ref_search, 394, 273, 94, 93), ("test.local/mix_activity/%%", ref_search, 559, 273, 94, 93), ("test.local/mix_genres/%%", ref_search, 723, 273, 94, 93), ("test.local/mix_era/%%", ref_search, 889, 273, 94, 93), ("test.local/vibe_bub_0/%%", ref_vibe, 309, 32, 57, 56), ("test.local/vibe_bub_1/%%", ref_vibe, 279, 123, 54, 53), ("test.local/vibe_bub_2/%%", ref_vibe, 253, 206, 66, 65), ("test.local/vibe_bub_3/%%", ref_vibe, 248, 299, 57, 59), ("test.local/vibe_bub_4/%%", ref_vibe, 253, 384, 65, 66), ("test.local/vibe_bub_5/%%", ref_vibe, 280, 476, 56, 62), ("test.local/vibe_bub_6/%%", ref_vibe, 307, 566, 59, 57), ]; for &(uri, img, x, y, w, h) in crops { let (rgba, cw, ch) = crop_rgba(img, x, y, w, h); shell .covers .insert_test_rgba(&mut shell.ui.textures, uri, &rgba, cw, ch); } // Discover playlist covers cropped & square-padded from ref_search let disc_crops: &[(&str, u32, u32, u32, u32)] = &[ ("test.local/disc_1/%%", 198, 484, 157, 72), ("test.local/disc_2/%%", 363, 484, 157, 72), ("test.local/disc_3/%%", 528, 484, 157, 72), ("test.local/disc_4/%%", 693, 484, 157, 72), ("test.local/disc_5/%%", 857, 484, 157, 72), ]; for &(uri, x, y, w, h) in disc_crops { let (rgba, cw, ch) = crop_rgba_pad_square(ref_search, x, y, w, h); shell .covers .insert_test_rgba(&mut shell.ui.textures, uri, &rgba, cw, ch); } shell } fn render_route_capture( vk: &mut HeadlessVulkanRenderer, shell: &mut YandexMusicShell, route: Route, name: &'static str, reference: RgbImage, ) -> PageCapture { shell.app.set_route_for_test(route); let mut last_rgba = Vec::new(); // Run 3 frames so glyph atlas, SVG icon uploads, and layout settle cleanly. for frame in 0..3 { let (out, _cmd) = shell.render_frame( Vec2::new(NATIVE_W as f32, NATIVE_H as f32), 1.0, frame as f64 * 0.016, false, ); let clear_col = shell.palette.clear_color_f32(); let vibe_push = shell.vibe_push_constants(); last_rgba = vk .render_to_rgba( &out.display_list, &out.texture_uploads, 1.0, clear_col, vibe_push, ) .expect("Headless Vulkan render_to_rgba failed"); } let rgba_img: RgbaImage = ImageBuffer::from_raw(NATIVE_W, NATIVE_H, last_rgba) .expect("Failed to construct RGBA image from Vulkan readback"); let native_rgb: RgbImage = ImageBuffer::from_fn(NATIVE_W, NATIVE_H, |x, y| { let p = rgba_img.get_pixel(x, y).0; Rgb([p[0], p[1], p[2]]) }); let scaled_rgb = image::imageops::resize(&native_rgb, REF_W, REF_H, FilterType::Lanczos3); // Save artifacts for immediate visual inspection! let out_dir = output_dir(); let _ = std::fs::create_dir_all(&out_dir); let _ = native_rgb.save(out_dir.join(format!("{}_actual_1280x800.png", name))); let _ = scaled_rgb.save(out_dir.join(format!("{}_actual_1024x640.png", name))); let _ = save_visual_diff_report(name, &reference, &scaled_rgb); PageCapture { name, reference, actual: scaled_rgb, actual_native: native_rgb, } } pub fn capture_all_pages() -> &'static VisualSuiteData { SUITE_DATA.get_or_init(|| { let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .expect("Failed to create tokio test runtime"); let ref_fav = load_reference("favorites"); let ref_fy = load_reference("for_you"); let ref_search = load_reference("search"); let ref_vibe = load_reference("my_vibe"); let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H) .expect("Failed to initialize HeadlessVulkanRenderer (Vulkan GPU required)"); let gpu_name = vk.gpu_name.clone(); let mut shell = build_reference_matched_shell( rt.handle().clone(), gpu_name.clone(), &ref_fav, &ref_fy, &ref_search, &ref_vibe, ); let favorites = render_route_capture( &mut vk, &mut shell, Route::LikedTracks, "favorites", ref_fav, ); let for_you = render_route_capture( &mut vk, &mut shell, Route::ForYou, "for_you", ref_fy, ); let search = render_route_capture( &mut vk, &mut shell, Route::Search, "search", ref_search, ); let my_vibe = render_route_capture( &mut vk, &mut shell, Route::MyVibe, "my_vibe", ref_vibe, ); VisualSuiteData { gpu_name, favorites, for_you, search, my_vibe, } }) } // ============================================================================ // PERCEPTUAL & STRUCTURAL IMAGE METRICS (Pure Rust) // ============================================================================ #[inline] fn luma(rgb: [u8; 3]) -> f64 { 0.2126 * rgb[0] as f64 + 0.7152 * rgb[1] as f64 + 0.0722 * rgb[2] as f64 } /// Windowed SSIM (8x8 non-overlapping blocks with stride 4) on luminance & color channels. /// Returns a value in [-1.0, 1.0] where 1.0 = pixel-identical. pub fn compute_ssim(a: &RgbImage, b: &RgbImage, region: Region) -> f64 { let x1 = region.x; let y1 = region.y; let x2 = region.x2(); let y2 = region.y2(); if x2 <= x1 + 8 || y2 <= y1 + 8 { return 0.0; } const C1: f64 = (0.01 * 255.0) * (0.01 * 255.0); const C2: f64 = (0.03 * 255.0) * (0.03 * 255.0); let mut total_ssim = 0.0; let mut blocks = 0u64; let mut by = y1; while by + 8 <= y2 { let mut bx = x1; while bx + 8 <= x2 { // Compute SSIM across all 3 RGB channels and average let mut block_ssim = 0.0; for ch in 0..3 { let mut sum_a = 0.0; let mut sum_b = 0.0; for dy in 0..8 { for dx in 0..8 { sum_a += a.get_pixel(bx + dx, by + dy).0[ch] as f64; sum_b += b.get_pixel(bx + dx, by + dy).0[ch] as f64; } } let mu_a = sum_a / 64.0; let mu_b = sum_b / 64.0; let mut var_a = 0.0; let mut var_b = 0.0; let mut cov_ab = 0.0; for dy in 0..8 { for dx in 0..8 { let da = a.get_pixel(bx + dx, by + dy).0[ch] as f64 - mu_a; let db = b.get_pixel(bx + dx, by + dy).0[ch] as f64 - mu_b; var_a += da * da; var_b += db * db; cov_ab += da * db; } } var_a /= 63.0; var_b /= 63.0; cov_ab /= 63.0; let num = (2.0 * mu_a * mu_b + C1) * (2.0 * cov_ab + C2); let den = (mu_a * mu_a + mu_b * mu_b + C1) * (var_a + var_b + C2); block_ssim += num / den; } total_ssim += block_ssim / 3.0; blocks += 1; bx += 4; } by += 4; } if blocks == 0 { 0.0 } else { total_ssim / blocks as f64 } } /// Standard Wang-Bovik luminance SSIM (immune to JPEG 4:2:0 blue-channel chroma bleed on pure #FFFF00). pub fn compute_luma_ssim(a: &RgbImage, b: &RgbImage, region: Region) -> f64 { let x1 = region.x; let y1 = region.y; let x2 = region.x2(); let y2 = region.y2(); if x2 <= x1 + 8 || y2 <= y1 + 8 { return 0.0; } const C1: f64 = (0.01 * 255.0) * (0.01 * 255.0); const C2: f64 = (0.03 * 255.0) * (0.03 * 255.0); let mut total_ssim = 0.0; let mut blocks = 0u64; let mut by = y1; while by + 8 <= y2 { let mut bx = x1; while bx + 8 <= x2 { let mut sum_a = 0.0; let mut sum_b = 0.0; for dy in 0..8 { for dx in 0..8 { sum_a += luma(a.get_pixel(bx + dx, by + dy).0); sum_b += luma(b.get_pixel(bx + dx, by + dy).0); } } let mu_a = sum_a / 64.0; let mu_b = sum_b / 64.0; let mut var_a = 0.0; let mut var_b = 0.0; let mut cov_ab = 0.0; for dy in 0..8 { for dx in 0..8 { let da = luma(a.get_pixel(bx + dx, by + dy).0) - mu_a; let db = luma(b.get_pixel(bx + dx, by + dy).0) - mu_b; var_a += da * da; var_b += db * db; cov_ab += da * db; } } var_a /= 63.0; var_b /= 63.0; cov_ab /= 63.0; let num = (2.0 * mu_a * mu_b + C1) * (2.0 * cov_ab + C2); let den = (mu_a * mu_a + mu_b * mu_b + C1) * (var_a + var_b + C2); total_ssim += num / den; blocks += 1; bx += 4; } by += 4; } if blocks == 0 { 0.0 } else { total_ssim / blocks as f64 } } fn srgb_to_lab(rgb: [u8; 3]) -> [f64; 3] { let to_lin = |c: u8| -> f64 { let v = c as f64 / 255.0; if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } }; let r = to_lin(rgb[0]); let g = to_lin(rgb[1]); let b = to_lin(rgb[2]); // D65 reference white let x = (r * 0.4124564 + g * 0.3575761 + b * 0.1804375) / 0.95047; let y = (r * 0.2126729 + g * 0.7151522 + b * 0.0721750) / 1.00000; let z = (r * 0.0193339 + g * 0.1191920 + b * 0.9503041) / 1.08883; let f = |t: f64| -> f64 { if t > 0.008856 { t.cbrt() } else { 7.787 * t + 16.0 / 116.0 } }; let fx = f(x); let fy = f(y); let fz = f(z); [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] } /// Returns `(mean_delta_e, p95_delta_e)` in perceptual CIELAB space over `region`. pub fn compute_lab_delta_e(a: &RgbImage, b: &RgbImage, region: Region) -> (f64, f64) { let x1 = region.x; let y1 = region.y; let x2 = region.x2(); let y2 = region.y2(); let mut vals = Vec::with_capacity(((x2 - x1) * (y2 - y1)) as usize); let mut sum = 0.0; for y in y1..y2 { for x in x1..x2 { let la = srgb_to_lab(a.get_pixel(x, y).0); let lb = srgb_to_lab(b.get_pixel(x, y).0); let de = ((la[0] - lb[0]).powi(2) + (la[1] - lb[1]).powi(2) + (la[2] - lb[2]).powi(2)) .sqrt(); sum += de; vals.push(de); } } if vals.is_empty() { return (0.0, 0.0); } vals.sort_by(|u, v| u.partial_cmp(v).unwrap_or(std::cmp::Ordering::Equal)); let mean = sum / vals.len() as f64; let p95 = vals[(vals.len() * 95 / 100).min(vals.len() - 1)]; (mean, p95) } fn sobel_blurred_map(img: &RgbImage, region: Region) -> Vec { let w = (region.x2() - region.x) as usize; let h = (region.y2() - region.y) as usize; let mut gray = vec![0.0f64; w * h]; for dy in 0..h { for dx in 0..w { gray[dy * w + dx] = luma(img.get_pixel(region.x + dx as u32, region.y + dy as u32).0); } } let mut mag = vec![0.0f64; w * h]; for y in 1..(h.saturating_sub(1)) { for x in 1..(w.saturating_sub(1)) { let tl = gray[(y - 1) * w + (x - 1)]; let tc = gray[(y - 1) * w + x]; let tr = gray[(y - 1) * w + (x + 1)]; let ml = gray[y * w + (x - 1)]; let mr = gray[y * w + (x + 1)]; let bl = gray[(y + 1) * w + (x - 1)]; let bc = gray[(y + 1) * w + x]; let br = gray[(y + 1) * w + (x + 1)]; let gx = -tl + tr - 2.0 * ml + 2.0 * mr - bl + br; let gy = -tl - 2.0 * tc - tr + bl + 2.0 * bc + br; mag[y * w + x] = (gx * gx + gy * gy).sqrt(); } } // 3x3 box blur for 1-2px subpixel layout tolerance let mut blur = vec![0.0f64; w * h]; for y in 1..(h.saturating_sub(1)) { for x in 1..(w.saturating_sub(1)) { let mut s = 0.0; for ky in -1isize..=1 { for kx in -1isize..=1 { s += mag[(y as isize + ky) as usize * w + (x as isize + kx) as usize]; } } blur[y * w + x] = s / 9.0; } } blur } /// Normalized Cross-Correlation of blurred Sobel edge maps. /// Catches misaligned cards, buttons, sidebars, text lines, and missing borders. pub fn compute_edge_ncc(a: &RgbImage, b: &RgbImage, region: Region) -> f64 { let ea = sobel_blurred_map(a, region); let eb = sobel_blurred_map(b, region); if ea.is_empty() { return 0.0; } let n = ea.len() as f64; let ma = ea.iter().sum::() / n; let mb = eb.iter().sum::() / n; let mut num = 0.0; let mut da2 = 0.0; let mut db2 = 0.0; for (&u, &v) in ea.iter().zip(eb.iter()) { let du = u - ma; let dv = v - mb; num += du * dv; da2 += du * du; db2 += dv * dv; } let den = (da2 * db2).sqrt(); if den < 1e-9 { 1.0 } else { num / den } } pub fn median_rgb(img: &RgbImage, region: Region) -> [u8; 3] { let mut rs = Vec::new(); let mut gs = Vec::new(); let mut bs = Vec::new(); for y in region.y..region.y2() { for x in region.x..region.x2() { let p = img.get_pixel(x, y).0; rs.push(p[0]); gs.push(p[1]); bs.push(p[2]); } } if rs.is_empty() { return [0, 0, 0]; } rs.sort_unstable(); gs.sort_unstable(); bs.sort_unstable(); let mid = rs.len() / 2; [rs[mid], gs[mid], bs[mid]] } pub fn mean_rgb(img: &RgbImage, region: Region) -> [f64; 3] { let mut s = [0.0f64; 3]; let mut n = 0u64; for y in region.y..region.y2() { for x in region.x..region.x2() { let p = img.get_pixel(x, y).0; s[0] += p[0] as f64; s[1] += p[1] as f64; s[2] += p[2] as f64; n += 1; } } if n == 0 { return [0.0; 3]; } [s[0] / n as f64, s[1] / n as f64, s[2] / n as f64] } pub fn rgb_dist(a: [u8; 3], b: [u8; 3]) -> f64 { let dr = a[0] as f64 - b[0] as f64; let dg = a[1] as f64 - b[1] as f64; let db = a[2] as f64 - b[2] as f64; (dr * dr + dg * dg + db * db).sqrt() } pub fn find_matching_bbox(img: &RgbImage, region: Region, pred: F) -> Option where F: Fn([u8; 3]) -> bool, { let mut x1 = u32::MAX; let mut y1 = u32::MAX; let mut x2 = 0u32; let mut y2 = 0u32; let mut count = 0usize; for y in region.y..region.y2() { for x in region.x..region.x2() { if pred(img.get_pixel(x, y).0) { x1 = x1.min(x); y1 = y1.min(y); x2 = x2.max(x); y2 = y2.max(y); count += 1; } } } if count == 0 { None } else { Some(BBox { x1, y1, x2, y2, pixel_count: count, }) } } pub fn is_yandex_yellow(rgb: [u8; 3]) -> bool { rgb[0] > 195 && rgb[1] > 185 && rgb[2] < 85 } pub fn is_vibe_gold(rgb: [u8; 3]) -> bool { rgb[0] > 170 && rgb[1] > 130 && rgb[2] < 85 } pub fn is_vibe_magenta(rgb: [u8; 3]) -> bool { rgb[0] > 95 && rgb[2] > 75 && rgb[1] < 85 } /// Measure shell layout boundaries directly from rendered pixels (no trusting code constants!). pub fn measure_shell_geometry(img: &RgbImage) -> ShellGeometry { let col_median_luma = |x: u32, y_start: u32, y_end: u32| -> f64 { let mut v: Vec = (y_start..y_end) .map(|y| luma(img.get_pixel(x, y).0)) .collect(); v.sort_by(|a, b| a.partial_cmp(b).unwrap()); v[v.len() / 2] }; let row_median_luma = |y: u32, x_start: u32, x_end: u32| -> f64 { let mut v: Vec = (x_start..x_end) .map(|x| luma(img.get_pixel(x, y).0)) .collect(); v.sort_by(|a, b| a.partial_cmp(b).unwrap()); v[v.len() / 2] }; // Content card left edge (scan x in 130..250 across y=100..500) let card_left = (130..250) .find(|&x| col_median_luma(x, 100, 500) > 10.0) .unwrap_or(0); // Content card right edge (scan right-to-left skipping 1px OS frame at x=1023) let card_right = (960..1022) .rev() .find(|&x| col_median_luma(x, 100, 500) > 10.0) .unwrap_or(REF_W - 1); // Content card top edge (scan y in 5..60 across x=400..900) let card_top = (5..60) .find(|&y| row_median_luma(y, 400, 900) > 10.0) .unwrap_or(0); // Content card bottom edge: find first dark black gap row below y=480 let card_bottom = (480..REF_H - 2) .find(|&y| row_median_luma(y, 400, 900) < 8.0) .unwrap_or(REF_H - 1); // Player bar top: first bright surface row after the dark gap below card_bottom let player_bar_top = (card_bottom..REF_H - 2) .find(|&y| row_median_luma(y, 400, 900) > 14.0); let player_bar_bottom = player_bar_top.and_then(|pt| { (pt + 10..REF_H - 1).find(|&y| row_median_luma(y, 400, 900) < 8.0) }); let gap_y = player_bar_top.map(|pt| pt.saturating_sub(card_bottom)); let right_margin = (REF_W - 1).saturating_sub(card_right); let bottom_margin = player_bar_bottom.map(|pb| (REF_H - 1).saturating_sub(pb)); ShellGeometry { card_left, card_right, card_top, card_bottom, player_bar_top, player_bar_bottom, gap_y, right_margin, bottom_margin, } } /// Generate a 3-panel visual diff composite image: /// [Left: Original Reference] | [Middle: Rust Actual] | [Right: 4x Amplified Error Heatmap] /// Saved to `target/visual_tests/_diff_report.png`. pub fn save_visual_diff_report(name: &str, reference: &RgbImage, actual: &RgbImage) -> anyhow::Result<()> { let w = reference.width(); let h = reference.height(); let mut canvas: ImageBuffer, Vec> = ImageBuffer::new(w * 3, h); for y in 0..h { for x in 0..w { let r = reference.get_pixel(x, y).0; let a = actual.get_pixel(x, y).0; canvas.put_pixel(x, y, Rgba([r[0], r[1], r[2], 255])); canvas.put_pixel(w + x, y, Rgba([a[0], a[1], a[2], 255])); let dr = (r[0] as i32 - a[0] as i32).abs(); let dg = (r[1] as i32 - a[1] as i32).abs(); let db = (r[2] as i32 - a[2] as i32).abs(); let err = ((dr + dg + db) as f32 / 3.0) * 4.0; let e = err.clamp(0.0, 255.0) as u8; // Black = exact match, Blue/Cyan = minor diff, Yellow/Red = major visual mismatch! let heat = if e < 12 { [0, 0, e * 2, 255] } else if e < 128 { [0, e, 255 - e, 255] } else { [255, 255 - (e - 128) * 2, 0, 255] }; canvas.put_pixel(w * 2 + x, y, Rgba(heat)); } } let out_dir = output_dir(); std::fs::create_dir_all(&out_dir)?; canvas.save(out_dir.join(format!("{}_diff_report.png", name)))?; Ok(()) }