net/
image_cache.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::OnceCell;
6use std::cmp::min;
7use std::collections::hash_map::Entry::{Occupied, Vacant};
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::sync::Arc;
10use std::{mem, thread};
11
12use imsz::imsz_from_reader;
13use log::{debug, warn};
14use malloc_size_of::{MallocConditionalSizeOf, MallocSizeOf as MallocSizeOfTrait, MallocSizeOfOps};
15use malloc_size_of_derive::MallocSizeOf;
16use mime::Mime;
17use net_traits::image_cache::{
18    Image, ImageCache, ImageCacheFactory, ImageCacheResponseCallback, ImageCacheResponseMessage,
19    ImageCacheResult, ImageLoadListener, ImageOrMetadataAvailable, ImageResponse, PendingImageId,
20    RasterizationCompleteResponse, VectorImage,
21};
22use net_traits::request::CorsSettings;
23use net_traits::{FetchMetadata, FetchResponseMsg, FilteredMetadata, NetworkError};
24use paint_api::{CrossProcessPaintApi, ImageUpdate, SerializableImageData};
25use parking_lot::Mutex;
26use pixels::{CorsStatus, ImageFrame, ImageMetadata, PixelFormat, RasterImage, load_from_memory};
27use profile_traits::mem::{Report, ReportKind};
28use profile_traits::path;
29use resvg::tiny_skia;
30use resvg::usvg::{self, fontdb};
31use rustc_hash::FxHashMap;
32use servo_base::id::{PipelineId, WebViewId};
33use servo_base::threadpool::ThreadPool;
34use servo_config::pref;
35use servo_url::{ImmutableOrigin, ServoUrl};
36use webrender_api::ImageKey as WebRenderImageKey;
37use webrender_api::units::DeviceIntSize;
38
39// We bake in rippy.png as a fallback, in case the embedder does not provide a broken
40// image icon resource. This version is 229 bytes, so don't exchange it against
41// something of higher resolution.
42const FALLBACK_RIPPY: &[u8] = include_bytes!("resources/rippy.png");
43
44/// The current SVG stack relies on `resvg` to provide the natural dimensions of
45/// the SVG, which it automatically infers from the width/height/viewBox properties
46/// of the SVG. Since these can be arbitrarily large, this can cause us to allocate
47/// a pixmap with very large dimensions leading to the process being killed due to
48/// memory exhaustion. For example, the `/css/css-transforms/perspective-svg-001.html`
49/// test uses very large values for viewBox. Hence, we just clamp the maximum
50/// width/height of the pixmap allocated for rasterization.
51const MAX_SVG_PIXMAP_DIMENSION: u32 = 5000;
52
53//
54// TODO(gw): Remaining work on image cache:
55//     * Make use of the prefetch support in various parts of the code.
56//     * Profile time in GetImageIfAvailable - might be worth caching these
57//       results per paint / layout.
58//
59// MAYBE(Yoric):
60//     * For faster lookups, it might be useful to store the LoadKey in the
61//       DOM once we have performed a first load.
62
63// ======================================================================
64// Helper functions.
65// ======================================================================
66
67fn parse_svg_document_in_memory(
68    bytes: &[u8],
69    fontdb: Arc<fontdb::Database>,
70) -> Result<usvg::Tree, &'static str> {
71    let image_string_href_resolver = Box::new(move |_: &str, _: &usvg::Options| {
72        // Do not try to load `href` in <image> as local file path.
73        None
74    });
75
76    let opt = usvg::Options {
77        image_href_resolver: usvg::ImageHrefResolver {
78            resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
79            resolve_string: image_string_href_resolver,
80        },
81        fontdb,
82        ..usvg::Options::default()
83    };
84
85    usvg::Tree::from_data(bytes, &opt)
86        .inspect_err(|error| {
87            warn!("Error when parsing SVG data: {error}");
88        })
89        .map_err(|_| "Not a valid SVG document")
90}
91
92fn decode_bytes_sync(
93    key: LoadKey,
94    bytes: &[u8],
95    cors: CorsStatus,
96    content_type: Option<Mime>,
97    fontdb: Arc<fontdb::Database>,
98) -> DecoderMsg {
99    let is_svg_document = content_type.is_some_and(|content_type| {
100        (
101            content_type.type_(),
102            content_type.subtype(),
103            content_type.suffix(),
104        ) == (mime::IMAGE, mime::SVG, Some(mime::XML))
105    });
106
107    let image = if is_svg_document {
108        parse_svg_document_in_memory(bytes, fontdb)
109            .ok()
110            .map(|svg_tree| {
111                DecodedImage::Vector(VectorImageData {
112                    svg_tree: Arc::new(svg_tree),
113                    cors_status: cors,
114                })
115            })
116    } else {
117        load_from_memory(bytes, cors).map(DecodedImage::Raster)
118    };
119
120    DecoderMsg { key, image }
121}
122
123fn set_webrender_image_key(
124    paint_api: &CrossProcessPaintApi,
125    image: &mut RasterImage,
126    image_key: WebRenderImageKey,
127) {
128    if image.id.is_some() {
129        return;
130    }
131
132    let (descriptor, ipc_shared_memory) = image.webrender_image_descriptor_and_data_for_frame(0);
133    let data = SerializableImageData::Raw(ipc_shared_memory);
134
135    paint_api.add_image(image_key, descriptor, data, image.should_animate());
136    image.id = Some(image_key);
137}
138
139// ======================================================================
140// Aux structs and enums.
141// ======================================================================
142
143/// <https://html.spec.whatwg.org/multipage/#list-of-available-images>
144type ImageKey = (ServoUrl, ImmutableOrigin, Option<CorsSettings>);
145
146// Represents all the currently pending loads/decodings. For
147// performance reasons, loads are indexed by a dedicated load key.
148#[derive(MallocSizeOf)]
149struct AllPendingLoads {
150    // The loads, indexed by a load key. Used during most operations,
151    // for performance reasons.
152    loads: FxHashMap<LoadKey, PendingLoad>,
153
154    // Get a load key from its url and requesting origin. Used ony when starting and
155    // finishing a load or when adding a new listener.
156    url_to_load_key: HashMap<ImageKey, LoadKey>,
157
158    // A counter used to generate instances of LoadKey
159    keygen: LoadKeyGenerator,
160}
161
162impl AllPendingLoads {
163    fn new() -> AllPendingLoads {
164        AllPendingLoads {
165            loads: FxHashMap::default(),
166            url_to_load_key: HashMap::default(),
167            keygen: LoadKeyGenerator::new(),
168        }
169    }
170
171    // get a PendingLoad from its LoadKey.
172    fn get_by_key_mut(&mut self, key: &LoadKey) -> Option<&mut PendingLoad> {
173        self.loads.get_mut(key)
174    }
175
176    fn remove(&mut self, key: &LoadKey) -> Option<PendingLoad> {
177        self.loads.remove(key).inspect(|pending_load| {
178            self.url_to_load_key
179                .remove(&(
180                    pending_load.url.clone(),
181                    pending_load.load_origin.clone(),
182                    pending_load.cors_setting,
183                ))
184                .unwrap();
185        })
186    }
187
188    fn get_cached(
189        &mut self,
190        url: ServoUrl,
191        origin: ImmutableOrigin,
192        cors_status: Option<CorsSettings>,
193    ) -> CacheResult<'_> {
194        match self
195            .url_to_load_key
196            .entry((url.clone(), origin.clone(), cors_status))
197        {
198            Occupied(url_entry) => {
199                let load_key = url_entry.get();
200                CacheResult::Hit(*load_key, self.loads.get_mut(load_key).unwrap())
201            },
202            Vacant(url_entry) => {
203                let load_key = self.keygen.next();
204                url_entry.insert(load_key);
205
206                let pending_load = PendingLoad::new(url, origin, cors_status);
207                match self.loads.entry(load_key) {
208                    Occupied(_) => unreachable!(),
209                    Vacant(load_entry) => {
210                        let mut_load = load_entry.insert(pending_load);
211                        CacheResult::Miss(Some((load_key, mut_load)))
212                    },
213                }
214            },
215        }
216    }
217}
218
219/// Result of accessing a cache.
220enum CacheResult<'a> {
221    /// The value was in the cache.
222    Hit(LoadKey, &'a mut PendingLoad),
223    /// The value was not in the cache and needed to be regenerated.
224    Miss(Option<(LoadKey, &'a mut PendingLoad)>),
225}
226
227/// Represents an image that has completed loading.
228/// Images that fail to load (due to network or decode
229/// failure) are still stored here, so that they aren't
230/// fetched again.
231#[derive(MallocSizeOf)]
232struct CompletedLoad {
233    image_response: ImageResponse,
234    id: PendingImageId,
235}
236
237impl CompletedLoad {
238    fn new(image_response: ImageResponse, id: PendingImageId) -> CompletedLoad {
239        CompletedLoad { image_response, id }
240    }
241}
242
243#[derive(Clone, MallocSizeOf)]
244struct VectorImageData {
245    #[conditional_malloc_size_of]
246    svg_tree: Arc<usvg::Tree>,
247    cors_status: CorsStatus,
248}
249
250impl std::fmt::Debug for VectorImageData {
251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252        f.debug_struct("VectorImageData").finish()
253    }
254}
255
256enum DecodedImage {
257    Raster(RasterImage),
258    Vector(VectorImageData),
259}
260
261/// Message that the decoder worker threads send to the image cache.
262struct DecoderMsg {
263    key: LoadKey,
264    image: Option<DecodedImage>,
265}
266
267#[derive(MallocSizeOf)]
268enum ImageBytes {
269    InProgress(Vec<u8>),
270    Complete(#[conditional_malloc_size_of] Arc<Vec<u8>>),
271}
272
273impl ImageBytes {
274    fn extend_from_slice(&mut self, data: &[u8]) {
275        match *self {
276            ImageBytes::InProgress(ref mut bytes) => bytes.extend_from_slice(data),
277            ImageBytes::Complete(_) => panic!("attempted modification of complete image bytes"),
278        }
279    }
280
281    fn mark_complete(&mut self) -> Arc<Vec<u8>> {
282        let bytes = {
283            let own_bytes = match *self {
284                ImageBytes::InProgress(ref mut bytes) => bytes,
285                ImageBytes::Complete(_) => panic!("attempted modification of complete image bytes"),
286            };
287            mem::take(own_bytes)
288        };
289        let bytes = Arc::new(bytes);
290        *self = ImageBytes::Complete(bytes.clone());
291        bytes
292    }
293
294    fn as_slice(&self) -> &[u8] {
295        match *self {
296            ImageBytes::InProgress(ref bytes) => bytes,
297            ImageBytes::Complete(ref bytes) => bytes,
298        }
299    }
300}
301
302// A key used to communicate during loading.
303type LoadKey = PendingImageId;
304
305#[derive(MallocSizeOf)]
306struct LoadKeyGenerator {
307    counter: u64,
308}
309
310impl LoadKeyGenerator {
311    fn new() -> LoadKeyGenerator {
312        LoadKeyGenerator { counter: 0 }
313    }
314    fn next(&mut self) -> PendingImageId {
315        self.counter += 1;
316        PendingImageId(self.counter)
317    }
318}
319
320#[derive(Debug)]
321enum LoadResult {
322    LoadedRasterImage(RasterImage),
323    LoadedVectorImage(VectorImageData),
324    FailedToLoadOrDecode,
325}
326
327/// Represents an image that is either being loaded
328/// by the resource thread, or decoded by a worker thread.
329#[derive(MallocSizeOf)]
330struct PendingLoad {
331    /// The bytes loaded so far. Reset to an empty vector once loading
332    /// is complete and the buffer has been transmitted to the decoder.
333    bytes: ImageBytes,
334
335    /// Image metadata, if available.
336    metadata: Option<ImageMetadata>,
337
338    /// Once loading is complete, the result of the operation.
339    result: Option<Result<(), NetworkError>>,
340
341    /// The listeners that are waiting for this response to complete.
342    listeners: Vec<ImageLoadListener>,
343
344    /// The url being loaded. Do not forget that this may be several Mb
345    /// if we are loading a data: url.
346    url: ServoUrl,
347
348    /// The origin that requested this load.
349    load_origin: ImmutableOrigin,
350
351    /// The CORS attribute setting for the requesting
352    cors_setting: Option<CorsSettings>,
353
354    /// The CORS status of this image response.
355    cors_status: CorsStatus,
356
357    /// The URL of the final response that contains a body.
358    final_url: Option<ServoUrl>,
359
360    /// The MIME type from the `Content-type` header of the HTTP response, if any.
361    content_type: Option<Mime>,
362}
363
364impl PendingLoad {
365    fn new(
366        url: ServoUrl,
367        load_origin: ImmutableOrigin,
368        cors_setting: Option<CorsSettings>,
369    ) -> PendingLoad {
370        PendingLoad {
371            bytes: ImageBytes::InProgress(vec![]),
372            metadata: None,
373            result: None,
374            listeners: vec![],
375            url,
376            load_origin,
377            final_url: None,
378            cors_setting,
379            cors_status: CorsStatus::Unsafe,
380            content_type: None,
381        }
382    }
383
384    fn add_listener(&mut self, listener: ImageLoadListener) {
385        self.listeners.push(listener);
386    }
387}
388
389#[derive(Default, MallocSizeOf)]
390struct RasterizationTask {
391    #[ignore_malloc_size_of = "Fn is difficult to measure"]
392    listeners: Vec<(PipelineId, ImageCacheResponseCallback)>,
393    result: Option<RasterImage>,
394}
395
396/// Used for storing images that do not have a `WebRenderImageKey` yet.
397#[derive(Debug, MallocSizeOf)]
398enum PendingKey {
399    RasterImage((LoadKey, RasterImage)),
400    Svg((LoadKey, RasterImage, DeviceIntSize)),
401}
402
403/// The state of the `WebRenderImageKey`` cache
404#[derive(Debug, MallocSizeOf)]
405enum KeyCacheState {
406    /// We already requested a batch of keys.
407    PendingBatch,
408    /// We have some keys in the cache.
409    Ready(Vec<WebRenderImageKey>),
410}
411
412impl KeyCacheState {
413    fn size(&self) -> usize {
414        match self {
415            KeyCacheState::PendingBatch => 0,
416            KeyCacheState::Ready(items) => items.len(),
417        }
418    }
419}
420
421/// As getting new keys takes a round trip over the constellation, we keep a small cache of them.
422/// Additionally, this cache will store image resources that do not have a key yet because those
423/// are needed to complete the load.
424#[derive(MallocSizeOf)]
425struct KeyCache {
426    /// A cache of `WebRenderImageKey`.
427    cache: KeyCacheState,
428    /// These images are loaded but have no key assigned to yet.
429    images_pending_keys: VecDeque<PendingKey>,
430    /// A set of `LoadKey` and image size pairs which have been evicted
431    /// but are either being rasterized or are in images_pending_key
432    evicted_images: HashSet<(LoadKey, DeviceIntSize)>,
433}
434
435impl KeyCache {
436    fn new() -> Self {
437        KeyCache {
438            cache: KeyCacheState::Ready(Vec::new()),
439            images_pending_keys: VecDeque::new(),
440            evicted_images: HashSet::new(),
441        }
442    }
443}
444
445/// ## Image cache implementation.
446#[derive(MallocSizeOf)]
447struct ImageCacheStore {
448    /// Images that are loading over network, or decoding.
449    pending_loads: AllPendingLoads,
450
451    /// Images that have finished loading (successful or not)
452    completed_loads: HashMap<ImageKey, CompletedLoad>,
453
454    /// Vector (e.g. SVG) images that have been sucessfully loaded and parsed
455    /// but are yet to be rasterized. Since the same SVG data can be used for
456    /// rasterizing at different sizes, we use this hasmap to share the data.
457    vector_images: FxHashMap<PendingImageId, VectorImageData>,
458
459    /// Vector images for which rasterization at a particular size has started
460    /// or completed. If completed, the `result` member of `RasterizationTask`
461    /// contains the rasterized image.
462    rasterized_vector_images: FxHashMap<(PendingImageId, DeviceIntSize), RasterizationTask>,
463
464    /// The [`RasterImage`] used for the broken image icon, initialized lazily, only when necessary.
465    #[conditional_malloc_size_of]
466    broken_image_icon_image: OnceCell<Option<Arc<RasterImage>>>,
467
468    /// Cross-process `Paint` API instance.
469    paint_api: CrossProcessPaintApi,
470
471    /// The [`WebView`] of the `Webview` associated with this [`ImageCache`].
472    webview_id: WebViewId,
473
474    /// The [`PipelineId`] of the `Pipeline` associated with this [`ImageCache`].
475    pipeline_id: PipelineId,
476
477    /// Main struct to handle the cache of `WebRenderImageKey` and
478    /// images that do not have a key yet.
479    key_cache: KeyCache,
480}
481
482impl ImageCacheStore {
483    /// Finishes loading the image by setting the WebRenderImageKey and calling `compete_load` or `complete_load_svg`.
484    fn set_key_and_finish_load(&mut self, pending_image: PendingKey, image_key: WebRenderImageKey) {
485        match pending_image {
486            PendingKey::RasterImage((pending_id, mut raster_image)) => {
487                set_webrender_image_key(&self.paint_api, &mut raster_image, image_key);
488                self.complete_load(pending_id, LoadResult::LoadedRasterImage(raster_image));
489            },
490            PendingKey::Svg((pending_id, mut raster_image, requested_size)) => {
491                set_webrender_image_key(&self.paint_api, &mut raster_image, image_key);
492                self.complete_load_svg(raster_image, pending_id, requested_size);
493            },
494        }
495    }
496
497    /// If a key is available the image will be immediately loaded, otherwise it will load then the next batch of
498    /// keys is received. Only call this if the image does not have a `LoadKey` yet.
499    fn load_image_with_keycache(&mut self, pending_image: PendingKey) {
500        if let PendingKey::Svg((pending_id, ref _raster_image, requested_size)) = pending_image {
501            if self
502                .key_cache
503                .evicted_images
504                .remove(&(pending_id, requested_size))
505            {
506                return;
507            }
508        };
509        match self.key_cache.cache {
510            KeyCacheState::PendingBatch => {
511                self.key_cache.images_pending_keys.push_back(pending_image);
512            },
513            KeyCacheState::Ready(ref mut cache) => match cache.pop() {
514                Some(image_key) => {
515                    self.set_key_and_finish_load(pending_image, image_key);
516                },
517                None => {
518                    self.key_cache.images_pending_keys.push_back(pending_image);
519                    self.fetch_more_image_keys();
520                },
521            },
522        }
523    }
524
525    fn evict_image_from_keycache(
526        &mut self,
527        image_id: &PendingImageId,
528        requested_size: &DeviceIntSize,
529    ) {
530        self.key_cache
531            .evicted_images
532            .insert((*image_id, *requested_size));
533    }
534
535    fn fetch_more_image_keys(&mut self) {
536        self.key_cache.cache = KeyCacheState::PendingBatch;
537        self.paint_api
538            .generate_image_key_async(self.webview_id, self.pipeline_id);
539    }
540
541    /// Insert received keys into the cache and complete the loading of images.
542    fn insert_keys_and_load_images(&mut self, image_keys: Vec<WebRenderImageKey>) {
543        if let KeyCacheState::PendingBatch = self.key_cache.cache {
544            self.key_cache.cache = KeyCacheState::Ready(image_keys);
545            let len = min(
546                self.key_cache.cache.size(),
547                self.key_cache.images_pending_keys.len(),
548            );
549            let images = self
550                .key_cache
551                .images_pending_keys
552                .drain(0..len)
553                .collect::<Vec<PendingKey>>();
554            for key in images {
555                self.load_image_with_keycache(key);
556            }
557            if !self.key_cache.images_pending_keys.is_empty() {
558                self.paint_api
559                    .generate_image_key_async(self.webview_id, self.pipeline_id);
560                self.key_cache.cache = KeyCacheState::PendingBatch
561            }
562        } else {
563            unreachable!("A batch was received while we didn't request one")
564        }
565    }
566
567    /// Complete the loading the of the rasterized svg image. This needs the `RasterImage` to
568    /// already have a `WebRenderImageKey`.
569    fn complete_load_svg(
570        &mut self,
571        rasterized_image: RasterImage,
572        pending_image_id: PendingImageId,
573        requested_size: DeviceIntSize,
574    ) {
575        let listeners = {
576            self.rasterized_vector_images
577                .get_mut(&(pending_image_id, requested_size))
578                .map(|task| {
579                    task.result = Some(rasterized_image);
580                    std::mem::take(&mut task.listeners)
581                })
582                .unwrap_or_default()
583        };
584
585        for (pipeline_id, callback) in listeners {
586            callback(ImageCacheResponseMessage::VectorImageRasterizationComplete(
587                RasterizationCompleteResponse {
588                    pipeline_id,
589                    image_id: pending_image_id,
590                    requested_size,
591                },
592            ));
593        }
594    }
595
596    /// The rest of complete load. This requires that images have a valid `WebRenderImageKey`.
597    fn complete_load(&mut self, key: LoadKey, load_result: LoadResult) {
598        debug!("Completed decoding for {:?}", load_result);
599        let pending_load = match self.pending_loads.remove(&key) {
600            Some(load) => load,
601            None => return,
602        };
603        let url = pending_load.final_url.clone();
604        let image_response = match load_result {
605            LoadResult::LoadedRasterImage(raster_image) => {
606                assert!(raster_image.id.is_some());
607                ImageResponse::Loaded(Image::Raster(Arc::new(raster_image)), url.unwrap())
608            },
609            LoadResult::LoadedVectorImage(vector_image) => {
610                self.vector_images.insert(key, vector_image.clone());
611                let natural_dimensions = vector_image.svg_tree.size().to_int_size();
612                let metadata = ImageMetadata {
613                    width: natural_dimensions.width(),
614                    height: natural_dimensions.height(),
615                };
616
617                let vector_image = VectorImage {
618                    id: key,
619                    svg_id: None,
620                    metadata,
621                    cors_status: vector_image.cors_status,
622                };
623                ImageResponse::Loaded(Image::Vector(vector_image), url.unwrap())
624            },
625            LoadResult::FailedToLoadOrDecode => ImageResponse::FailedToLoadOrDecode,
626        };
627
628        let completed_load = CompletedLoad::new(image_response.clone(), key);
629        self.completed_loads.insert(
630            (
631                pending_load.url,
632                pending_load.load_origin,
633                pending_load.cors_setting,
634            ),
635            completed_load,
636        );
637
638        for listener in pending_load.listeners {
639            listener.respond(image_response.clone());
640        }
641    }
642
643    fn remove_loaded_image(
644        &mut self,
645        url: &ServoUrl,
646        origin: &ImmutableOrigin,
647        cors_setting: &Option<CorsSettings>,
648    ) {
649        if let Some(loaded_image) =
650            self.completed_loads
651                .remove(&(url.clone(), origin.clone(), *cors_setting))
652        {
653            if let ImageResponse::Loaded(Image::Raster(image), _) = loaded_image.image_response {
654                if let Some(id) = image.id {
655                    self.paint_api.update_images(
656                        self.webview_id.into(),
657                        vec![ImageUpdate::DeleteImage(id)].into(),
658                    );
659                }
660            }
661        }
662    }
663
664    fn remove_rasterized_vector_image(
665        &mut self,
666        image_id: &PendingImageId,
667        device_size: &DeviceIntSize,
668    ) {
669        if let Some(entry) = self
670            .rasterized_vector_images
671            .remove(&(*image_id, *device_size))
672        {
673            if let Some(result) = entry.result {
674                if let Some(image_id) = result.id {
675                    self.paint_api.update_images(
676                        self.webview_id.into(),
677                        vec![ImageUpdate::DeleteImage(image_id)].into(),
678                    );
679                }
680            } else {
681                // If there is no corresponding rasterized_vector_image result,
682                // then the vector image is either being rasterized or is in
683                // self.store.key_cache.pending_image_keys. Either way, we need to notify the
684                // KeyCache that it was evicted.
685                self.evict_image_from_keycache(image_id, device_size);
686            }
687        }
688    }
689
690    /// Return a completed image if it exists, or None if there is no complete load
691    /// or the complete load is not fully decoded or is unavailable.
692    fn get_completed_image_if_available(
693        &self,
694        url: ServoUrl,
695        origin: ImmutableOrigin,
696        cors_setting: Option<CorsSettings>,
697    ) -> Option<Result<(Image, ServoUrl), ()>> {
698        self.completed_loads
699            .get(&(url, origin, cors_setting))
700            .map(|completed_load| match &completed_load.image_response {
701                ImageResponse::Loaded(image, url) => Ok((image.clone(), url.clone())),
702                ImageResponse::FailedToLoadOrDecode | ImageResponse::MetadataLoaded(_) => Err(()),
703            })
704    }
705
706    /// Handle a message from one of the decoder worker threads or from a sync
707    /// decoding operation.
708    fn handle_decoder(&mut self, msg: DecoderMsg) {
709        let image = match msg.image {
710            None => LoadResult::FailedToLoadOrDecode,
711            Some(DecodedImage::Raster(raster_image)) => {
712                self.load_image_with_keycache(PendingKey::RasterImage((msg.key, raster_image)));
713                return;
714            },
715            Some(DecodedImage::Vector(vector_image_data)) => {
716                LoadResult::LoadedVectorImage(vector_image_data)
717            },
718        };
719        self.complete_load(msg.key, image);
720    }
721}
722
723pub struct ImageCacheFactoryImpl {
724    /// The data to use for the broken image icon used when images cannot load.
725    broken_image_icon_data: Arc<Vec<u8>>,
726    /// Thread pool for image decoding
727    thread_pool: Arc<ThreadPool>,
728    /// A shared font database to be used by system fonts accessed when rasterizing vector
729    /// images.
730    fontdb: Arc<fontdb::Database>,
731}
732
733impl ImageCacheFactoryImpl {
734    pub fn new(broken_image_icon_data: Vec<u8>) -> Self {
735        debug!("Creating new ImageCacheFactoryImpl");
736
737        // Uses an estimate of the system cpus to decode images
738        // See https://doc.rust-lang.org/stable/std/thread/fn.available_parallelism.html
739        // If no information can be obtained about the system, uses 4 threads as a default
740        let thread_count = thread::available_parallelism()
741            .map(|i| i.get())
742            .unwrap_or(pref!(threadpools_fallback_worker_num) as usize)
743            .min(pref!(threadpools_image_cache_workers_max).max(1) as usize);
744
745        let mut fontdb = fontdb::Database::new();
746        fontdb.load_system_fonts();
747
748        Self {
749            broken_image_icon_data: Arc::new(broken_image_icon_data),
750            thread_pool: Arc::new(ThreadPool::new(thread_count, "ImageCache".to_string())),
751            fontdb: Arc::new(fontdb),
752        }
753    }
754}
755
756impl ImageCacheFactory for ImageCacheFactoryImpl {
757    fn create(
758        &self,
759        webview_id: WebViewId,
760        pipeline_id: PipelineId,
761        paint_api: &CrossProcessPaintApi,
762    ) -> Arc<dyn ImageCache> {
763        Arc::new(ImageCacheImpl {
764            store: Arc::new(Mutex::new(ImageCacheStore {
765                pending_loads: AllPendingLoads::new(),
766                completed_loads: HashMap::new(),
767                vector_images: FxHashMap::default(),
768                rasterized_vector_images: FxHashMap::default(),
769                broken_image_icon_image: OnceCell::new(),
770                paint_api: paint_api.clone(),
771                pipeline_id,
772                webview_id,
773                key_cache: KeyCache::new(),
774            })),
775            svg_id_image_id_map: Arc::new(Mutex::new(FxHashMap::default())),
776            image_id_size_map: Arc::new(Mutex::new(FxHashMap::default())),
777            broken_image_icon_data: self.broken_image_icon_data.clone(),
778            thread_pool: self.thread_pool.clone(),
779            fontdb: self.fontdb.clone(),
780        })
781    }
782}
783
784pub struct ImageCacheImpl {
785    /// Per-[`ImageCache`] data.
786    store: Arc<Mutex<ImageCacheStore>>,
787    /// Maps an SVGSVGElement uuid to a pending image id in the store
788    svg_id_image_id_map: Arc<Mutex<FxHashMap<String, PendingImageId>>>,
789    /// Maps a pending image id to a set of sizes for which that image was requested
790    image_id_size_map: Arc<Mutex<FxHashMap<PendingImageId, Vec<DeviceIntSize>>>>,
791    /// The data to use for the broken image icon used when images cannot load.
792    broken_image_icon_data: Arc<Vec<u8>>,
793    /// Thread pool for image decoding. This is shared with other [`ImageCache`]s in the
794    /// same process.
795    thread_pool: Arc<ThreadPool>,
796    /// A shared font database to be used by system fonts accessed when rasterizing vector
797    /// images. This is shared with other [`ImageCache`]s in the same process.
798    fontdb: Arc<fontdb::Database>,
799}
800
801impl ImageCache for ImageCacheImpl {
802    fn memory_reports(&self, prefix: &str, ops: &mut MallocSizeOfOps) -> Vec<Report> {
803        let store_size = self.store.lock().size_of(ops);
804        let fontdb_size = self.fontdb.conditional_size_of(ops);
805        vec![
806            Report {
807                path: path![prefix, "image-cache"],
808                kind: ReportKind::ExplicitSystemHeapSize,
809                size: store_size,
810            },
811            Report {
812                path: path![prefix, "image-cache", "fontdb"],
813                kind: ReportKind::ExplicitSystemHeapSize,
814                size: fontdb_size,
815            },
816        ]
817    }
818
819    fn get_image_key(&self) -> Option<WebRenderImageKey> {
820        let mut store = self.store.lock();
821        if let KeyCacheState::Ready(ref mut cache) = store.key_cache.cache {
822            if let Some(image_key) = cache.pop() {
823                return Some(image_key);
824            }
825
826            store.fetch_more_image_keys();
827        }
828
829        store
830            .paint_api
831            .generate_image_key_blocking(store.webview_id)
832    }
833
834    fn get_image(
835        &self,
836        url: ServoUrl,
837        origin: ImmutableOrigin,
838        cors_setting: Option<CorsSettings>,
839    ) -> Option<Image> {
840        let store = self.store.lock();
841        let result = store.get_completed_image_if_available(url, origin, cors_setting);
842        match result {
843            Some(Ok((img, _))) => Some(img),
844            _ => None,
845        }
846    }
847
848    fn get_cached_image_status(
849        &self,
850        url: ServoUrl,
851        origin: ImmutableOrigin,
852        cors_setting: Option<CorsSettings>,
853    ) -> ImageCacheResult {
854        let mut store = self.store.lock();
855        if let Some(result) =
856            store.get_completed_image_if_available(url.clone(), origin.clone(), cors_setting)
857        {
858            match result {
859                Ok((image, image_url)) => {
860                    debug!("{} is available", url);
861                    return ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
862                        image,
863                        url: image_url,
864                    });
865                },
866                Err(()) => {
867                    debug!("{} is not available", url);
868                    return ImageCacheResult::FailedToLoadOrDecode;
869                },
870            }
871        }
872
873        let (key, decoded) = {
874            let result = store
875                .pending_loads
876                .get_cached(url.clone(), origin.clone(), cors_setting);
877            match result {
878                CacheResult::Hit(key, pl) => match (&pl.result, &pl.metadata) {
879                    (&Some(Ok(_)), _) => {
880                        debug!("Sync decoding {} ({:?})", url, key);
881                        (
882                            key,
883                            decode_bytes_sync(
884                                key,
885                                pl.bytes.as_slice(),
886                                pl.cors_status,
887                                pl.content_type.clone(),
888                                self.fontdb.clone(),
889                            ),
890                        )
891                    },
892                    (&None, Some(meta)) => {
893                        debug!("Metadata available for {} ({:?})", url, key);
894                        return ImageCacheResult::Available(
895                            ImageOrMetadataAvailable::MetadataAvailable(*meta, key),
896                        );
897                    },
898                    (&Some(Err(_)), _) | (&None, &None) => {
899                        debug!("{} ({:?}) is still pending", url, key);
900                        return ImageCacheResult::Pending(key);
901                    },
902                },
903                CacheResult::Miss(Some((key, _pl))) => {
904                    debug!("Should be requesting {} ({:?})", url, key);
905                    return ImageCacheResult::ReadyForRequest(key);
906                },
907                CacheResult::Miss(None) => {
908                    debug!("Couldn't find an entry for {}", url);
909                    return ImageCacheResult::FailedToLoadOrDecode;
910                },
911            }
912        };
913
914        // In the case where a decode is ongoing (or waiting in a queue) but we
915        // have the full response available, we decode the bytes synchronously
916        // and ignore the async decode when it finishes later.
917        // TODO: make this behaviour configurable according to the caller's needs.
918        store.handle_decoder(decoded);
919        match store.get_completed_image_if_available(url, origin, cors_setting) {
920            Some(Ok((image, image_url))) => {
921                ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
922                    image,
923                    url: image_url,
924                })
925            },
926            // Note: this happens if we are pending a batch of image keys.
927            _ => ImageCacheResult::Pending(key),
928        }
929    }
930
931    fn add_rasterization_complete_listener(
932        &self,
933        pipeline_id: PipelineId,
934        image_id: PendingImageId,
935        requested_size: DeviceIntSize,
936        callback: ImageCacheResponseCallback,
937    ) {
938        {
939            let mut store = self.store.lock();
940            let key = (image_id, requested_size);
941            if !store.vector_images.contains_key(&image_id) {
942                warn!("Unknown image requested for rasterization for key {key:?}");
943                return;
944            };
945
946            let Some(task) = store.rasterized_vector_images.get_mut(&key) else {
947                warn!("Image rasterization task not found in the cache for key {key:?}");
948                return;
949            };
950
951            // If `result` is `None`, the task is still pending.
952            if task.result.is_none() {
953                task.listeners.push((pipeline_id, callback));
954                return;
955            }
956        }
957
958        callback(ImageCacheResponseMessage::VectorImageRasterizationComplete(
959            RasterizationCompleteResponse {
960                pipeline_id,
961                image_id,
962                requested_size,
963            },
964        ));
965    }
966
967    fn rasterize_vector_image(
968        &self,
969        image_id: PendingImageId,
970        requested_size: DeviceIntSize,
971        svg_id: Option<String>,
972    ) -> Option<RasterImage> {
973        let mut store = self.store.lock();
974        let Some(vector_image) = store.vector_images.get(&image_id).cloned() else {
975            warn!("Unknown image id {image_id:?} requested for rasterization");
976            return None;
977        };
978
979        // This early return relies on the fact that the result of image rasterization cannot
980        // ever be `None`. If that were the case we would need to check whether the entry
981        // in the `HashMap` was `Occupied` or not.
982        let entry = store
983            .rasterized_vector_images
984            .entry((image_id, requested_size))
985            .or_default();
986        if let Some(result) = entry.result.as_ref() {
987            return Some(result.clone());
988        }
989
990        if let Some(svg_id) = svg_id {
991            if let Some(old_mapped_image_id) =
992                self.svg_id_image_id_map.lock().insert(svg_id, image_id)
993            {
994                if old_mapped_image_id != image_id {
995                    store.vector_images.remove(&old_mapped_image_id);
996                    store
997                        .rasterized_vector_images
998                        .remove(&(old_mapped_image_id, requested_size));
999                }
1000            }
1001        }
1002        if let Some(requested_sizes_for_id) = self.image_id_size_map.lock().get_mut(&image_id) {
1003            requested_sizes_for_id.push(requested_size);
1004        } else {
1005            self.image_id_size_map
1006                .lock()
1007                .insert(image_id, vec![requested_size]);
1008        }
1009
1010        let store = self.store.clone();
1011        self.thread_pool.spawn(move || {
1012            let natural_size = vector_image.svg_tree.size().to_int_size();
1013            let tinyskia_requested_size = {
1014                let width = requested_size
1015                    .width
1016                    .try_into()
1017                    .unwrap_or(0)
1018                    .min(MAX_SVG_PIXMAP_DIMENSION);
1019                let height = requested_size
1020                    .height
1021                    .try_into()
1022                    .unwrap_or(0)
1023                    .min(MAX_SVG_PIXMAP_DIMENSION);
1024                tiny_skia::IntSize::from_wh(width, height).unwrap_or(natural_size)
1025            };
1026            let transform = tiny_skia::Transform::from_scale(
1027                tinyskia_requested_size.width() as f32 / natural_size.width() as f32,
1028                tinyskia_requested_size.height() as f32 / natural_size.height() as f32,
1029            );
1030            let mut pixmap = tiny_skia::Pixmap::new(
1031                tinyskia_requested_size.width(),
1032                tinyskia_requested_size.height(),
1033            )
1034            .unwrap();
1035            resvg::render(&vector_image.svg_tree, transform, &mut pixmap.as_mut());
1036
1037            let bytes = pixmap.take();
1038            let frame = ImageFrame {
1039                delay: None,
1040                byte_range: 0..bytes.len(),
1041                width: tinyskia_requested_size.width(),
1042                height: tinyskia_requested_size.height(),
1043            };
1044
1045            let rasterized_image = RasterImage {
1046                metadata: ImageMetadata {
1047                    width: tinyskia_requested_size.width(),
1048                    height: tinyskia_requested_size.height(),
1049                },
1050                format: PixelFormat::RGBA8,
1051                frames: vec![frame],
1052                bytes: Arc::new(bytes),
1053                id: None,
1054                cors_status: vector_image.cors_status,
1055                is_opaque: false,
1056            };
1057
1058            let mut store = store.lock();
1059            store.load_image_with_keycache(PendingKey::Svg((
1060                image_id,
1061                rasterized_image,
1062                requested_size,
1063            )));
1064        });
1065
1066        None
1067    }
1068
1069    /// Add a new listener for the given pending image id. If the image is already present,
1070    /// the responder will still receive the expected response.
1071    fn add_listener(&self, listener: ImageLoadListener) {
1072        let mut store = self.store.lock();
1073        self.add_listener_with_store(&mut store, listener);
1074    }
1075
1076    fn evict_completed_image(
1077        &self,
1078        url: &ServoUrl,
1079        origin: &ImmutableOrigin,
1080        cors_setting: &Option<CorsSettings>,
1081    ) {
1082        let mut store = self.store.lock();
1083        store.remove_loaded_image(url, origin, cors_setting);
1084    }
1085
1086    fn evict_rasterized_image(&self, svg_id: &str) {
1087        let mut store = self.store.lock();
1088        if let Some(mapped_image_id) = self.svg_id_image_id_map.lock().remove(svg_id) {
1089            store.pending_loads.remove(&mapped_image_id);
1090            store.vector_images.remove(&mapped_image_id);
1091            if let Some(requested_sizes) = self.image_id_size_map.lock().remove(&mapped_image_id) {
1092                for requested_size in requested_sizes.iter() {
1093                    store.remove_rasterized_vector_image(&mapped_image_id, requested_size);
1094                }
1095            }
1096        }
1097    }
1098
1099    /// Inform the image cache about a response for a pending request.
1100    fn notify_pending_response(&self, id: PendingImageId, action: FetchResponseMsg) {
1101        match (action, id) {
1102            (FetchResponseMsg::ProcessRequestBody(..), _) |
1103            (FetchResponseMsg::ProcessCspViolations(..), _) => (),
1104            (FetchResponseMsg::ProcessResponse(_, response), _) => {
1105                debug!("Received {:?} for {:?}", response.as_ref().map(|_| ()), id);
1106                let mut store = self.store.lock();
1107                if let Some(pending_load) = store.pending_loads.get_by_key_mut(&id) {
1108                    let (cors_status, metadata) = match response {
1109                        Ok(meta) => match meta {
1110                            FetchMetadata::Unfiltered(m) => (CorsStatus::Safe, Some(m)),
1111                            FetchMetadata::Filtered { unsafe_, filtered } => (
1112                                match filtered {
1113                                    FilteredMetadata::Basic(_) | FilteredMetadata::Cors(_) => {
1114                                        CorsStatus::Safe
1115                                    },
1116                                    FilteredMetadata::Opaque |
1117                                    FilteredMetadata::OpaqueRedirect(_) => CorsStatus::Unsafe,
1118                                },
1119                                Some(unsafe_),
1120                            ),
1121                        },
1122                        Err(_) => (CorsStatus::Unsafe, None),
1123                    };
1124                    let final_url = metadata.as_ref().map(|m| m.final_url.clone());
1125                    pending_load.final_url = final_url;
1126                    pending_load.cors_status = cors_status;
1127                    pending_load.content_type = metadata
1128                        .as_ref()
1129                        .and_then(|metadata| metadata.content_type.clone())
1130                        .map(|content_type| content_type.into_inner().into());
1131                } else {
1132                    debug!("Pending load for id {:?} already evicted from cache", id);
1133                }
1134            },
1135            (FetchResponseMsg::ProcessResponseChunk(_, data), _) => {
1136                debug!("Got some data for {:?}", id);
1137                let mut store = self.store.lock();
1138                if let Some(pending_load) = store.pending_loads.get_by_key_mut(&id) {
1139                    pending_load.bytes.extend_from_slice(&data);
1140
1141                    // jmr0 TODO: possibly move to another task?
1142                    if pending_load.metadata.is_none() {
1143                        let mut reader = std::io::Cursor::new(pending_load.bytes.as_slice());
1144                        if let Ok(info) = imsz_from_reader(&mut reader) {
1145                            let img_metadata = ImageMetadata {
1146                                width: info.width as u32,
1147                                height: info.height as u32,
1148                            };
1149                            for listener in &pending_load.listeners {
1150                                listener.respond(ImageResponse::MetadataLoaded(img_metadata));
1151                            }
1152                            pending_load.metadata = Some(img_metadata);
1153                        }
1154                    }
1155                } else {
1156                    debug!("Pending load for id {:?} already evicted from cache", id);
1157                }
1158            },
1159            (FetchResponseMsg::ProcessResponseEOF(_, result, _), key) => {
1160                debug!("Received EOF for {:?}", key);
1161                match result {
1162                    Ok(_) => {
1163                        let (bytes, cors_status, content_type) = {
1164                            let mut store = self.store.lock();
1165                            if let Some(pending_load) = store.pending_loads.get_by_key_mut(&id) {
1166                                pending_load.result = Some(Ok(()));
1167                                debug!("Async decoding {} ({:?})", pending_load.url, key);
1168                                (
1169                                    pending_load.bytes.mark_complete(),
1170                                    pending_load.cors_status,
1171                                    pending_load.content_type.clone(),
1172                                )
1173                            } else {
1174                                debug!("Pending load for id {:?} already evicted from cache", id);
1175                                return;
1176                            }
1177                        };
1178
1179                        let local_store = self.store.clone();
1180                        let fontdb = self.fontdb.clone();
1181                        self.thread_pool.spawn(move || {
1182                            let msg =
1183                                decode_bytes_sync(key, &bytes, cors_status, content_type, fontdb);
1184                            local_store.lock().handle_decoder(msg);
1185                        });
1186                    },
1187                    Err(error) => {
1188                        debug!("Processing error for {key:?}: {error:?}");
1189                        let mut store = self.store.lock();
1190                        store.complete_load(id, LoadResult::FailedToLoadOrDecode)
1191                    },
1192                }
1193            },
1194        }
1195    }
1196
1197    fn fill_key_cache_with_batch_of_keys(&self, image_keys: Vec<WebRenderImageKey>) {
1198        let mut store = self.store.lock();
1199        store.insert_keys_and_load_images(image_keys);
1200    }
1201
1202    fn get_broken_image_icon(&self) -> Option<Arc<RasterImage>> {
1203        let store = self.store.lock();
1204        store
1205            .broken_image_icon_image
1206            .get_or_init(|| {
1207                let mut image = load_from_memory(&self.broken_image_icon_data, CorsStatus::Unsafe)
1208                    .or_else(|| load_from_memory(FALLBACK_RIPPY, CorsStatus::Unsafe))?;
1209                let image_key = store
1210                    .paint_api
1211                    .generate_image_key_blocking(store.webview_id)
1212                    .expect("Could not generate image key for broken image icon");
1213                set_webrender_image_key(&store.paint_api, &mut image, image_key);
1214                Some(Arc::new(image))
1215            })
1216            .clone()
1217    }
1218}
1219
1220impl Drop for ImageCacheStore {
1221    fn drop(&mut self) {
1222        let image_updates = self
1223            .completed_loads
1224            .values()
1225            .filter_map(|load| match &load.image_response {
1226                ImageResponse::Loaded(Image::Raster(image), _) => {
1227                    image.id.map(ImageUpdate::DeleteImage)
1228                },
1229                _ => None,
1230            })
1231            .chain(
1232                self.rasterized_vector_images
1233                    .values()
1234                    .filter_map(|task| task.result.as_ref()?.id.map(ImageUpdate::DeleteImage)),
1235            )
1236            .collect();
1237        self.paint_api
1238            .update_images(self.webview_id.into(), image_updates);
1239    }
1240}
1241
1242impl ImageCacheImpl {
1243    /// Require self.store.lock() before calling.
1244    fn add_listener_with_store(&self, store: &mut ImageCacheStore, listener: ImageLoadListener) {
1245        let id = listener.id;
1246        if let Some(load) = store.pending_loads.get_by_key_mut(&id) {
1247            if let Some(ref metadata) = load.metadata {
1248                listener.respond(ImageResponse::MetadataLoaded(*metadata));
1249            }
1250            load.add_listener(listener);
1251            return;
1252        }
1253        if let Some(load) = store.completed_loads.values().find(|l| l.id == id) {
1254            listener.respond(load.image_response.clone());
1255            return;
1256        }
1257        warn!("Couldn't find cached entry for listener {:?}", id);
1258    }
1259}