Skip to main content

velox_engine/
image_pipeline.rs

1//! 通用位图资产管线:纯 Rust PNG/BMP 解码器、显存/内存预算 LRU 缓存、异步后台加载队列、`ObjectFit` 与九宫格 `NineSlice`。
2//!
3//! - 核心数据结构([`ImageAssetId`]、[`ObjectFit`]、[`NineSliceInsets`]、[`DecodedImageSpec`]、[`compute_object_fit`])
4//!   100% 无堆兼容,可在所有硬件与桌面目标上直接构建与排版;
5//! - `std` 环境下提供纯 Rust 零外部依赖 PNG(完整 RFC 1951 Inflate + 5 种滤波器)/ BMP 解码、
6//!   按字节预算自动淘汰的 [`LruImageCache`] 与后台线程池 [`AsyncImageLoader`]。
7
8use crate::element::{Element, IntoElement};
9use crate::paint::CornerRadii;
10use crate::pod::FrameScope;
11use crate::solver::Region;
12use crate::style::Color;
13
14/// 图像资产稳定句柄 ID(用于在 `LruImageCache` 与 GPU 纹理缓存中 $O(1)$ 查找)。
15#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
16pub struct ImageAssetId(pub u32);
17
18/// 图像内容在目标盒子中的缩放适配模式(对应 CSS `object-fit`)。
19#[repr(u8)]
20#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
21pub enum ObjectFit {
22    /// 拉伸填满整个目标区域(不保持纵横比)。
23    Fill = 0,
24    /// 等比缩放使整张图完整显示在盒子内(可能留边)。
25    #[default]
26    Contain = 1,
27    /// 等比缩放填满整个盒子并裁切溢出边缘(最常用于头像/卡片封面)。
28    Cover = 2,
29    /// 仅当原图大于目标盒子时等比缩小,否则按原尺寸居中显示。
30    ScaleDown = 3,
31    /// 按原尺寸居中显示,不做缩放。
32    None = 4,
33}
34
35/// 九宫格(9-Slice)边框保持内边距(单位:源图像素,四角不拉伸、四边单轴拉伸、中心双轴拉伸)。
36#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
37pub struct NineSliceInsets {
38    pub left: u16,
39    pub top: u16,
40    pub right: u16,
41    pub bottom: u16,
42}
43
44impl NineSliceInsets {
45    pub const ZERO: Self = Self {
46        left: 0,
47        top: 0,
48        right: 0,
49        bottom: 0,
50    };
51
52    #[inline(always)]
53    pub const fn all(v: u16) -> Self {
54        Self {
55            left: v,
56            top: v,
57            right: v,
58            bottom: v,
59        }
60    }
61
62    #[inline(always)]
63    pub const fn new(left: u16, top: u16, right: u16, bottom: u16) -> Self {
64        Self {
65            left,
66            top,
67            right,
68            bottom,
69        }
70    }
71
72    #[inline(always)]
73    pub const fn is_active(self) -> bool {
74        self.left > 0 || self.top > 0 || self.right > 0 || self.bottom > 0
75    }
76}
77
78/// 已解码图像绘制规格(分配于 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::DecodedImage`)。
79#[derive(Copy, Clone, PartialEq, Eq, Debug)]
80pub struct DecodedImageSpec {
81    pub id: ImageAssetId,
82    pub width: i16,
83    pub height: i16,
84    pub fit: ObjectFit,
85    pub nine_slice: NineSliceInsets,
86    pub radii: CornerRadii,
87    pub opacity: u8,
88    pub tint: Color,
89    pub fallback_bg: Color,
90    pub content_revision: u64,
91}
92
93impl DecodedImageSpec {
94    #[inline(always)]
95    pub const fn new(id: ImageAssetId, width: i16, height: i16) -> Self {
96        Self {
97            id,
98            width,
99            height,
100            fit: ObjectFit::Contain,
101            nine_slice: NineSliceInsets::ZERO,
102            radii: CornerRadii::ZERO,
103            opacity: 255,
104            tint: Color::WHITE,
105            fallback_bg: Color::rgba(36, 42, 54, 255),
106            content_revision: 0,
107        }
108    }
109
110    #[inline]
111    pub fn mix_hash(&self, h: &mut u32) {
112        let mut mix = |b: u8| {
113            *h ^= b as u32;
114            *h = h.wrapping_mul(0x0100_0193);
115        };
116        for b in self.id.0.to_le_bytes() {
117            mix(b);
118        }
119        mix(self.fit as u8);
120        for b in self.nine_slice.left.to_le_bytes() {
121            mix(b);
122        }
123        for b in self.nine_slice.top.to_le_bytes() {
124            mix(b);
125        }
126        for b in self.nine_slice.right.to_le_bytes() {
127            mix(b);
128        }
129        for b in self.nine_slice.bottom.to_le_bytes() {
130            mix(b);
131        }
132        mix(self.radii.tl);
133        mix(self.radii.tr);
134        mix(self.radii.br);
135        mix(self.radii.bl);
136        mix(self.opacity);
137        for b in self.tint.0.to_le_bytes() {
138            mix(b);
139        }
140        for b in self.fallback_bg.0.to_le_bytes() {
141            mix(b);
142        }
143        for b in self.content_revision.to_le_bytes() {
144            mix(b);
145        }
146    }
147}
148
149/// 声明式解码图像构建器。
150#[derive(Copy, Clone, Debug)]
151pub struct DecodedImage {
152    pub spec: DecodedImageSpec,
153}
154
155/// 构造一个支持 `ObjectFit`、`NineSlice` 与异步 LRU 纹理缓存的通用图像元素。
156#[inline(always)]
157pub const fn decoded_image(id: ImageAssetId, width: i16, height: i16) -> DecodedImage {
158    DecodedImage {
159        spec: DecodedImageSpec::new(id, width, height),
160    }
161}
162
163impl DecodedImage {
164    #[inline(always)]
165    pub const fn fit(mut self, fit: ObjectFit) -> Self {
166        self.spec.fit = fit;
167        self
168    }
169
170    #[inline(always)]
171    pub const fn nine_slice(mut self, insets: NineSliceInsets) -> Self {
172        self.spec.nine_slice = insets;
173        self
174    }
175
176    #[inline(always)]
177    pub const fn rounded(mut self, r: u8) -> Self {
178        self.spec.radii = CornerRadii::all(r);
179        self
180    }
181
182    #[inline(always)]
183    pub const fn rounded_corners(mut self, radii: CornerRadii) -> Self {
184        self.spec.radii = radii;
185        self
186    }
187
188    #[inline(always)]
189    pub const fn opacity(mut self, opacity: u8) -> Self {
190        self.spec.opacity = opacity;
191        self
192    }
193
194    #[inline(always)]
195    pub const fn tint(mut self, tint: Color) -> Self {
196        self.spec.tint = tint;
197        self
198    }
199
200    #[inline(always)]
201    pub const fn fallback_bg(mut self, color: Color) -> Self {
202        self.spec.fallback_bg = color;
203        self
204    }
205
206    #[inline(always)]
207    pub const fn revision(mut self, rev: u64) -> Self {
208        self.spec.content_revision = rev;
209        self
210    }
211}
212
213impl<'a> IntoElement<'a> for DecodedImage {
214    #[inline]
215    fn into_element(self, cx: &'a FrameScope) -> Element<'a> {
216        let spec_ref = cx.arena().alloc_temp(self.spec);
217        Element::DecodedImage(spec_ref)
218    }
219}
220
221/// 根据源图像尺寸 `(src_w, src_h)`、目标绘制区域 `dst` 与 [`ObjectFit`] 计算实际绘制子矩形与采样 UV `[u0, v0, u1, v1]`。
222pub fn compute_object_fit(
223    src_w: u32,
224    src_h: u32,
225    dst: Region,
226    fit: ObjectFit,
227) -> (Region, [f32; 4]) {
228    if src_w == 0 || src_h == 0 || dst.w <= 0 || dst.h <= 0 {
229        return (dst, [0.0, 0.0, 1.0, 1.0]);
230    }
231    let sw = src_w as f32;
232    let sh = src_h as f32;
233    let dw = dst.w as f32;
234    let dh = dst.h as f32;
235
236    match fit {
237        ObjectFit::Fill => (dst, [0.0, 0.0, 1.0, 1.0]),
238        ObjectFit::Contain => {
239            let scale = (dw / sw).min(dh / sh);
240            let rw = (sw * scale).max(1.0);
241            let rh = (sh * scale).max(1.0);
242            let rx = dst.x as f32 + (dw - rw) * 0.5;
243            let ry = dst.y as f32 + (dh - rh) * 0.5;
244            (
245                Region::new(rx as i16, ry as i16, rw as i16, rh as i16),
246                [0.0, 0.0, 1.0, 1.0],
247            )
248        }
249        ObjectFit::Cover => {
250            let scale = (dw / sw).max(dh / sh);
251            let vis_w = (dw / scale) / sw;
252            let vis_h = (dh / scale) / sh;
253            let u0 = ((1.0 - vis_w) * 0.5).clamp(0.0, 0.5);
254            let v0 = ((1.0 - vis_h) * 0.5).clamp(0.0, 0.5);
255            (dst, [u0, v0, 1.0 - u0, 1.0 - v0])
256        }
257        ObjectFit::ScaleDown => {
258            if sw <= dw && sh <= dh {
259                compute_object_fit(src_w, src_h, dst, ObjectFit::None)
260            } else {
261                compute_object_fit(src_w, src_h, dst, ObjectFit::Contain)
262            }
263        }
264        ObjectFit::None => {
265            let rw = sw.min(dw);
266            let rh = sh.min(dh);
267            let rx = dst.x as f32 + (dw - rw) * 0.5;
268            let ry = dst.y as f32 + (dh - rh) * 0.5;
269            let u_span = (rw / sw).min(1.0);
270            let v_span = (rh / sh).min(1.0);
271            let u0 = (1.0 - u_span) * 0.5;
272            let v0 = (1.0 - v_span) * 0.5;
273            (
274                Region::new(rx as i16, ry as i16, rw as i16, rh as i16),
275                [u0, v0, u0 + u_span, v0 + v_span],
276            )
277        }
278    }
279}
280
281/// 九宫格坐标映射:将目标局部像素位置 `pos`(区间 `[0, dst_len)`)映射到源图浮点采样坐标(区间 `[0, src_len)`)。
282#[inline]
283pub fn map_nine_slice_coord(pos: f32, dst_len: f32, src_len: f32, start_inset: u16, end_inset: u16) -> f32 {
284    if dst_len <= 0.0 || src_len <= 0.0 {
285        return 0.0;
286    }
287    let si = (start_inset as f32).min(src_len * 0.5).min(dst_len * 0.5);
288    let ei = (end_inset as f32).min(src_len * 0.5).min(dst_len * 0.5);
289    if pos < si {
290        pos
291    } else if pos >= dst_len - ei {
292        src_len - (dst_len - pos)
293    } else {
294        let dst_mid = (dst_len - si - ei).max(1.0);
295        let src_mid = (src_len - si - ei).max(0.0);
296        si + ((pos - si) / dst_mid) * src_mid
297    }
298}
299
300// ============================================================================
301// `std` 通用图像解码(PNG / BMP / 魔数探测)、预算感知 LRU 缓存与异步后台解码管线
302// ============================================================================
303
304mod std_pipeline {
305    use super::*;
306    use std::collections::HashMap;
307    use std::sync::atomic::{AtomicU64, Ordering};
308    use std::sync::{Arc, Mutex, OnceLock, RwLock};
309    use std::vec;
310    use std::vec::Vec;
311
312    /// 支持探测的图像容器格式。
313    #[derive(Copy, Clone, PartialEq, Eq, Debug)]
314    pub enum ImageFormat {
315        Png,
316        Jpeg,
317        WebP,
318        Bmp,
319        Unknown,
320    }
321
322    /// 识别字节流的图像文件格式魔数。
323    pub fn detect_image_format(bytes: &[u8]) -> ImageFormat {
324        if bytes.len() >= 8 && &bytes[..8] == b"\x89PNG\r\n\x1a\n" {
325            ImageFormat::Png
326        } else if bytes.len() >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF {
327            ImageFormat::Jpeg
328        } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
329            ImageFormat::WebP
330        } else if bytes.len() >= 2 && &bytes[..2] == b"BM" {
331            ImageFormat::Bmp
332        } else {
333            ImageFormat::Unknown
334        }
335    }
336
337    /// 已解码的直通 RGBA8888 图像像素缓冲(线程安全共享)。
338    #[derive(Clone, Debug)]
339    pub struct DecodedPixels {
340        pub width: u32,
341        pub height: u32,
342        pub rgba: Arc<[u8]>,
343        pub revision: u64,
344    }
345
346    impl DecodedPixels {
347        #[inline]
348        pub fn byte_size(&self) -> usize {
349            self.rgba.len()
350        }
351    }
352
353    /// 异步图像加载状态。
354    #[derive(Clone, Debug)]
355    pub enum ImageLoadState {
356        Loading,
357        Ready(DecodedPixels),
358        Failed,
359    }
360
361    /// 按显存/内存字节预算自动淘汰最久未用条目的 LRU 图像缓存。
362    pub struct LruImageCache {
363        max_bytes: usize,
364        cur_bytes: usize,
365        clock: u64,
366        entries: HashMap<ImageAssetId, (DecodedPixels, u64)>,
367    }
368
369    impl LruImageCache {
370        pub fn new(max_bytes: usize) -> Self {
371            Self {
372                max_bytes: max_bytes.max(1024),
373                cur_bytes: 0,
374                clock: 0,
375                entries: HashMap::new(),
376            }
377        }
378
379        #[inline]
380        pub fn current_bytes(&self) -> usize {
381            self.cur_bytes
382        }
383
384        #[inline]
385        pub fn max_bytes(&self) -> usize {
386            self.max_bytes
387        }
388
389        #[inline]
390        pub fn set_max_bytes(&mut self, max_bytes: usize) {
391            self.max_bytes = max_bytes.max(1024);
392            self.evict_if_needed();
393        }
394
395        #[inline]
396        pub fn len(&self) -> usize {
397            self.entries.len()
398        }
399
400        #[inline]
401        pub fn is_empty(&self) -> bool {
402            self.entries.is_empty()
403        }
404
405        pub fn insert(&mut self, id: ImageAssetId, pixels: DecodedPixels) {
406            if let Some((old, _)) = self.entries.remove(&id) {
407                self.cur_bytes = self.cur_bytes.saturating_sub(old.byte_size());
408            }
409            self.clock = self.clock.saturating_add(1);
410            self.cur_bytes = self.cur_bytes.saturating_add(pixels.byte_size());
411            self.entries.insert(id, (pixels, self.clock));
412            self.evict_if_needed();
413        }
414
415        pub fn get(&mut self, id: ImageAssetId) -> Option<DecodedPixels> {
416            self.clock = self.clock.saturating_add(1);
417            let clk = self.clock;
418            if let Some((px, stamp)) = self.entries.get_mut(&id) {
419                *stamp = clk;
420                return Some(px.clone());
421            }
422            None
423        }
424
425        pub fn remove(&mut self, id: ImageAssetId) -> bool {
426            if let Some((old, _)) = self.entries.remove(&id) {
427                self.cur_bytes = self.cur_bytes.saturating_sub(old.byte_size());
428                true
429            } else {
430                false
431            }
432        }
433
434        pub fn clear(&mut self) {
435            self.entries.clear();
436            self.cur_bytes = 0;
437        }
438
439        fn evict_if_needed(&mut self) {
440            while self.cur_bytes > self.max_bytes && self.entries.len() > 1 {
441                let Some((&victim_id, _)) = self.entries.iter().min_by_key(|(_, (_, ts))| *ts) else {
442                    break;
443                };
444                if let Some((old, _)) = self.entries.remove(&victim_id) {
445                    self.cur_bytes = self.cur_bytes.saturating_sub(old.byte_size());
446                }
447            }
448        }
449    }
450
451    type CustomDecoderFn = fn(&[u8]) -> Option<(u32, u32, Vec<u8>)>;
452    static CUSTOM_DECODERS: OnceLock<RwLock<Vec<CustomDecoderFn>>> = OnceLock::new();
453    static GLOBAL_IMAGE_CACHE: OnceLock<Mutex<LruImageCache>> = OnceLock::new();
454    static GLOBAL_IMAGE_STATES: OnceLock<Mutex<HashMap<ImageAssetId, ImageLoadState>>> = OnceLock::new();
455    static NEXT_IMAGE_REV: AtomicU64 = AtomicU64::new(1);
456
457    /// 注册外部格式解码器(例如项目外部接入 `zune-jpeg` / `webp` 时无缝挂载到统一管线)。
458    pub fn register_custom_image_decoder(decoder: CustomDecoderFn) {
459        let list = CUSTOM_DECODERS.get_or_init(|| RwLock::new(Vec::new()));
460        if let Ok(mut w) = list.write() {
461            w.push(decoder);
462        }
463    }
464
465    /// 设置全局图像 LRU 缓存字节上限(默认 64 MiB)。
466    pub fn set_global_image_cache_budget(max_bytes: usize) {
467        let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(64 * 1024 * 1024)));
468        if let Ok(mut c) = cache.lock() {
469            c.set_max_bytes(max_bytes);
470        }
471    }
472
473    /// 直接向全局 LRU 缓存注册已解码的 RGBA8888 像素(返回递增版本号)。
474    pub fn register_image_rgba(id: ImageAssetId, width: u32, height: u32, rgba: Vec<u8>) -> Option<u64> {
475        if width == 0 || height == 0 || rgba.len() != (width as usize) * (height as usize) * 4 {
476            return None;
477        }
478        let rev = NEXT_IMAGE_REV.fetch_add(1, Ordering::Relaxed);
479        let px = DecodedPixels {
480            width,
481            height,
482            rgba: Arc::from(rgba.into_boxed_slice()),
483            revision: rev,
484        };
485        let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(64 * 1024 * 1024)));
486        if let Ok(mut c) = cache.lock() {
487            c.insert(id, px.clone());
488        }
489        let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
490        if let Ok(mut s) = states.lock() {
491            s.insert(id, ImageLoadState::Ready(px));
492        }
493        Some(rev)
494    }
495
496    /// 同步解码 PNG / BMP / 自定义格式字节流并写入全局 LRU 缓存。
497    pub fn load_image_bytes(id: ImageAssetId, bytes: &[u8]) -> Option<u64> {
498        let (w, h, rgba) = decode_image_bytes(bytes)?;
499        register_image_rgba(id, w, h, rgba)
500    }
501
502    /// 在后台线程异步解码图像字节流,完成后自动写入全局 LRU 缓存并触发 `on_ready` 唤醒回调。
503    pub fn load_image_bytes_async(
504        id: ImageAssetId,
505        bytes: Vec<u8>,
506        on_ready: Option<Arc<dyn Fn(ImageAssetId, bool) + Send + Sync + 'static>>,
507    ) {
508        let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
509        if let Ok(mut s) = states.lock() {
510            s.insert(id, ImageLoadState::Loading);
511        }
512        let _ = std::thread::Builder::new()
513            .name(std::string::String::from("velox-img-decode"))
514            .spawn(move || {
515                let ok = load_image_bytes(id, &bytes).is_some();
516                if !ok {
517                    let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
518                    if let Ok(mut s) = states.lock() {
519                        s.insert(id, ImageLoadState::Failed);
520                    }
521                }
522                if let Some(cb) = on_ready {
523                    cb(id, ok);
524                }
525            });
526    }
527
528    /// 查询指定图像 ID 的缓存像素(同时刷新其 LRU 活跃时间戳)。
529    pub fn get_cached_image(id: ImageAssetId) -> Option<DecodedPixels> {
530        let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(64 * 1024 * 1024)));
531        cache.lock().ok().and_then(|mut c| c.get(id))
532    }
533
534    /// 查询指定图像 ID 的异步加载状态。
535    pub fn image_load_state(id: ImageAssetId) -> Option<ImageLoadState> {
536        let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
537        states.lock().ok().and_then(|s| s.get(&id).cloned())
538    }
539
540    /// 统一解码入口:内置纯 Rust PNG + BMP 解码器,未知或 JPEG/WebP 格式自动尝试已注册外部解码器。
541    pub fn decode_image_bytes(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
542        match detect_image_format(bytes) {
543            ImageFormat::Png => decode_png(bytes),
544            ImageFormat::Bmp => decode_bmp(bytes),
545            _ => {
546                if let Some(list) = CUSTOM_DECODERS.get() {
547                    if let Ok(r) = list.read() {
548                        for dec in r.iter() {
549                            if let Some(res) = dec(bytes) {
550                                return Some(res);
551                            }
552                        }
553                    }
554                }
555                None
556            }
557        }
558    }
559
560    // ------------------------------------------------------------------------
561    // 纯 Rust BMP 解码器(24-bit BGR / 32-bit BGRA)
562    // ------------------------------------------------------------------------
563
564    fn decode_bmp(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
565        if bytes.len() < 54 || &bytes[..2] != b"BM" {
566            return None;
567        }
568        let data_off = u32::from_le_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]) as usize;
569        let w = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);
570        let h_signed = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]);
571        let bpp = u16::from_le_bytes([bytes[28], bytes[29]]);
572        let comp = u32::from_le_bytes([bytes[30], bytes[31], bytes[32], bytes[33]]);
573        if w <= 0 || h_signed == 0 || (bpp != 24 && bpp != 32) || comp != 0 {
574            return None;
575        }
576        let width = w as u32;
577        let top_down = h_signed < 0;
578        let height = h_signed.unsigned_abs();
579        let bytes_per_px = (bpp / 8) as usize;
580        let row_stride = ((width as usize) * bytes_per_px + 3) & !3;
581        if data_off + row_stride * (height as usize) > bytes.len() {
582            return None;
583        }
584        let mut rgba = vec![0u8; (width as usize) * (height as usize) * 4];
585        for y in 0..(height as usize) {
586            let src_y = if top_down { y } else { (height as usize) - 1 - y };
587            let row = &bytes[data_off + src_y * row_stride..data_off + (src_y + 1) * row_stride];
588            for x in 0..(width as usize) {
589                let si = x * bytes_per_px;
590                let di = (y * (width as usize) + x) * 4;
591                rgba[di] = row[si + 2];
592                rgba[di + 1] = row[si + 1];
593                rgba[di + 2] = row[si];
594                rgba[di + 3] = if bytes_per_px == 4 { row[si + 3] } else { 255 };
595            }
596        }
597        Some((width, height, rgba))
598    }
599
600    // ------------------------------------------------------------------------
601    // 纯 Rust PNG 解码器(RFC 2083 + RFC 1951 Inflate + 5 种滤波器)
602    // ------------------------------------------------------------------------
603
604    struct BitReader<'a> {
605        data: &'a [u8],
606        pos: usize,
607        bit_buf: u32,
608        bit_cnt: u32,
609    }
610
611    impl<'a> BitReader<'a> {
612        fn new(data: &'a [u8]) -> Self {
613            Self {
614                data,
615                pos: 0,
616                bit_buf: 0,
617                bit_cnt: 0,
618            }
619        }
620
621        #[inline]
622        fn read_bits(&mut self, n: u32) -> Option<u32> {
623            while self.bit_cnt < n {
624                if self.pos >= self.data.len() {
625                    return None;
626                }
627                self.bit_buf |= (self.data[self.pos] as u32) << self.bit_cnt;
628                self.pos += 1;
629                self.bit_cnt += 8;
630            }
631            let mask = if n == 32 { u32::MAX } else { (1u32 << n) - 1 };
632            let val = self.bit_buf & mask;
633            self.bit_buf >>= n;
634            self.bit_cnt -= n;
635            Some(val)
636        }
637
638        fn align_byte(&mut self) {
639            let drop_bits = self.bit_cnt & 7;
640            self.bit_buf >>= drop_bits;
641            self.bit_cnt -= drop_bits;
642        }
643
644        fn read_u16_le_aligned(&mut self) -> Option<u16> {
645            self.align_byte();
646            let lo = self.read_bits(8)? as u16;
647            let hi = self.read_bits(8)? as u16;
648            Some(lo | (hi << 8))
649        }
650    }
651
652    struct HuffTree {
653        counts: [u16; 16],
654        symbols: Vec<u16>,
655    }
656
657    impl HuffTree {
658        fn from_lengths(lengths: &[u8]) -> Option<Self> {
659            let mut counts = [0u16; 16];
660            for &len in lengths {
661                if len as usize >= 16 {
662                    return None;
663                }
664                if len > 0 {
665                    counts[len as usize] += 1;
666                }
667            }
668            let mut offsets = [0u16; 16];
669            let mut sum = 0u16;
670            for bits in 1..16 {
671                offsets[bits] = sum;
672                sum = sum.checked_add(counts[bits])?;
673            }
674            let mut symbols = vec![0u16; sum as usize];
675            for (sym, &len) in lengths.iter().enumerate() {
676                if len > 0 {
677                    let off = offsets[len as usize] as usize;
678                    symbols[off] = sym as u16;
679                    offsets[len as usize] += 1;
680                }
681            }
682            Some(Self { counts, symbols })
683        }
684
685        fn decode(&self, br: &mut BitReader<'_>) -> Option<u16> {
686            let mut code = 0i32;
687            let mut first = 0i32;
688            let mut index = 0i32;
689            for len in 1..16 {
690                code |= br.read_bits(1)? as i32;
691                let cnt = self.counts[len] as i32;
692                if code - cnt < first {
693                    return self.symbols.get((index + (code - first)) as usize).copied();
694                }
695                index += cnt;
696                first = (first + cnt) << 1;
697                code <<= 1;
698            }
699            None
700        }
701    }
702
703    fn inflate_zlib(zlib: &[u8]) -> Option<Vec<u8>> {
704        if zlib.len() < 6 {
705            return None;
706        }
707        let cmf = zlib[0];
708        let flg = zlib[1];
709        if (cmf & 0x0F) != 8 || (((cmf as u16) << 8 | flg as u16) % 31) != 0 {
710            return None;
711        }
712        let start = if (flg & 0x20) != 0 { 6 } else { 2 };
713        let mut br = BitReader::new(&zlib[start..]);
714        let mut out = Vec::new();
715
716        const LEN_BASE: [u16; 29] = [
717            3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99,
718            115, 131, 163, 195, 227, 258,
719        ];
720        const LEN_EXTRA: [u8; 29] = [
721            0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
722        ];
723        const DIST_BASE: [u16; 30] = [
724            1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025,
725            1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
726        ];
727        const DIST_EXTRA: [u8; 30] = [
728            0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12,
729            12, 13, 13,
730        ];
731        const CL_ORDER: [usize; 19] = [
732            16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
733        ];
734
735        loop {
736            let bfinal = br.read_bits(1)?;
737            let btype = br.read_bits(2)?;
738            match btype {
739                0 => {
740                    let len = br.read_u16_le_aligned()?;
741                    let nlen = br.read_u16_le_aligned()?;
742                    if len != !nlen {
743                        return None;
744                    }
745                    for _ in 0..len {
746                        out.push(br.read_bits(8)? as u8);
747                    }
748                }
749                1 | 2 => {
750                    let (lit_tree, dist_tree) = if btype == 1 {
751                        let mut ll = [0u8; 288];
752                        for l in &mut ll[0..144] {
753                            *l = 8;
754                        }
755                        for l in &mut ll[144..256] {
756                            *l = 9;
757                        }
758                        for l in &mut ll[256..280] {
759                            *l = 7;
760                        }
761                        for l in &mut ll[280..288] {
762                            *l = 8;
763                        }
764                        let dl = [5u8; 32];
765                        (HuffTree::from_lengths(&ll)?, HuffTree::from_lengths(&dl)?)
766                    } else {
767                        let hlit = br.read_bits(5)? as usize + 257;
768                        let hdist = br.read_bits(5)? as usize + 1;
769                        let hclen = br.read_bits(4)? as usize + 4;
770                        let mut cl_lens = [0u8; 19];
771                        for i in 0..hclen {
772                            cl_lens[CL_ORDER[i]] = br.read_bits(3)? as u8;
773                        }
774                        let cl_tree = HuffTree::from_lengths(&cl_lens)?;
775                        let mut lens = Vec::with_capacity(hlit + hdist);
776                        while lens.len() < hlit + hdist {
777                            let sym = cl_tree.decode(&mut br)?;
778                            match sym {
779                                0..=15 => lens.push(sym as u8),
780                                16 => {
781                                    let prev = *lens.last()?;
782                                    let rep = br.read_bits(2)? as usize + 3;
783                                    for _ in 0..rep {
784                                        lens.push(prev);
785                                    }
786                                }
787                                17 => {
788                                    let rep = br.read_bits(3)? as usize + 3;
789                                    for _ in 0..rep {
790                                        lens.push(0);
791                                    }
792                                }
793                                18 => {
794                                    let rep = br.read_bits(7)? as usize + 11;
795                                    for _ in 0..rep {
796                                        lens.push(0);
797                                    }
798                                }
799                                _ => return None,
800                            }
801                        }
802                        if lens.len() < hlit + hdist {
803                            return None;
804                        }
805                        (
806                            HuffTree::from_lengths(&lens[..hlit])?,
807                            HuffTree::from_lengths(&lens[hlit..hlit + hdist])?,
808                        )
809                    };
810
811                    loop {
812                        let sym = lit_tree.decode(&mut br)?;
813                        if sym < 256 {
814                            out.push(sym as u8);
815                        } else if sym == 256 {
816                            break;
817                        } else {
818                            let lidx = (sym as usize).checked_sub(257)?;
819                            if lidx >= 29 {
820                                return None;
821                            }
822                            let length = LEN_BASE[lidx] as usize
823                                + br.read_bits(LEN_EXTRA[lidx] as u32)? as usize;
824                            let dsym = dist_tree.decode(&mut br)? as usize;
825                            if dsym >= 30 {
826                                return None;
827                            }
828                            let dist = DIST_BASE[dsym] as usize
829                                + br.read_bits(DIST_EXTRA[dsym] as u32)? as usize;
830                            if dist == 0 || dist > out.len() {
831                                return None;
832                            }
833                            for _ in 0..length {
834                                let b = out[out.len() - dist];
835                                out.push(b);
836                            }
837                        }
838                    }
839                }
840                _ => return None,
841            }
842            if bfinal != 0 {
843                break;
844            }
845        }
846        Some(out)
847    }
848
849    #[inline]
850    fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
851        let ai = a as i32;
852        let bi = b as i32;
853        let ci = c as i32;
854        let p = ai + bi - ci;
855        let pa = (p - ai).abs();
856        let pb = (p - bi).abs();
857        let pc = (p - ci).abs();
858        if pa <= pb && pa <= pc {
859            a
860        } else if pb <= pc {
861            b
862        } else {
863            c
864        }
865    }
866
867    fn decode_png(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
868        if bytes.len() < 33 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" {
869            return None;
870        }
871        let mut pos = 8usize;
872        let mut width = 0u32;
873        let mut height = 0u32;
874        let mut bit_depth = 0u8;
875        let mut color_type = 0u8;
876        let mut interlace = 0u8;
877        let mut palette: Vec<[u8; 3]> = Vec::new();
878        let mut trns: Vec<u8> = Vec::new();
879        let mut idat: Vec<u8> = Vec::new();
880
881        while pos + 12 <= bytes.len() {
882            let len = u32::from_be_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
883            let ctype = &bytes[pos + 4..pos + 8];
884            let data_start = pos + 8;
885            let data_end = data_start.checked_add(len)?;
886            if data_end + 4 > bytes.len() {
887                return None;
888            }
889            let chunk = &bytes[data_start..data_end];
890            match ctype {
891                b"IHDR" => {
892                    if chunk.len() < 13 {
893                        return None;
894                    }
895                    width = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
896                    height = u32::from_be_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
897                    bit_depth = chunk[8];
898                    color_type = chunk[9];
899                    interlace = chunk[12];
900                }
901                b"PLTE" => {
902                    for rgb in chunk.chunks_exact(3) {
903                        palette.push([rgb[0], rgb[1], rgb[2]]);
904                    }
905                }
906                b"tRNS" => {
907                    trns.extend_from_slice(chunk);
908                }
909                b"IDAT" => {
910                    idat.extend_from_slice(chunk);
911                }
912                b"IEND" => break,
913                _ => {}
914            }
915            pos = data_end + 4;
916        }
917
918        if width == 0 || height == 0 || bit_depth != 8 || interlace != 0 {
919            return None;
920        }
921        let bpp = match color_type {
922            0 => 1usize, // Gray
923            2 => 3usize, // RGB
924            3 => 1usize, // Indexed
925            4 => 2usize, // GrayAlpha
926            6 => 4usize, // RGBA
927            _ => return None,
928        };
929        let raw = inflate_zlib(&idat)?;
930        let row_bytes = (width as usize) * bpp;
931        if raw.len() < (height as usize) * (row_bytes + 1) {
932            return None;
933        }
934
935        let mut prev_row = vec![0u8; row_bytes];
936        let mut cur_row = vec![0u8; row_bytes];
937        let mut rgba = vec![0u8; (width as usize) * (height as usize) * 4];
938
939        for y in 0..(height as usize) {
940            let line = &raw[y * (row_bytes + 1)..(y + 1) * (row_bytes + 1)];
941            let filter = line[0];
942            let src = &line[1..];
943            for i in 0..row_bytes {
944                let left = if i >= bpp { cur_row[i - bpp] } else { 0 };
945                let up = prev_row[i];
946                let up_left = if i >= bpp { prev_row[i - bpp] } else { 0 };
947                cur_row[i] = match filter {
948                    0 => src[i],
949                    1 => src[i].wrapping_add(left),
950                    2 => src[i].wrapping_add(up),
951                    3 => src[i].wrapping_add((((left as u16) + (up as u16)) >> 1) as u8),
952                    4 => src[i].wrapping_add(paeth_predictor(left, up, up_left)),
953                    _ => return None,
954                };
955            }
956
957            let dst_row = &mut rgba[y * (width as usize) * 4..(y + 1) * (width as usize) * 4];
958            match color_type {
959                0 => {
960                    for x in 0..(width as usize) {
961                        let g = cur_row[x];
962                        let d = x * 4;
963                        dst_row[d] = g;
964                        dst_row[d + 1] = g;
965                        dst_row[d + 2] = g;
966                        dst_row[d + 3] = 255;
967                    }
968                }
969                2 => {
970                    for x in 0..(width as usize) {
971                        let s = x * 3;
972                        let d = x * 4;
973                        dst_row[d] = cur_row[s];
974                        dst_row[d + 1] = cur_row[s + 1];
975                        dst_row[d + 2] = cur_row[s + 2];
976                        dst_row[d + 3] = 255;
977                    }
978                }
979                3 => {
980                    for x in 0..(width as usize) {
981                        let idx = cur_row[x] as usize;
982                        let [r, g, b] = palette.get(idx).copied().unwrap_or([0, 0, 0]);
983                        let a = trns.get(idx).copied().unwrap_or(255);
984                        let d = x * 4;
985                        dst_row[d] = r;
986                        dst_row[d + 1] = g;
987                        dst_row[d + 2] = b;
988                        dst_row[d + 3] = a;
989                    }
990                }
991                4 => {
992                    for x in 0..(width as usize) {
993                        let s = x * 2;
994                        let d = x * 4;
995                        let g = cur_row[s];
996                        dst_row[d] = g;
997                        dst_row[d + 1] = g;
998                        dst_row[d + 2] = g;
999                        dst_row[d + 3] = cur_row[s + 1];
1000                    }
1001                }
1002                6 => {
1003                    dst_row.copy_from_slice(&cur_row);
1004                }
1005                _ => return None,
1006            }
1007            core::mem::swap(&mut prev_row, &mut cur_row);
1008        }
1009
1010        Some((width, height, rgba))
1011    }
1012}
1013
1014pub use std_pipeline::{
1015    decode_image_bytes, detect_image_format, get_cached_image, image_load_state,
1016    load_image_bytes, load_image_bytes_async, register_custom_image_decoder, register_image_rgba,
1017    set_global_image_cache_budget, DecodedPixels, ImageFormat, ImageLoadState, LruImageCache,
1018};