1use alloc::string::String;
4use alloc::vec::Vec;
5use spin::Mutex;
6
7use super::cache::{read_cache, write_cache};
8
9pub(super) struct ImageLoadQueue {
14 pub pending: Vec<ImageFetchReq>,
16 pub results: Vec<(String, super::DecodedImage)>,
18 pub active_workers: usize,
26}
27
28#[derive(Clone)]
29pub(super) struct ImageFetchReq {
30 pub src_key: String, pub is_https: bool,
32 pub host: String,
33 pub path: String,
34 pub is_local: bool, pub owner: u64, pub group: u8,
39}
40
41pub(super) static IMAGE_QUEUE: Mutex<ImageLoadQueue> = Mutex::new(ImageLoadQueue {
42 pending: Vec::new(),
43 results: Vec::new(),
44 active_workers: 0,
45});
46
47const MAX_IMAGE_WORKERS: usize = 4;
52
53fn svg_target_size(data: &[u8]) -> (u32, u32) {
55 let (w, h) = crate::os_lib::svg::natural_size(data);
56 let cap = 512.0f32;
57 let scale = (cap / w.max(1.0)).min(cap / h.max(1.0)).clamp(0.01, 1.0);
58 let tw = (w * if w > cap || h > cap { scale } else { 1.0 }).max(1.0) as u32;
60 let th = (h * if w > cap || h > cap { scale } else { 1.0 }).max(1.0) as u32;
61 (tw.max(1), th.max(1))
62}
63
64#[inline]
68fn decode_kill_checkpoint(row: u32) {
69 if row & 31 == 0 {
70 crate::kernel::window_mgr::kill_checkpoint();
71 }
72}
73
74pub(super) fn decode_image(data: &[u8]) -> Option<super::DecodedImage> {
75 crate::kernel::window_mgr::kill_checkpoint();
76 crate::debug!("[GPU] TRACE: decode_image start. len={}", data.len());
77 {
79 let head_len = data.len().min(512);
80 if let Ok(head) = core::str::from_utf8(&data[..head_len]) {
81 let ht = head.trim_start();
82 if ht.starts_with("<svg")
83 || ht.starts_with("<?xml")
84 || ht.starts_with("<!--") && head.contains("<svg")
85 {
86 crate::debug!("[GPU] TRACE: decode_image SVG target size parsing...");
87 let (tw, th) = svg_target_size(data);
88 crate::debug!("[GPU] TRACE: decode_image SVG decoding...");
89 if let Some((w, h, rgba)) = crate::os_lib::svg::decode_svg_image(data, tw, th) {
90 crate::debug!("[GPU] TRACE: decode_image SVG success");
91 return Some(super::DecodedImage {
92 width: w,
93 height: h,
94 rgba,
95 });
96 }
97 crate::debug!("[GPU] TRACE: decode_image SVG failed");
98 return None;
99 }
100 }
101 }
102 if data.len() > 8 && &data[0..8] == b"\x89PNG\r\n\x1a\n" {
103 crate::debug!("[GPU] TRACE: decode_image trying PNG...");
104 let mut decoder = zune_png::PngDecoder::new(data);
105 if let Ok(pixels) = decoder.decode_raw() {
106 if let Some(info) = decoder.get_info() {
107 let width = info.width as u32;
108 let height = info.height as u32;
109 let bpp = pixels.len() / (width as usize * height as usize).max(1);
110 const MAX_DIM: u32 = 1024;
111 let (out_w, out_h) = if width > MAX_DIM || height > MAX_DIM {
112 if width * MAX_DIM > height * MAX_DIM {
113 (MAX_DIM, (height * MAX_DIM / width).max(1))
114 } else {
115 ((width * MAX_DIM / height).max(1), MAX_DIM)
116 }
117 } else {
118 (width, height)
119 };
120 let mut rgba = alloc::vec::Vec::with_capacity((out_w * out_h * 4) as usize);
121 for row in 0..out_h {
122 decode_kill_checkpoint(row);
123 let src_row = (row * height) / out_h;
124 for col in 0..out_w {
125 let src_col = (col * width) / out_w;
126 let i = (src_row * width + src_col) as usize;
127 let idx = i * bpp;
128 if idx + bpp <= pixels.len() {
129 let (r, g, b, a) = match bpp {
130 1 => (pixels[idx], pixels[idx], pixels[idx], 255),
131 2 => (pixels[idx], pixels[idx], pixels[idx], pixels[idx + 1]),
132 3 => (pixels[idx], pixels[idx + 1], pixels[idx + 2], 255),
133 4 => (
134 pixels[idx],
135 pixels[idx + 1],
136 pixels[idx + 2],
137 pixels[idx + 3],
138 ),
139 _ => (0, 0, 0, 255),
140 };
141 rgba.push(r);
142 rgba.push(g);
143 rgba.push(b);
144 rgba.push(a);
145 }
146 }
147 }
148 crate::debug!(
149 "[GPU] TRACE: decode_image PNG success {}x{} -> {}x{}",
150 width,
151 height,
152 out_w,
153 out_h
154 );
155 return Some(super::DecodedImage {
156 width: out_w,
157 height: out_h,
158 rgba,
159 });
160 }
161 }
162 crate::debug!("[GPU] TRACE: decode_image PNG failed");
163 } else if data.len() > 2 && data[0] == 0xFF && data[1] == 0xD8 {
164 crate::debug!("[GPU] TRACE: decode_image trying JPEG...");
165 const MAX_JPEG_DIM: u32 = 8192;
175 {
176 let mut i = 2usize;
177 let mut skip = false;
178 while i + 3 < data.len() {
179 if data[i] != 0xFF {
180 break;
181 }
182 let marker = data[i + 1];
183 let is_sof =
184 matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF);
185 if is_sof && i + 8 < data.len() {
186 let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
187 let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
188 if w > MAX_JPEG_DIM || h > MAX_JPEG_DIM {
189 crate::debug!(
190 "[GPU] TRACE: decode_image JPEG too large {}x{}, skipping (max {})",
191 w,
192 h,
193 MAX_JPEG_DIM
194 );
195 skip = true;
196 }
197 break;
198 }
199 if i + 3 >= data.len() {
200 break;
201 }
202 let seg_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
203 if seg_len < 2 {
204 break;
205 }
206 i += 2 + seg_len;
207 }
208 if skip {
209 return None;
210 }
211 }
212 crate::kernel::window_mgr::kill_checkpoint();
213 let mut decoder = zune_jpeg::JpegDecoder::new(data);
214 let t0 = crate::kernel::timer::get_ticks();
217 let decoded = decoder.decode();
218 crate::warn!(
219 "[IMGDIAG] jpeg decode ok={} bytes={} elapsed_ticks={}",
220 decoded.is_ok(),
221 data.len(),
222 crate::kernel::timer::get_ticks().wrapping_sub(t0)
223 );
224 if let Ok(pixels) = decoded {
225 if let Some(info) = decoder.info() {
226 let width = info.width as u32;
227 let height = info.height as u32;
228 let bpp = pixels.len() / (width as usize * height as usize).max(1);
229 const MAX_DIM: u32 = 1024;
230 let (out_w, out_h) = if width > MAX_DIM || height > MAX_DIM {
231 if width * MAX_DIM > height * MAX_DIM {
232 (MAX_DIM, (height * MAX_DIM / width).max(1))
233 } else {
234 ((width * MAX_DIM / height).max(1), MAX_DIM)
235 }
236 } else {
237 (width, height)
238 };
239 let mut rgba = alloc::vec::Vec::with_capacity((out_w * out_h * 4) as usize);
240 for row in 0..out_h {
241 decode_kill_checkpoint(row);
242 let src_row = (row * height) / out_h;
243 for col in 0..out_w {
244 let src_col = (col * width) / out_w;
245 let i = (src_row * width + src_col) as usize;
246 let idx = i * bpp;
247 if idx + bpp <= pixels.len() {
248 let (r, g, b) = match bpp {
249 1 => (pixels[idx], pixels[idx], pixels[idx]),
250 3 => (pixels[idx], pixels[idx + 1], pixels[idx + 2]),
251 _ => (0, 0, 0),
252 };
253 rgba.push(r);
254 rgba.push(g);
255 rgba.push(b);
256 rgba.push(255);
257 }
258 }
259 }
260 crate::debug!(
261 "[GPU] TRACE: decode_image JPEG success {}x{} -> {}x{}",
262 width,
263 height,
264 out_w,
265 out_h
266 );
267 return Some(super::DecodedImage {
268 width: out_w,
269 height: out_h,
270 rgba,
271 });
272 }
273 }
274 crate::debug!("[GPU] TRACE: decode_image JPEG failed");
275 } else if data.len() > 6 && &data[0..3] == b"GIF" {
276 crate::debug!("[GPU] TRACE: decode_image trying GIF...");
277 if let Some(img) = decode_gif(data) {
278 crate::debug!("[GPU] TRACE: decode_image GIF success");
279 return Some(img);
280 }
281 crate::debug!("[GPU] TRACE: decode_image GIF failed");
282 } else if data.len() > 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
283 crate::debug!("[GPU] TRACE: decode_image trying WEBP...");
284 if let Some((w, h, rgba)) = crate::os_lib::webp::decode_webp(data) {
285 crate::debug!("[GPU] TRACE: decode_image WEBP success");
286 return Some(super::DecodedImage {
287 width: w,
288 height: h,
289 rgba,
290 });
291 }
292 crate::debug!("[GPU] TRACE: decode_image WEBP failed");
293 } else if data.len() >= 54 && &data[0..2] == b"BM" {
294 crate::debug!("[GPU] TRACE: decode_image trying BMP...");
295 let off_bits = u32::from_le_bytes(data[10..14].try_into().unwrap_or([0; 4])) as usize;
296 let width = i32::from_le_bytes(data[18..22].try_into().unwrap_or([0; 4]));
297 let height = i32::from_le_bytes(data[22..26].try_into().unwrap_or([0; 4]));
298 let bit_count = u16::from_le_bytes(data[28..30].try_into().unwrap_or([0; 2]));
299 let compression = u32::from_le_bytes(data[30..34].try_into().unwrap_or([0; 4]));
300 if compression == 0 && (bit_count == 24 || bit_count == 32) {
301 let abs_h = height.unsigned_abs();
302 let bpp = (bit_count / 8) as usize;
303 let row_stride = (width.unsigned_abs() as usize * bpp).div_ceil(4) * 4;
304 let mut rgba =
305 alloc::vec::Vec::with_capacity((width.unsigned_abs() * abs_h * 4) as usize);
306 for row in 0..abs_h {
307 decode_kill_checkpoint(row);
308 let src_row = if height > 0 { abs_h - 1 - row } else { row };
309 let row_off = off_bits + (src_row as usize * row_stride);
310 for col in 0..width.unsigned_abs() {
311 let pix_off = row_off + (col as usize * bpp);
312 if pix_off + bpp <= data.len() {
313 let b = data[pix_off];
314 let g = data[pix_off + 1];
315 let r = data[pix_off + 2];
316 let a = if bpp == 4 { data[pix_off + 3] } else { 255 };
317 rgba.push(r);
318 rgba.push(g);
319 rgba.push(b);
320 rgba.push(a);
321 } else {
322 rgba.push(0);
323 rgba.push(0);
324 rgba.push(0);
325 rgba.push(255);
326 }
327 }
328 }
329 crate::debug!("[GPU] TRACE: decode_image BMP success");
330 return Some(super::DecodedImage {
331 width: width.unsigned_abs(),
332 height: abs_h,
333 rgba,
334 });
335 }
336 crate::debug!("[GPU] TRACE: decode_image BMP failed");
337 }
338 crate::debug!("[GPU] TRACE: decode_image unsupported/unknown");
339 None
340}
341
342fn decode_gif(data: &[u8]) -> Option<super::DecodedImage> {
346 let mut p = 6usize; if data.len() < 13 {
348 return None;
349 }
350
351 let screen_w = u16::from_le_bytes([data[p], data[p + 1]]) as u32;
352 let screen_h = u16::from_le_bytes([data[p + 2], data[p + 3]]) as u32;
353 let packed = data[6 + 4];
354 p = 13;
355
356 let gct_flag = (packed & 0x80) != 0;
358 let gct_size = 2usize << (packed & 0x07); let mut global_palette: Vec<[u8; 3]> = Vec::new();
360 if gct_flag {
361 for _ in 0..gct_size {
362 if p + 3 > data.len() {
363 return None;
364 }
365 global_palette.push([data[p], data[p + 1], data[p + 2]]);
366 p += 3;
367 }
368 }
369
370 let mut transparent_idx: Option<u8> = None;
371
372 while p < data.len() {
374 match data[p] {
375 0x21 => {
376 p += 1;
378 if p >= data.len() {
379 return None;
380 }
381 let label = data[p];
382 p += 1;
383 if label == 0xF9 {
384 if p < data.len() {
386 let blk_size = data[p] as usize; if p + 1 + blk_size <= data.len() && blk_size >= 4 {
388 let gce_packed = data[p + 1];
389 if gce_packed & 0x01 != 0 {
390 transparent_idx = Some(data[p + 4]);
391 }
392 }
393 }
394 }
395 p = skip_gif_subblocks(data, p)?;
397 }
398 0x2C => {
399 if p + 10 > data.len() {
401 return None;
402 }
403 let img_w = u16::from_le_bytes([data[p + 5], data[p + 6]]) as u32;
404 let img_h = u16::from_le_bytes([data[p + 7], data[p + 8]]) as u32;
405 let ipacked = data[p + 9];
406 let lct_flag = (ipacked & 0x80) != 0;
407 let interlace = (ipacked & 0x40) != 0;
408 let lct_size = 2usize << (ipacked & 0x07);
409 p += 10;
410
411 let palette = if lct_flag {
413 let mut lp: Vec<[u8; 3]> = Vec::new();
414 for _ in 0..lct_size {
415 if p + 3 > data.len() {
416 return None;
417 }
418 lp.push([data[p], data[p + 1], data[p + 2]]);
419 p += 3;
420 }
421 lp
422 } else {
423 global_palette.clone()
424 };
425 if palette.is_empty() {
426 return None;
427 }
428 if img_w == 0 || img_h == 0 || img_w > 4096 || img_h > 4096 {
429 return None;
430 }
431
432 if p >= data.len() {
434 return None;
435 }
436 let min_code_size = data[p];
437 p += 1;
438
439 let mut lzw_data: Vec<u8> = Vec::new();
441 loop {
442 if p >= data.len() {
443 return None;
444 }
445 let bs = data[p] as usize;
446 p += 1;
447 if bs == 0 {
448 break;
449 }
450 if p + bs > data.len() {
451 return None;
452 }
453 lzw_data.extend_from_slice(&data[p..p + bs]);
454 p += bs;
455 }
456
457 let indices = gif_lzw_decode(&lzw_data, min_code_size, (img_w * img_h) as usize)?;
458
459 let total = (img_w * img_h) as usize;
461 let mut rgba = alloc::vec![0u8; total * 4];
462 let row_order: Vec<u32> = if interlace {
463 gif_interlace_rows(img_h)
464 } else {
465 (0..img_h).collect()
466 };
467 let mut src = 0usize;
468 for &dst_row in row_order.iter() {
469 decode_kill_checkpoint(dst_row);
470 for col in 0..img_w {
471 if src >= indices.len() {
472 break;
473 }
474 let ci = indices[src];
475 src += 1;
476 let dst = ((dst_row * img_w + col) as usize) * 4;
477 if Some(ci) == transparent_idx {
478 rgba[dst + 3] = 0; } else {
480 let c = palette.get(ci as usize).copied().unwrap_or([0, 0, 0]);
481 rgba[dst] = c[0];
482 rgba[dst + 1] = c[1];
483 rgba[dst + 2] = c[2];
484 rgba[dst + 3] = 255;
485 }
486 }
487 }
488 let _ = (screen_w, screen_h);
489 return Some(super::DecodedImage {
490 width: img_w,
491 height: img_h,
492 rgba,
493 });
494 }
495 0x3B => break, _ => {
497 p += 1;
498 }
499 }
500 }
501 None
502}
503
504fn skip_gif_subblocks(data: &[u8], mut p: usize) -> Option<usize> {
506 loop {
507 if p >= data.len() {
508 return None;
509 }
510 let bs = data[p] as usize;
511 p += 1;
512 if bs == 0 {
513 return Some(p);
514 }
515 p += bs;
516 }
517}
518
519fn gif_interlace_rows(h: u32) -> Vec<u32> {
521 let mut rows = Vec::with_capacity(h as usize);
522 let mut y = 0;
523 while y < h {
524 rows.push(y);
525 y += 8;
526 }
527 y = 4;
528 while y < h {
529 rows.push(y);
530 y += 8;
531 }
532 y = 2;
533 while y < h {
534 rows.push(y);
535 y += 4;
536 }
537 y = 1;
538 while y < h {
539 rows.push(y);
540 y += 2;
541 }
542 rows
543}
544
545fn gif_lzw_decode(data: &[u8], min_code_size: u8, expected: usize) -> Option<Vec<u8>> {
547 let clear_code = 1u16 << min_code_size;
548 let end_code = clear_code + 1;
549 let mut code_size = min_code_size + 1;
550
551 let mut prefix: Vec<i32> = Vec::with_capacity(4096);
553 let mut suffix: Vec<u8> = Vec::with_capacity(4096);
554 let reset_dict = |prefix: &mut Vec<i32>, suffix: &mut Vec<u8>| {
555 prefix.clear();
556 suffix.clear();
557 for i in 0..clear_code {
558 prefix.push(-1);
559 suffix.push(i as u8);
560 }
561 prefix.push(-1);
562 suffix.push(0); prefix.push(-1);
564 suffix.push(0); };
566 reset_dict(&mut prefix, &mut suffix);
567
568 let mut out: Vec<u8> = Vec::with_capacity(expected);
569 let mut bit_pos = 0usize;
570 let total_bits = data.len() * 8;
571 let mut prev_code: i32 = -1;
572 let mut stack: Vec<u8> = Vec::with_capacity(4096);
573
574 let read_code = |bit_pos: &mut usize, code_size: u8| -> Option<u16> {
575 if *bit_pos + code_size as usize > total_bits {
576 return None;
577 }
578 let mut val = 0u32;
579 for i in 0..code_size as usize {
580 let byte = data[(*bit_pos + i) >> 3];
581 let bit = (byte >> ((*bit_pos + i) & 7)) & 1;
582 val |= (bit as u32) << i;
583 }
584 *bit_pos += code_size as usize;
585 Some(val as u16)
586 };
587
588 let mut lzw_steps = 0usize;
589 while let Some(code) = read_code(&mut bit_pos, code_size) {
590 lzw_steps = lzw_steps.wrapping_add(1);
591 if lzw_steps & 31 == 0 {
592 crate::kernel::window_mgr::kill_checkpoint();
593 }
594 if code == clear_code {
595 reset_dict(&mut prefix, &mut suffix);
596 code_size = min_code_size + 1;
597 prev_code = -1;
598 continue;
599 }
600 if code == end_code {
601 break;
602 }
603
604 stack.clear();
606 let mut cur = code as i32;
607 let first_byte;
608 if (cur as usize) < suffix.len() {
609 while cur >= 0 && (cur as usize) < suffix.len() {
611 stack.push(suffix[cur as usize]);
612 cur = prefix[cur as usize];
613 }
614 first_byte = *stack.last()?;
615 } else {
616 if prev_code < 0 {
618 return None;
619 }
620 let mut c2 = prev_code;
621 while c2 >= 0 && (c2 as usize) < suffix.len() {
622 stack.push(suffix[c2 as usize]);
623 c2 = prefix[c2 as usize];
624 }
625 first_byte = *stack.last()?;
626 stack.insert(0, first_byte); }
628
629 for &b in stack.iter().rev() {
631 out.push(b);
632 }
633
634 if prev_code >= 0 && suffix.len() < 4096 {
636 prefix.push(prev_code);
637 suffix.push(first_byte);
638 if suffix.len() == (1usize << code_size) && code_size < 12 {
640 code_size += 1;
641 }
642 }
643 prev_code = code as i32;
644
645 if out.len() >= expected {
646 break;
647 }
648 }
649
650 Some(out)
651}
652
653pub(super) fn pump() {
656 let Some(mut q) = IMAGE_QUEUE.try_lock() else {
660 return;
661 };
662 let dead = super::fetch_limit::take_image_deaths();
664 if dead > 0 {
665 crate::warn!("[IMG] パニックで死んだワーカー {} 本を回収", dead);
666 q.active_workers = q.active_workers.saturating_sub(dead);
667 store_worker_count(q.active_workers);
668 }
669 if q.pending.is_empty() {
670 return;
671 }
672 let higher = super::font_queue::pending_higher_than(
674 super::fetch_limit::Kind::Image.priority(),
675 );
676 if q.active_workers < MAX_IMAGE_WORKERS
677 && super::fetch_limit::may_spawn_lower(
678 super::fetch_limit::main_load_in_flight(),
679 super::fetch_limit::active(),
680 q.pending.len(),
681 higher,
682 )
683 && super::fetch_limit::try_acquire(q.pending.len())
684 {
685 q.active_workers += 1;
686 store_worker_count(q.active_workers);
687 let pid = crate::kernel::scheduler::spawn_shared(
692 image_loader_thread,
693 crate::kernel::scheduler::Priority::Low,
694 "img_load",
695 );
696 if pid == 0 {
697 q.active_workers = q.active_workers.saturating_sub(1);
698 store_worker_count(q.active_workers);
699 super::fetch_limit::release();
700 }
701 }
702}
703
704pub(super) fn forget_requests_of_group(g: u8) -> usize {
706 let Some(mut q) = IMAGE_QUEUE.try_lock() else { return 0 };
707 let before = q.pending.len();
708 q.pending.retain(|r| r.group != g);
709 IMG_PENDING.store(q.pending.len(), core::sync::atomic::Ordering::Release);
710 before - q.pending.len()
711}
712
713pub(super) fn forget_requests_of_owner(owner: u64) -> usize {
716 if owner == 0 {
717 return 0;
718 }
719 let Some(mut q) = IMAGE_QUEUE.try_lock() else { return 0 };
720 let before = q.pending.len();
721 q.pending.retain(|r| r.owner != owner);
722 IMG_PENDING.store(q.pending.len(), core::sync::atomic::Ordering::Release);
723 before - q.pending.len()
724}
725
726fn image_loader_thread() {
727 let my_pid = crate::kernel::scheduler::get_current_process_id().unwrap_or(0);
729 super::fetch_limit::claim(my_pid, super::fetch_limit::KIND_IMAGE);
730 loop {
731 let req = {
734 let mut q = IMAGE_QUEUE.lock();
735 q.pending.retain(|r| !crate::kernel::window_mgr::group_stopped(r.group));
737 let popped = q.pending.pop();
738 IMG_PENDING.store(q.pending.len(), core::sync::atomic::Ordering::Release);
739 match popped {
740 Some(r) => r,
741 None => {
742 q.active_workers = q.active_workers.saturating_sub(1);
743 store_worker_count(q.active_workers);
744 drop(q);
745 super::fetch_limit::unclaim(my_pid);
746 super::fetch_limit::release();
747 crate::kernel::scheduler::exit();
752 }
753 }
754 };
755
756 crate::kernel::window_mgr::kill_checkpoint();
757 let _loan = crate::kernel::scheduler::borrow_mem_group(req.group);
760 let raw: Option<Vec<u8>> = if req.is_local {
783 let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
788 let fs = crate::kernel::fs::get_fs();
789 match fs.read_file_checked(&req.path) {
790 Ok(v) => v.map(|(_m, d)| d),
791 Err(e) => {
792 crate::warn!("[IMAGE] ローカル画像の読み込みに失敗 path={} err={}", req.path, e);
793 None
794 }
795 }
796 } else {
797 if let Some(cached) = read_cache(&req.host, &req.path) {
798 Some(cached)
800 } else {
801 let stack = crate::kernel::net_stack::TcpIpStack::new();
802 match stack.web_get_binary_complete(req.is_https, &req.host, &req.path) {
805 Ok(d) => {
806 write_cache(&req.host, &req.path, &d);
807 Some(d)
808 }
809 Err(e) => {
810 crate::warn!(
811 "IMAGE_LOADER: fetch failed for {}{}: {}",
812 req.host,
813 req.path,
814 e.message
815 );
816 None
817 }
818 }
819 }
820 };
821
822 if let Some(bytes) = raw {
823 let _t_dec = super::perf::start();
830 let decoded_result = decode_image(&bytes);
831 super::perf::add(super::perf::Slot::ImageDecode, _t_dec);
832 match decoded_result {
834 Some(decoded) => {
835 if crate::kernel::window_mgr::group_stopped(req.group) {
850 continue;
851 }
852 let mut q = IMAGE_QUEUE.lock();
853 q.results.push((req.src_key, decoded));
854 store_results_len(q.results.len());
855 }
856 None => {
857 let fmt =
859 if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP"
860 {
861 "WebP (unsupported)"
862 } else if bytes.len() >= 6
863 && (&bytes[0..6] == b"GIF89a" || &bytes[0..6] == b"GIF87a")
864 {
865 "GIF (unsupported)"
866 } else if bytes.len() >= 5 && &bytes[0..5] == b"<?xml"
867 || (bytes.len() >= 4 && &bytes[0..4] == b"<svg")
868 {
869 "SVG (unsupported)"
870 } else {
871 "unknown/corrupt"
872 };
873 crate::warn!(
874 "IMAGE_LOADER: decode failed for {} ({} bytes, format={})",
875 req.src_key,
876 bytes.len(),
877 fmt
878 );
879 }
880 }
881 }
882 }
883}
884
885pub fn image_results_ready() -> bool {
890 IMG_RESULTS.load(core::sync::atomic::Ordering::Acquire) > 0
891}
892
893static IMG_RESULTS: core::sync::atomic::AtomicUsize =
909 core::sync::atomic::AtomicUsize::new(0);
910
911pub(super) fn store_results_len(n: usize) {
913 IMG_RESULTS.store(n, core::sync::atomic::Ordering::Release);
914}
915
916static IMG_PENDING: core::sync::atomic::AtomicUsize =
929 core::sync::atomic::AtomicUsize::new(0);
930
931pub(super) fn pending_count() -> usize {
932 IMG_PENDING.load(core::sync::atomic::Ordering::Acquire)
933}
934
935static IMG_WORKERS: core::sync::atomic::AtomicUsize =
937 core::sync::atomic::AtomicUsize::new(0);
938
939pub(super) fn worker_count() -> usize {
940 IMG_WORKERS.load(core::sync::atomic::Ordering::Acquire)
941}
942
943pub(super) fn store_worker_count(n: usize) {
945 IMG_WORKERS.store(n, core::sync::atomic::Ordering::Release);
946}
947
948pub(super) fn enqueue_image(req: ImageFetchReq) {
949 let mut q = IMAGE_QUEUE.lock();
950 if let Some(r) = q.pending.iter_mut().find(|r| r.src_key == req.src_key) {
954 if r.owner != req.owner {
955 r.owner = 0;
956 }
957 return;
958 }
959 q.pending.push(req);
960 IMG_PENDING.store(q.pending.len(), core::sync::atomic::Ordering::Release);
961 if q.active_workers < MAX_IMAGE_WORKERS
964 && super::fetch_limit::try_acquire(q.pending.len())
965 {
966 q.active_workers += 1;
967 store_worker_count(q.active_workers);
968 let pid = crate::kernel::scheduler::spawn_shared(
973 image_loader_thread,
974 crate::kernel::scheduler::Priority::Normal,
975 "img_load",
976 );
977 if pid == 0 {
978 q.active_workers = q.active_workers.saturating_sub(1);
979 store_worker_count(q.active_workers);
980 super::fetch_limit::release();
981 }
982 }
983}
984
985static SHARED_IMAGES: spin::Mutex<
1003 alloc::collections::BTreeMap<alloc::string::String, (alloc::sync::Arc<super::DecodedImage>, u8)>,
1004> = spin::Mutex::new(alloc::collections::BTreeMap::new());
1005
1006pub fn share_image(key: &str, img: alloc::sync::Arc<super::DecodedImage>) {
1008 let g = crate::kernel::window_mgr::current_group();
1009 SHARED_IMAGES.lock().insert(alloc::string::String::from(key), (img, g));
1010}
1011
1012pub fn shared_image(key: &str) -> Option<alloc::sync::Arc<super::DecodedImage>> {
1014 SHARED_IMAGES.lock().get(key).map(|(img, _)| img.clone())
1015}
1016
1017pub fn forget_shared_images_of_group(g: u8) -> Option<usize> {
1020 let mut m = SHARED_IMAGES.try_lock()?;
1021 let before = m.len();
1022 m.retain(|_, (_, owner)| *owner != g);
1023 Some(before - m.len())
1024}
1025
1026pub fn clear_shared_images() {
1028 SHARED_IMAGES.lock().clear();
1029}