1use crate::element::{Element, IntoElement};
9use crate::paint::CornerRadii;
10use crate::pod::FrameScope;
11use crate::solver::Region;
12use crate::style::Color;
13
14#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
16pub struct ImageAssetId(pub u32);
17
18#[repr(u8)]
20#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
21pub enum ObjectFit {
22 Fill = 0,
24 #[default]
26 Contain = 1,
27 Cover = 2,
29 ScaleDown = 3,
31 None = 4,
33}
34
35#[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#[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#[derive(Copy, Clone, Debug)]
151pub struct DecodedImage {
152 pub spec: DecodedImageSpec,
153}
154
155#[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
221pub 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#[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
300mod std_pipeline {
305 use super::*;
306 use std::collections::{HashMap, VecDeque};
307 use std::sync::atomic::{AtomicU64, Ordering};
308 use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock};
309 use std::vec;
310 use std::vec::Vec;
311
312 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
314 pub enum ImageFormat {
315 Png,
316 Jpeg,
317 WebP,
318 Bmp,
319 Unknown,
320 }
321
322 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 #[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 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
355 pub struct ImageMetadata {
356 pub width: u32,
357 pub height: u32,
358 pub revision: u64,
359 }
360
361 impl ImageMetadata {
362 #[inline]
364 pub const fn byte_size(&self) -> usize {
365 (self.width as usize)
366 .saturating_mul(self.height as usize)
367 .saturating_mul(4)
368 }
369 }
370
371 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
373 pub enum ImageLoadState {
374 Loading,
375 Ready(ImageMetadata),
376 Failed,
377 }
378
379 pub struct LruImageCache {
381 max_bytes: usize,
382 cur_bytes: usize,
383 clock: u64,
384 entries: HashMap<ImageAssetId, (DecodedPixels, u64)>,
385 }
386
387 impl LruImageCache {
388 pub fn new(max_bytes: usize) -> Self {
389 Self {
390 max_bytes,
391 cur_bytes: 0,
392 clock: 0,
393 entries: HashMap::new(),
394 }
395 }
396
397 #[inline]
398 pub fn current_bytes(&self) -> usize {
399 self.cur_bytes
400 }
401
402 #[inline]
403 pub fn max_bytes(&self) -> usize {
404 self.max_bytes
405 }
406
407 #[inline]
408 pub fn set_max_bytes(&mut self, max_bytes: usize) {
409 self.max_bytes = max_bytes;
410 self.evict_if_needed();
411 }
412
413 #[inline]
414 pub fn len(&self) -> usize {
415 self.entries.len()
416 }
417
418 #[inline]
419 pub fn is_empty(&self) -> bool {
420 self.entries.is_empty()
421 }
422
423 pub fn insert(&mut self, id: ImageAssetId, pixels: DecodedPixels) {
425 let _ = self.insert_checked(id, pixels);
426 }
427
428 pub fn insert_checked(&mut self, id: ImageAssetId, pixels: DecodedPixels) -> bool {
430 if let Some((old, _)) = self.entries.remove(&id) {
431 self.cur_bytes = self.cur_bytes.saturating_sub(old.byte_size());
432 }
433 let sz = pixels.byte_size();
434 if sz > self.max_bytes {
435 return false;
437 }
438 self.clock = self.clock.saturating_add(1);
439 self.cur_bytes = self.cur_bytes.saturating_add(sz);
440 self.entries.insert(id, (pixels, self.clock));
441 self.evict_if_needed();
442 true
443 }
444
445 pub fn get(&mut self, id: ImageAssetId) -> Option<DecodedPixels> {
446 self.clock = self.clock.saturating_add(1);
447 let clk = self.clock;
448 if let Some((px, stamp)) = self.entries.get_mut(&id) {
449 *stamp = clk;
450 return Some(px.clone());
451 }
452 None
453 }
454
455 pub fn remove(&mut self, id: ImageAssetId) -> bool {
456 if let Some((old, _)) = self.entries.remove(&id) {
457 self.cur_bytes = self.cur_bytes.saturating_sub(old.byte_size());
458 true
459 } else {
460 false
461 }
462 }
463
464 pub fn clear(&mut self) {
465 self.entries.clear();
466 self.cur_bytes = 0;
467 }
468
469 fn evict_if_needed(&mut self) {
470 while self.cur_bytes > self.max_bytes {
471 let Some((&victim_id, _)) = self.entries.iter().min_by_key(|(_, (_, ts))| *ts) else {
472 break;
473 };
474 if let Some((old, _)) = self.entries.remove(&victim_id) {
475 self.cur_bytes = self.cur_bytes.saturating_sub(old.byte_size());
476 }
477 }
478 }
479 }
480
481 type CustomDecoderFn = fn(&[u8]) -> Option<(u32, u32, Vec<u8>)>;
482 type ReadyCallback = Arc<dyn Fn(ImageAssetId, bool) + Send + Sync + 'static>;
483
484 const DEFAULT_IMAGE_CACHE_BUDGET: usize = 64 * 1024 * 1024;
485 const MAX_DECODE_QUEUE_LEN: usize = 256;
486 const DEFAULT_MAX_IN_FLIGHT_DECODE_BYTES: usize = 32 * 1024 * 1024;
487
488 static CUSTOM_DECODERS: OnceLock<RwLock<Vec<CustomDecoderFn>>> = OnceLock::new();
489 static GLOBAL_IMAGE_CACHE: OnceLock<Mutex<LruImageCache>> = OnceLock::new();
490 static GLOBAL_IMAGE_STATES: OnceLock<Mutex<HashMap<ImageAssetId, ImageLoadState>>> = OnceLock::new();
491 static NEXT_IMAGE_REV: AtomicU64 = AtomicU64::new(1);
492
493 struct DecodeJob {
494 id: ImageAssetId,
495 bytes: Vec<u8>,
496 estimated_rgba_bytes: usize,
497 on_ready: Option<ReadyCallback>,
498 }
499
500 struct DecodePoolState {
501 queue: VecDeque<DecodeJob>,
502 in_flight_bytes: usize,
503 max_in_flight_bytes: usize,
504 worker_count: usize,
505 }
506
507 struct DecodePool {
508 state: Mutex<DecodePoolState>,
509 cv: Condvar,
510 }
511
512 static DECODE_POOL: OnceLock<Arc<DecodePool>> = OnceLock::new();
513
514 fn estimate_decoded_rgba_bytes(bytes: &[u8]) -> usize {
515 if bytes.len() >= 24 && &bytes[..8] == b"\x89PNG\r\n\x1a\n" && &bytes[12..16] == b"IHDR" {
517 let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]) as usize;
518 let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]) as usize;
519 if w > 0 && h > 0 {
520 return w.saturating_mul(h).saturating_mul(4).max(4096);
521 }
522 } else if bytes.len() >= 26 && &bytes[..2] == b"BM" {
523 let w = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);
524 let h = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]).unsigned_abs();
525 if w > 0 && h > 0 {
526 return (w as usize).saturating_mul(h as usize).saturating_mul(4).max(4096);
527 }
528 }
529 bytes.len().saturating_mul(4).max(4096)
530 }
531
532 fn decode_pool() -> &'static Arc<DecodePool> {
533 DECODE_POOL.get_or_init(|| {
534 let workers = std::thread::available_parallelism()
535 .map(|n| n.get().clamp(2, 4))
536 .unwrap_or(2);
537 let pool = Arc::new(DecodePool {
538 state: Mutex::new(DecodePoolState {
539 queue: VecDeque::with_capacity(32),
540 in_flight_bytes: 0,
541 max_in_flight_bytes: DEFAULT_MAX_IN_FLIGHT_DECODE_BYTES,
542 worker_count: workers,
543 }),
544 cv: Condvar::new(),
545 });
546 for idx in 0..workers {
547 let p = Arc::clone(&pool);
548 let _ = std::thread::Builder::new()
549 .name(std::format!("velox-img-decode-{idx}"))
550 .spawn(move || decode_worker_loop(p));
551 }
552 pool
553 })
554 }
555
556 fn decode_worker_loop(pool: Arc<DecodePool>) {
557 loop {
558 let (job, reserved_bytes) = {
559 let Ok(mut st) = pool.state.lock() else {
560 return;
561 };
562 loop {
563 if let Some(front) = st.queue.front() {
564 if st.in_flight_bytes == 0
566 || st.in_flight_bytes.saturating_add(front.estimated_rgba_bytes)
567 <= st.max_in_flight_bytes
568 {
569 let job = st.queue.pop_front().unwrap();
570 let est = job.estimated_rgba_bytes;
571 st.in_flight_bytes = st.in_flight_bytes.saturating_add(est);
572 break (job, est);
573 }
574 }
575 let Ok(guard) = pool.cv.wait(st) else {
576 return;
577 };
578 st = guard;
579 }
580 };
581
582 let ok = decode_and_commit_async(job.id, &job.bytes);
583
584 {
585 if let Ok(mut st) = pool.state.lock() {
586 st.in_flight_bytes = st.in_flight_bytes.saturating_sub(reserved_bytes);
587 pool.cv.notify_all();
588 }
589 }
590
591 if let Some(cb) = job.on_ready {
592 cb(job.id, ok);
593 }
594 }
595 }
596
597 fn decode_and_commit_async(id: ImageAssetId, bytes: &[u8]) -> bool {
598 let decoded = decode_image_bytes(bytes);
599 let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
600 let still_loading = states
602 .lock()
603 .ok()
604 .is_some_and(|s| matches!(s.get(&id), Some(ImageLoadState::Loading)));
605 if !still_loading {
606 return false;
607 }
608 if let Some((w, h, rgba)) = decoded {
609 register_image_rgba(id, w, h, rgba).is_some()
610 } else {
611 if let Ok(mut s) = states.lock() {
612 if matches!(s.get(&id), Some(ImageLoadState::Loading)) {
613 s.insert(id, ImageLoadState::Failed);
614 }
615 }
616 false
617 }
618 }
619
620 pub fn set_async_decode_in_flight_budget(max_bytes: usize) {
622 let pool = decode_pool();
623 if let Ok(mut st) = pool.state.lock() {
624 st.max_in_flight_bytes = max_bytes.max(64 * 1024);
625 pool.cv.notify_all();
626 }
627 }
628
629 pub fn async_decode_worker_count() -> usize {
631 decode_pool()
632 .state
633 .lock()
634 .map(|st| st.worker_count)
635 .unwrap_or(0)
636 }
637
638 pub fn register_custom_image_decoder(decoder: CustomDecoderFn) {
640 let list = CUSTOM_DECODERS.get_or_init(|| RwLock::new(Vec::new()));
641 if let Ok(mut w) = list.write() {
642 w.push(decoder);
643 }
644 }
645
646 pub fn set_global_image_cache_budget(max_bytes: usize) {
648 let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(DEFAULT_IMAGE_CACHE_BUDGET)));
649 if let Ok(mut c) = cache.lock() {
650 c.set_max_bytes(max_bytes);
651 }
652 }
653
654 pub fn global_image_cache_stats() -> (usize, usize, usize) {
656 let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(DEFAULT_IMAGE_CACHE_BUDGET)));
657 cache
658 .lock()
659 .map(|c| (c.current_bytes(), c.max_bytes(), c.len()))
660 .unwrap_or((0, DEFAULT_IMAGE_CACHE_BUDGET, 0))
661 }
662
663 pub fn release_cached_image(id: ImageAssetId) -> bool {
665 let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(DEFAULT_IMAGE_CACHE_BUDGET)));
666 cache.lock().map(|mut c| c.remove(id)).unwrap_or(false)
667 }
668
669 pub fn clear_global_image_cache() {
671 let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(DEFAULT_IMAGE_CACHE_BUDGET)));
672 if let Ok(mut c) = cache.lock() {
673 c.clear();
674 }
675 }
676
677 pub fn unload_image(id: ImageAssetId) -> bool {
679 let removed_px = release_cached_image(id);
680 let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
681 let removed_st = states
682 .lock()
683 .map(|mut s| s.remove(&id).is_some())
684 .unwrap_or(false);
685 removed_px || removed_st
686 }
687
688 pub fn register_image_rgba(id: ImageAssetId, width: u32, height: u32, rgba: Vec<u8>) -> Option<u64> {
693 let expected_len = (width as usize).checked_mul(height as usize)?.checked_mul(4)?;
694 if width == 0 || height == 0 || rgba.len() != expected_len {
695 return None;
696 }
697 let rev = NEXT_IMAGE_REV.fetch_add(1, Ordering::Relaxed);
698 let px = DecodedPixels {
699 width,
700 height,
701 rgba: Arc::from(rgba.into_boxed_slice()),
702 revision: rev,
703 };
704 let meta = ImageMetadata {
705 width,
706 height,
707 revision: rev,
708 };
709 let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(DEFAULT_IMAGE_CACHE_BUDGET)));
710 if let Ok(mut c) = cache.lock() {
711 c.insert(id, px);
712 }
713 let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
714 if let Ok(mut s) = states.lock() {
715 s.insert(id, ImageLoadState::Ready(meta));
716 }
717 Some(rev)
718 }
719
720 pub fn load_image_bytes(id: ImageAssetId, bytes: &[u8]) -> Option<u64> {
722 let (w, h, rgba) = decode_image_bytes(bytes)?;
723 register_image_rgba(id, w, h, rgba)
724 }
725
726 pub fn load_image_bytes_async(
730 id: ImageAssetId,
731 bytes: Vec<u8>,
732 on_ready: Option<ReadyCallback>,
733 ) {
734 let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
735 if let Ok(mut s) = states.lock() {
736 s.insert(id, ImageLoadState::Loading);
737 }
738 let estimated_rgba_bytes = estimate_decoded_rgba_bytes(&bytes);
739 let pool = decode_pool();
740 let rejected = {
741 let Ok(mut st) = pool.state.lock() else {
742 return;
743 };
744 if st.queue.len() >= MAX_DECODE_QUEUE_LEN {
745 true
746 } else {
747 st.queue.push_back(DecodeJob {
748 id,
749 bytes,
750 estimated_rgba_bytes,
751 on_ready: on_ready.clone(),
752 });
753 pool.cv.notify_one();
754 false
755 }
756 };
757 if rejected {
758 if let Ok(mut s) = states.lock() {
759 if matches!(s.get(&id), Some(ImageLoadState::Loading)) {
760 s.insert(id, ImageLoadState::Failed);
761 }
762 }
763 if let Some(cb) = on_ready {
764 cb(id, false);
765 }
766 }
767 }
768
769 pub fn get_cached_image(id: ImageAssetId) -> Option<DecodedPixels> {
771 let cache = GLOBAL_IMAGE_CACHE.get_or_init(|| Mutex::new(LruImageCache::new(DEFAULT_IMAGE_CACHE_BUDGET)));
772 cache.lock().ok().and_then(|mut c| c.get(id))
773 }
774
775 pub fn image_load_state(id: ImageAssetId) -> Option<ImageLoadState> {
777 let states = GLOBAL_IMAGE_STATES.get_or_init(|| Mutex::new(HashMap::new()));
778 states.lock().ok().and_then(|s| s.get(&id).copied())
779 }
780
781 pub fn image_metadata(id: ImageAssetId) -> Option<ImageMetadata> {
783 match image_load_state(id) {
784 Some(ImageLoadState::Ready(meta)) => Some(meta),
785 _ => None,
786 }
787 }
788
789 pub fn image_revision(id: ImageAssetId) -> Option<u64> {
791 image_metadata(id).map(|m| m.revision)
792 }
793
794 pub fn decode_image_bytes(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
796 match detect_image_format(bytes) {
797 ImageFormat::Png => decode_png(bytes),
798 ImageFormat::Bmp => decode_bmp(bytes),
799 _ => {
800 if let Some(list) = CUSTOM_DECODERS.get() {
801 if let Ok(r) = list.read() {
802 for dec in r.iter() {
803 if let Some(res) = dec(bytes) {
804 return Some(res);
805 }
806 }
807 }
808 }
809 None
810 }
811 }
812 }
813
814 fn decode_bmp(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
819 if bytes.len() < 54 || &bytes[..2] != b"BM" {
820 return None;
821 }
822 let data_off = u32::from_le_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]) as usize;
823 let w = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);
824 let h_signed = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]);
825 let bpp = u16::from_le_bytes([bytes[28], bytes[29]]);
826 let comp = u32::from_le_bytes([bytes[30], bytes[31], bytes[32], bytes[33]]);
827 if w <= 0 || h_signed == 0 || (bpp != 24 && bpp != 32) || comp != 0 {
828 return None;
829 }
830 let width = w as u32;
831 let top_down = h_signed < 0;
832 let height = h_signed.unsigned_abs();
833 let bytes_per_px = (bpp / 8) as usize;
834 let row_stride = ((width as usize) * bytes_per_px + 3) & !3;
835 if data_off + row_stride * (height as usize) > bytes.len() {
836 return None;
837 }
838 let mut rgba = vec![0u8; (width as usize) * (height as usize) * 4];
839 for y in 0..(height as usize) {
840 let src_y = if top_down { y } else { (height as usize) - 1 - y };
841 let row = &bytes[data_off + src_y * row_stride..data_off + (src_y + 1) * row_stride];
842 for x in 0..(width as usize) {
843 let si = x * bytes_per_px;
844 let di = (y * (width as usize) + x) * 4;
845 rgba[di] = row[si + 2];
846 rgba[di + 1] = row[si + 1];
847 rgba[di + 2] = row[si];
848 rgba[di + 3] = if bytes_per_px == 4 { row[si + 3] } else { 255 };
849 }
850 }
851 Some((width, height, rgba))
852 }
853
854 struct BitReader<'a> {
859 data: &'a [u8],
860 pos: usize,
861 bit_buf: u32,
862 bit_cnt: u32,
863 }
864
865 impl<'a> BitReader<'a> {
866 fn new(data: &'a [u8]) -> Self {
867 Self {
868 data,
869 pos: 0,
870 bit_buf: 0,
871 bit_cnt: 0,
872 }
873 }
874
875 #[inline]
876 fn read_bits(&mut self, n: u32) -> Option<u32> {
877 while self.bit_cnt < n {
878 if self.pos >= self.data.len() {
879 return None;
880 }
881 self.bit_buf |= (self.data[self.pos] as u32) << self.bit_cnt;
882 self.pos += 1;
883 self.bit_cnt += 8;
884 }
885 let mask = if n == 32 { u32::MAX } else { (1u32 << n) - 1 };
886 let val = self.bit_buf & mask;
887 self.bit_buf >>= n;
888 self.bit_cnt -= n;
889 Some(val)
890 }
891
892 fn align_byte(&mut self) {
893 let drop_bits = self.bit_cnt & 7;
894 self.bit_buf >>= drop_bits;
895 self.bit_cnt -= drop_bits;
896 }
897
898 fn read_u16_le_aligned(&mut self) -> Option<u16> {
899 self.align_byte();
900 let lo = self.read_bits(8)? as u16;
901 let hi = self.read_bits(8)? as u16;
902 Some(lo | (hi << 8))
903 }
904 }
905
906 struct HuffTree {
907 counts: [u16; 16],
908 symbols: Vec<u16>,
909 }
910
911 impl HuffTree {
912 fn from_lengths(lengths: &[u8]) -> Option<Self> {
913 let mut counts = [0u16; 16];
914 for &len in lengths {
915 if len as usize >= 16 {
916 return None;
917 }
918 if len > 0 {
919 counts[len as usize] += 1;
920 }
921 }
922 let mut offsets = [0u16; 16];
923 let mut sum = 0u16;
924 for bits in 1..16 {
925 offsets[bits] = sum;
926 sum = sum.checked_add(counts[bits])?;
927 }
928 let mut symbols = vec![0u16; sum as usize];
929 for (sym, &len) in lengths.iter().enumerate() {
930 if len > 0 {
931 let off = offsets[len as usize] as usize;
932 symbols[off] = sym as u16;
933 offsets[len as usize] += 1;
934 }
935 }
936 Some(Self { counts, symbols })
937 }
938
939 fn decode(&self, br: &mut BitReader<'_>) -> Option<u16> {
940 let mut code = 0i32;
941 let mut first = 0i32;
942 let mut index = 0i32;
943 for len in 1..16 {
944 code |= br.read_bits(1)? as i32;
945 let cnt = self.counts[len] as i32;
946 if code - cnt < first {
947 return self.symbols.get((index + (code - first)) as usize).copied();
948 }
949 index += cnt;
950 first = (first + cnt) << 1;
951 code <<= 1;
952 }
953 None
954 }
955 }
956
957 fn inflate_zlib(zlib: &[u8]) -> Option<Vec<u8>> {
958 if zlib.len() < 6 {
959 return None;
960 }
961 let cmf = zlib[0];
962 let flg = zlib[1];
963 if (cmf & 0x0F) != 8 || (((cmf as u16) << 8 | flg as u16) % 31) != 0 {
964 return None;
965 }
966 let start = if (flg & 0x20) != 0 { 6 } else { 2 };
967 let mut br = BitReader::new(&zlib[start..]);
968 let mut out = Vec::new();
969
970 const LEN_BASE: [u16; 29] = [
971 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99,
972 115, 131, 163, 195, 227, 258,
973 ];
974 const LEN_EXTRA: [u8; 29] = [
975 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,
976 ];
977 const DIST_BASE: [u16; 30] = [
978 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025,
979 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
980 ];
981 const DIST_EXTRA: [u8; 30] = [
982 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,
983 12, 13, 13,
984 ];
985 const CL_ORDER: [usize; 19] = [
986 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
987 ];
988
989 loop {
990 let bfinal = br.read_bits(1)?;
991 let btype = br.read_bits(2)?;
992 match btype {
993 0 => {
994 let len = br.read_u16_le_aligned()?;
995 let nlen = br.read_u16_le_aligned()?;
996 if len != !nlen {
997 return None;
998 }
999 for _ in 0..len {
1000 out.push(br.read_bits(8)? as u8);
1001 }
1002 }
1003 1 | 2 => {
1004 let (lit_tree, dist_tree) = if btype == 1 {
1005 let mut ll = [0u8; 288];
1006 for l in &mut ll[0..144] {
1007 *l = 8;
1008 }
1009 for l in &mut ll[144..256] {
1010 *l = 9;
1011 }
1012 for l in &mut ll[256..280] {
1013 *l = 7;
1014 }
1015 for l in &mut ll[280..288] {
1016 *l = 8;
1017 }
1018 let dl = [5u8; 32];
1019 (HuffTree::from_lengths(&ll)?, HuffTree::from_lengths(&dl)?)
1020 } else {
1021 let hlit = br.read_bits(5)? as usize + 257;
1022 let hdist = br.read_bits(5)? as usize + 1;
1023 let hclen = br.read_bits(4)? as usize + 4;
1024 let mut cl_lens = [0u8; 19];
1025 for i in 0..hclen {
1026 cl_lens[CL_ORDER[i]] = br.read_bits(3)? as u8;
1027 }
1028 let cl_tree = HuffTree::from_lengths(&cl_lens)?;
1029 let mut lens = Vec::with_capacity(hlit + hdist);
1030 while lens.len() < hlit + hdist {
1031 let sym = cl_tree.decode(&mut br)?;
1032 match sym {
1033 0..=15 => lens.push(sym as u8),
1034 16 => {
1035 let prev = *lens.last()?;
1036 let rep = br.read_bits(2)? as usize + 3;
1037 for _ in 0..rep {
1038 lens.push(prev);
1039 }
1040 }
1041 17 => {
1042 let rep = br.read_bits(3)? as usize + 3;
1043 for _ in 0..rep {
1044 lens.push(0);
1045 }
1046 }
1047 18 => {
1048 let rep = br.read_bits(7)? as usize + 11;
1049 for _ in 0..rep {
1050 lens.push(0);
1051 }
1052 }
1053 _ => return None,
1054 }
1055 }
1056 if lens.len() < hlit + hdist {
1057 return None;
1058 }
1059 (
1060 HuffTree::from_lengths(&lens[..hlit])?,
1061 HuffTree::from_lengths(&lens[hlit..hlit + hdist])?,
1062 )
1063 };
1064
1065 loop {
1066 let sym = lit_tree.decode(&mut br)?;
1067 if sym < 256 {
1068 out.push(sym as u8);
1069 } else if sym == 256 {
1070 break;
1071 } else {
1072 let lidx = (sym as usize).checked_sub(257)?;
1073 if lidx >= 29 {
1074 return None;
1075 }
1076 let length = LEN_BASE[lidx] as usize
1077 + br.read_bits(LEN_EXTRA[lidx] as u32)? as usize;
1078 let dsym = dist_tree.decode(&mut br)? as usize;
1079 if dsym >= 30 {
1080 return None;
1081 }
1082 let dist = DIST_BASE[dsym] as usize
1083 + br.read_bits(DIST_EXTRA[dsym] as u32)? as usize;
1084 if dist == 0 || dist > out.len() {
1085 return None;
1086 }
1087 for _ in 0..length {
1088 let b = out[out.len() - dist];
1089 out.push(b);
1090 }
1091 }
1092 }
1093 }
1094 _ => return None,
1095 }
1096 if bfinal != 0 {
1097 break;
1098 }
1099 }
1100 Some(out)
1101 }
1102
1103 #[inline]
1104 fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
1105 let ai = a as i32;
1106 let bi = b as i32;
1107 let ci = c as i32;
1108 let p = ai + bi - ci;
1109 let pa = (p - ai).abs();
1110 let pb = (p - bi).abs();
1111 let pc = (p - ci).abs();
1112 if pa <= pb && pa <= pc {
1113 a
1114 } else if pb <= pc {
1115 b
1116 } else {
1117 c
1118 }
1119 }
1120
1121 fn decode_png(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
1122 if bytes.len() < 33 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" {
1123 return None;
1124 }
1125 let mut pos = 8usize;
1126 let mut width = 0u32;
1127 let mut height = 0u32;
1128 let mut bit_depth = 0u8;
1129 let mut color_type = 0u8;
1130 let mut interlace = 0u8;
1131 let mut palette: Vec<[u8; 3]> = Vec::new();
1132 let mut trns: Vec<u8> = Vec::new();
1133 let mut idat: Vec<u8> = Vec::new();
1134
1135 while pos + 12 <= bytes.len() {
1136 let len = u32::from_be_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
1137 let ctype = &bytes[pos + 4..pos + 8];
1138 let data_start = pos + 8;
1139 let data_end = data_start.checked_add(len)?;
1140 if data_end + 4 > bytes.len() {
1141 return None;
1142 }
1143 let chunk = &bytes[data_start..data_end];
1144 match ctype {
1145 b"IHDR" => {
1146 if chunk.len() < 13 {
1147 return None;
1148 }
1149 width = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
1150 height = u32::from_be_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
1151 bit_depth = chunk[8];
1152 color_type = chunk[9];
1153 interlace = chunk[12];
1154 }
1155 b"PLTE" => {
1156 for rgb in chunk.chunks_exact(3) {
1157 palette.push([rgb[0], rgb[1], rgb[2]]);
1158 }
1159 }
1160 b"tRNS" => {
1161 trns.extend_from_slice(chunk);
1162 }
1163 b"IDAT" => {
1164 idat.extend_from_slice(chunk);
1165 }
1166 b"IEND" => break,
1167 _ => {}
1168 }
1169 pos = data_end + 4;
1170 }
1171
1172 if width == 0 || height == 0 || bit_depth != 8 || interlace != 0 {
1173 return None;
1174 }
1175 let bpp = match color_type {
1176 0 => 1usize, 2 => 3usize, 3 => 1usize, 4 => 2usize, 6 => 4usize, _ => return None,
1182 };
1183 let raw = inflate_zlib(&idat)?;
1184 let row_bytes = (width as usize) * bpp;
1185 if raw.len() < (height as usize) * (row_bytes + 1) {
1186 return None;
1187 }
1188
1189 let mut prev_row = vec![0u8; row_bytes];
1190 let mut cur_row = vec![0u8; row_bytes];
1191 let mut rgba = vec![0u8; (width as usize) * (height as usize) * 4];
1192
1193 for y in 0..(height as usize) {
1194 let line = &raw[y * (row_bytes + 1)..(y + 1) * (row_bytes + 1)];
1195 let filter = line[0];
1196 let src = &line[1..];
1197 for i in 0..row_bytes {
1198 let left = if i >= bpp { cur_row[i - bpp] } else { 0 };
1199 let up = prev_row[i];
1200 let up_left = if i >= bpp { prev_row[i - bpp] } else { 0 };
1201 cur_row[i] = match filter {
1202 0 => src[i],
1203 1 => src[i].wrapping_add(left),
1204 2 => src[i].wrapping_add(up),
1205 3 => src[i].wrapping_add((((left as u16) + (up as u16)) >> 1) as u8),
1206 4 => src[i].wrapping_add(paeth_predictor(left, up, up_left)),
1207 _ => return None,
1208 };
1209 }
1210
1211 let dst_row = &mut rgba[y * (width as usize) * 4..(y + 1) * (width as usize) * 4];
1212 match color_type {
1213 0 => {
1214 for x in 0..(width as usize) {
1215 let g = cur_row[x];
1216 let d = x * 4;
1217 dst_row[d] = g;
1218 dst_row[d + 1] = g;
1219 dst_row[d + 2] = g;
1220 dst_row[d + 3] = 255;
1221 }
1222 }
1223 2 => {
1224 for x in 0..(width as usize) {
1225 let s = x * 3;
1226 let d = x * 4;
1227 dst_row[d] = cur_row[s];
1228 dst_row[d + 1] = cur_row[s + 1];
1229 dst_row[d + 2] = cur_row[s + 2];
1230 dst_row[d + 3] = 255;
1231 }
1232 }
1233 3 => {
1234 for x in 0..(width as usize) {
1235 let idx = cur_row[x] as usize;
1236 let [r, g, b] = palette.get(idx).copied().unwrap_or([0, 0, 0]);
1237 let a = trns.get(idx).copied().unwrap_or(255);
1238 let d = x * 4;
1239 dst_row[d] = r;
1240 dst_row[d + 1] = g;
1241 dst_row[d + 2] = b;
1242 dst_row[d + 3] = a;
1243 }
1244 }
1245 4 => {
1246 for x in 0..(width as usize) {
1247 let s = x * 2;
1248 let d = x * 4;
1249 let g = cur_row[s];
1250 dst_row[d] = g;
1251 dst_row[d + 1] = g;
1252 dst_row[d + 2] = g;
1253 dst_row[d + 3] = cur_row[s + 1];
1254 }
1255 }
1256 6 => {
1257 dst_row.copy_from_slice(&cur_row);
1258 }
1259 _ => return None,
1260 }
1261 core::mem::swap(&mut prev_row, &mut cur_row);
1262 }
1263
1264 Some((width, height, rgba))
1265 }
1266}
1267
1268pub use std_pipeline::{
1269 async_decode_worker_count, clear_global_image_cache, decode_image_bytes, detect_image_format,
1270 get_cached_image, global_image_cache_stats, image_load_state, image_metadata, image_revision,
1271 load_image_bytes, load_image_bytes_async, register_custom_image_decoder, register_image_rgba,
1272 release_cached_image, set_async_decode_in_flight_budget, set_global_image_cache_budget,
1273 unload_image, DecodedPixels, ImageFormat, ImageLoadState, ImageMetadata, LruImageCache,
1274};