-
Notifications
You must be signed in to change notification settings - Fork 54
/
texture_cache.rs
1823 lines (1637 loc) · 68.4 KB
/
texture_cache.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{DirtyRect, DocumentId, ExternalImageType, ImageFormat};
use api::{DebugFlags, ImageDescriptor};
use api::units::*;
#[cfg(test)]
use api::IdNamespace;
use crate::device::{TextureFilter, total_gpu_bytes_allocated};
use crate::freelist::{FreeList, FreeListHandle, UpsertResult, WeakFreeListHandle};
use crate::gpu_cache::{GpuCache, GpuCacheHandle};
use crate::gpu_types::{ImageSource, UvRectKind};
use crate::internal_types::{CacheTextureId, FastHashMap, LayerIndex, TextureUpdateList, TextureUpdateSource};
use crate::internal_types::{TextureSource, TextureCacheAllocInfo, TextureCacheUpdate};
use crate::profiler::{ResourceProfileCounter, TextureCacheProfileCounters};
use crate::render_backend::{FrameId, FrameStamp};
use crate::resource_cache::{CacheItem, CachedImageData};
use std::cell::Cell;
use std::cmp;
use std::mem;
use std::time::{Duration, SystemTime};
use std::rc::Rc;
/// The size of each region/layer in shared cache texture arrays.
pub const TEXTURE_REGION_DIMENSIONS: i32 = 512;
const PICTURE_TEXTURE_ADD_SLICES: usize = 4;
/// The chosen image format for picture tiles.
const PICTURE_TILE_FORMAT: ImageFormat = ImageFormat::BGRA8;
/// The number of pixels in a region. Derived from the above.
const TEXTURE_REGION_PIXELS: usize =
(TEXTURE_REGION_DIMENSIONS as usize) * (TEXTURE_REGION_DIMENSIONS as usize);
// The minimum number of bytes that we must be able to reclaim in order
// to justify clearing the entire shared cache in order to shrink it.
const RECLAIM_THRESHOLD_BYTES: usize = 5 * 1024 * 1024;
/// Items in the texture cache can either be standalone textures,
/// or a sub-rect inside the shared cache.
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
enum EntryDetails {
Standalone,
Picture {
// Index in the picture_textures array
texture_index: usize,
// Slice in the texture array
layer_index: usize,
},
Cache {
/// Origin within the texture layer where this item exists.
origin: DeviceIntPoint,
/// The layer index of the texture array.
layer_index: usize,
},
}
impl EntryDetails {
fn describe(&self) -> (LayerIndex, DeviceIntPoint) {
match *self {
EntryDetails::Standalone => (0, DeviceIntPoint::zero()),
EntryDetails::Picture { layer_index, .. } => (layer_index, DeviceIntPoint::zero()),
EntryDetails::Cache { origin, layer_index } => (layer_index, origin),
}
}
}
impl EntryDetails {
/// Returns the kind associated with the details.
fn kind(&self) -> EntryKind {
match *self {
EntryDetails::Standalone => EntryKind::Standalone,
EntryDetails::Picture { .. } => EntryKind::Picture,
EntryDetails::Cache { .. } => EntryKind::Shared,
}
}
}
/// Tag identifying standalone-versus-shared, without the details.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum EntryKind {
Standalone,
Picture,
Shared,
}
#[derive(Debug)]
pub enum CacheEntryMarker {}
// Stores information related to a single entry in the texture
// cache. This is stored for each item whether it's in the shared
// cache or a standalone texture.
#[derive(Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct CacheEntry {
/// Size the requested item, in device pixels.
size: DeviceIntSize,
/// Details specific to standalone or shared items.
details: EntryDetails,
/// Arbitrary user data associated with this item.
user_data: [f32; 3],
/// The last frame this item was requested for rendering.
last_access: FrameStamp,
/// Handle to the resource rect in the GPU cache.
uv_rect_handle: GpuCacheHandle,
/// Image format of the item.
format: ImageFormat,
filter: TextureFilter,
/// The actual device texture ID this is part of.
texture_id: CacheTextureId,
/// Optional notice when the entry is evicted from the cache.
eviction_notice: Option<EvictionNotice>,
/// The type of UV rect this entry specifies.
uv_rect_kind: UvRectKind,
/// If set to `Auto` the cache entry may be evicted if unused for a number of frames.
eviction: Eviction,
}
impl CacheEntry {
// Create a new entry for a standalone texture.
fn new_standalone(
texture_id: CacheTextureId,
last_access: FrameStamp,
params: &CacheAllocParams,
) -> Self {
CacheEntry {
size: params.descriptor.size,
user_data: params.user_data,
last_access,
details: EntryDetails::Standalone,
texture_id,
format: params.descriptor.format,
filter: params.filter,
uv_rect_handle: GpuCacheHandle::new(),
eviction_notice: None,
uv_rect_kind: params.uv_rect_kind,
eviction: Eviction::Auto,
}
}
// Update the GPU cache for this texture cache entry.
// This ensures that the UV rect, and texture layer index
// are up to date in the GPU cache for vertex shaders
// to fetch from.
fn update_gpu_cache(&mut self, gpu_cache: &mut GpuCache) {
if let Some(mut request) = gpu_cache.request(&mut self.uv_rect_handle) {
let (layer_index, origin) = self.details.describe();
let image_source = ImageSource {
p0: origin.to_f32(),
p1: (origin + self.size).to_f32(),
texture_layer: layer_index as f32,
user_data: self.user_data,
uv_rect_kind: self.uv_rect_kind,
};
image_source.write_gpu_blocks(&mut request);
}
}
fn evict(&self) {
if let Some(eviction_notice) = self.eviction_notice.as_ref() {
eviction_notice.notify();
}
}
}
/// A texture cache handle is a weak reference to a cache entry.
///
/// If the handle has not been inserted into the cache yet, or if the entry was
/// previously inserted and then evicted, lookup of the handle will fail, and
/// the cache handle needs to re-upload this item to the texture cache (see
/// request() below).
pub type TextureCacheHandle = WeakFreeListHandle<CacheEntryMarker>;
/// Describes the eviction policy for a given entry in the texture cache.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum Eviction {
/// The entry will be evicted under the normal rules (which differ between
/// standalone and shared entries).
Auto,
/// The entry will not be evicted until the policy is explicitly set to a
/// different value.
Manual,
/// The entry will be evicted if it was not used in the last frame.
///
/// FIXME(bholley): Currently this only applies to the standalone case.
Eager,
}
// An eviction notice is a shared condition useful for detecting
// when a TextureCacheHandle gets evicted from the TextureCache.
// It is optionally installed to the TextureCache when an update()
// is scheduled. A single notice may be shared among any number of
// TextureCacheHandle updates. The notice may then be subsequently
// checked to see if any of the updates using it have been evicted.
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct EvictionNotice {
evicted: Rc<Cell<bool>>,
}
impl EvictionNotice {
fn notify(&self) {
self.evicted.set(true);
}
pub fn check(&self) -> bool {
if self.evicted.get() {
self.evicted.set(false);
true
} else {
false
}
}
}
/// A set of lazily allocated, fixed size, texture arrays for each format the
/// texture cache supports.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct SharedTextures {
array_rgba8_nearest: TextureArray,
array_a8_linear: TextureArray,
array_a16_linear: TextureArray,
array_rgba8_linear: TextureArray,
}
impl SharedTextures {
/// Mints a new set of shared textures.
fn new() -> Self {
Self {
// Used primarily for cached shadow masks. There can be lots of
// these on some pages like francine, but most pages don't use it
// much.
array_a8_linear: TextureArray::new(
ImageFormat::R8,
TextureFilter::Linear,
),
// Used for experimental hdr yuv texture support, but not used in
// production Firefox.
array_a16_linear: TextureArray::new(
ImageFormat::R16,
TextureFilter::Linear,
),
// The primary cache for images, glyphs, etc.
array_rgba8_linear: TextureArray::new(
ImageFormat::BGRA8,
TextureFilter::Linear,
),
// Used for image-rendering: crisp. This is mostly favicons, which
// are small. Some other images use it too, but those tend to be
// larger than 512x512 and thus don't use the shared cache anyway.
array_rgba8_nearest: TextureArray::new(
ImageFormat::BGRA8,
TextureFilter::Nearest,
),
}
}
/// Returns the cumulative number of GPU bytes consumed by all the shared textures.
fn size_in_bytes(&self) -> usize {
self.array_a8_linear.size_in_bytes() +
self.array_a16_linear.size_in_bytes() +
self.array_rgba8_linear.size_in_bytes() +
self.array_rgba8_nearest.size_in_bytes()
}
/// Returns the cumulative number of GPU bytes consumed by empty regions.
fn empty_region_bytes(&self) -> usize {
self.array_a8_linear.empty_region_bytes() +
self.array_a16_linear.empty_region_bytes() +
self.array_rgba8_linear.empty_region_bytes() +
self.array_rgba8_nearest.empty_region_bytes()
}
/// Clears each texture in the set, with the given set of pending updates.
fn clear(&mut self, updates: &mut TextureUpdateList) {
self.array_a8_linear.clear(updates);
self.array_a16_linear.clear(updates);
self.array_rgba8_linear.clear(updates);
self.array_rgba8_nearest.clear(updates);
}
/// Returns a mutable borrow for the shared texture array matching the parameters.
fn select(&mut self, format: ImageFormat, filter: TextureFilter) -> &mut TextureArray {
match (format, filter) {
(ImageFormat::R8, TextureFilter::Linear) => &mut self.array_a8_linear,
(ImageFormat::R16, TextureFilter::Linear) => &mut self.array_a16_linear,
(ImageFormat::BGRA8, TextureFilter::Linear) => &mut self.array_rgba8_linear,
(ImageFormat::BGRA8, TextureFilter::Nearest) => &mut self.array_rgba8_nearest,
(_, _) => unreachable!(),
}
}
}
/// Lists of strong handles owned by the texture cache. There is only one strong
/// handle for each entry, but unlimited weak handles. Consumers receive the weak
/// handles, and `TextureCache` owns the strong handles internally.
#[derive(Default, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct EntryHandles {
/// Handles for each standalone texture cache entry.
standalone: Vec<FreeListHandle<CacheEntryMarker>>,
/// Handles for each picture cache entry.
picture: Vec<FreeListHandle<CacheEntryMarker>>,
/// Handles for each shared texture cache entry.
shared: Vec<FreeListHandle<CacheEntryMarker>>,
}
impl EntryHandles {
/// Mutably borrows the requested handle list.
fn select(&mut self, kind: EntryKind) -> &mut Vec<FreeListHandle<CacheEntryMarker>> {
match kind {
EntryKind::Standalone => &mut self.standalone,
EntryKind::Picture => &mut self.picture,
EntryKind::Shared => &mut self.shared,
}
}
}
/// Container struct for the various parameters used in cache allocation.
struct CacheAllocParams {
descriptor: ImageDescriptor,
filter: TextureFilter,
user_data: [f32; 3],
uv_rect_kind: UvRectKind,
}
/// Criterion to determine whether a cache entry should be evicted. Generated
/// with `EvictionThresholdBuilder`.
///
/// Our eviction scheme is based on the age of the entry, both in terms of
/// number of frames and ellapsed time. It does not directly consider the size
/// of the entry, but may consider overall memory usage by WebRender, by making
/// eviction increasingly aggressive as overall memory usage increases.
///
/// Note that we don't just wrap a `FrameStamp` here, because `FrameStamp`
/// requires that if the id fields are the same, the time fields will be as
/// well. The pair of values in our eviction threshold generally do not match
/// the stamp of any actual frame, and the comparison semantics are also
/// different - so it's best to use a distinct type.
#[derive(Clone, Copy)]
struct EvictionThreshold {
id: FrameId,
time: SystemTime,
}
impl EvictionThreshold {
/// Returns true if the entry with the given access record should be evicted
/// under this threshold.
fn should_evict(&self, last_access: FrameStamp) -> bool {
last_access.frame_id() < self.id &&
last_access.time() < self.time
}
}
/// Helper to generate an `EvictionThreshold` with the desired policy.
///
/// Without any constraints, the builder will generate a threshold that evicts
/// all frames other than the current one. Constraints are additive, i.e. setting
/// a frame limit and a time limit only evicts frames with an id and time each
/// less than the respective limits.
struct EvictionThresholdBuilder {
now: FrameStamp,
max_frames: Option<usize>,
max_time_ms: Option<usize>,
scale_by_pressure: bool,
}
impl EvictionThresholdBuilder {
fn new(now: FrameStamp) -> Self {
Self {
now,
max_frames: None,
max_time_ms: None,
scale_by_pressure: false,
}
}
fn max_frames(mut self, frames: usize) -> Self {
self.max_frames = Some(frames);
self
}
fn max_time_s(mut self, seconds: usize) -> Self {
self.max_time_ms = Some(seconds * 1000);
self
}
fn scale_by_pressure(mut self) -> Self {
self.scale_by_pressure = true;
self
}
fn build(self) -> EvictionThreshold {
const MAX_MEMORY_PRESSURE_BYTES: f64 = (500 * 1024 * 1024) as f64;
// Compute the memory pressure factor in the range of [0, 1.0].
let pressure_factor = if self.scale_by_pressure {
let bytes_allocated = total_gpu_bytes_allocated() as f64;
1.0 - (bytes_allocated / MAX_MEMORY_PRESSURE_BYTES).min(1.0)
} else {
1.0
};
// Compute the maximum period an entry can go unused before eviction.
// If a category (frame or time) wasn't specified, we set the
// threshold for that category to |now|, which lets the other category
// be the deciding factor. If neither category is specified, we'll evict
// everything but the current frame.
//
// Note that we need to clamp the frame id to avoid it going negative or
// matching FrameId::INVALID early in execution. We don't need to clamp
// the time because it's unix-epoch-relative.
let max_frames = self.max_frames
.map(|f| (f as f64 * pressure_factor) as usize)
.unwrap_or(0)
.min(self.now.frame_id().as_usize() - 1);
let max_time_ms = self.max_time_ms
.map(|f| (f as f64 * pressure_factor) as usize)
.unwrap_or(0) as u64;
EvictionThreshold {
id: self.now.frame_id() - max_frames,
time: self.now.time() - Duration::from_millis(max_time_ms),
}
}
}
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PerDocumentData {
/// The last `FrameStamp` in which we expired the shared cache for
/// this document.
last_shared_cache_expiration: FrameStamp,
/// Strong handles for all entries that this document has allocated
/// from the shared FreeList.
handles: EntryHandles,
}
impl PerDocumentData {
pub fn new() -> Self {
PerDocumentData {
last_shared_cache_expiration: FrameStamp::INVALID,
handles: EntryHandles::default(),
}
}
}
/// General-purpose manager for images in GPU memory. This includes images,
/// rasterized glyphs, rasterized blobs, cached render tasks, etc.
///
/// The texture cache is owned and managed by the RenderBackend thread, and
/// produces a series of commands to manipulate the textures on the Renderer
/// thread. These commands are executed before any rendering is performed for
/// a given frame.
///
/// Entries in the texture cache are not guaranteed to live past the end of the
/// frame in which they are requested, and may be evicted. The API supports
/// querying whether an entry is still available.
///
/// The TextureCache is different from the GpuCache in that the former stores
/// images, whereas the latter stores data and parameters for use in the shaders.
/// This means that the texture cache can be visualized, which is a good way to
/// understand how it works. Enabling gfx.webrender.debug.texture-cache shows a
/// live view of its contents in Firefox.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct TextureCache {
/// Set of texture arrays in different formats used for the shared cache.
shared_textures: SharedTextures,
/// A single texture array for picture caching.
picture_textures: Vec<WholeTextureArray>,
/// Maximum texture size supported by hardware.
max_texture_size: i32,
/// Maximum number of texture layers supported by hardware.
max_texture_layers: usize,
/// The current set of debug flags.
debug_flags: DebugFlags,
/// The next unused virtual texture ID. Monotonically increasing.
next_id: CacheTextureId,
/// A list of allocations and updates that need to be applied to the texture
/// cache in the rendering thread this frame.
#[cfg_attr(all(feature = "serde", any(feature = "capture", feature = "replay")), serde(skip))]
pending_updates: TextureUpdateList,
/// The current `FrameStamp`. Used for cache eviction policies.
now: FrameStamp,
/// The time at which we first reached the byte threshold for reclaiming
/// cache memory. `None if we haven't reached the threshold.
reached_reclaim_threshold: Option<SystemTime>,
/// Maintains the list of all current items in the texture cache.
entries: FreeList<CacheEntry, CacheEntryMarker>,
/// Holds items that need to be maintained on a per-document basis. If we
/// modify this data for a document without also building a frame for that
/// document, then we might end up erroneously evicting items out from
/// under that document.
per_doc_data: FastHashMap<DocumentId, PerDocumentData>,
/// The current document's data. This is moved out of per_doc_data in
/// begin_frame and moved back in end_frame to solve borrow checker issues.
/// We should try removing this when we require a rustc with NLL.
doc_data: PerDocumentData,
/// This indicates that we performed a cleanup operation which requires all
/// documents to build a frame.
require_frame_build: bool,
}
impl TextureCache {
pub fn new(
max_texture_size: i32,
mut max_texture_layers: usize,
picture_tile_sizes: &[DeviceIntSize],
initial_size: DeviceIntSize,
) -> Self {
if cfg!(target_os = "macos") {
// On MBP integrated Intel GPUs, texture arrays appear to be
// implemented as a single texture of stacked layers, and that
// texture appears to be subject to the texture size limit. As such,
// allocating more than 32 512x512 regions results in a dimension
// longer than 16k (the max texture size), causing incorrect behavior.
//
// So we clamp the number of layers on mac. This results in maximum
// texture array size of 32MB, which isn't ideal but isn't terrible
// either. OpenGL on mac is not long for this earth, so this may be
// good enough until we have WebRender on gfx-rs (on Metal).
//
// Note that we could also define this more generally in terms of
// |max_texture_size / TEXTURE_REGION_DIMENSION|, except:
// * max_texture_size is actually clamped beyond the device limit
// by Gecko to 8192, so we'd need to thread the raw device value
// here, and:
// * The bug we're working around is likely specific to a single
// driver family, and those drivers are also likely to share
// the same max texture size of 16k. If we do encounter a driver
// with the same bug but a lower max texture size, we might need
// to rethink our strategy anyway, since a limit below 32MB might
// start to introduce performance issues.
max_texture_layers = max_texture_layers.min(32);
}
let mut pending_updates = TextureUpdateList::new();
let mut picture_textures = Vec::new();
let mut next_texture_id = 1;
for tile_size in picture_tile_sizes {
// TODO(gw): The way initial size is used here may allocate a lot of memory once
// we are using multiple slice sizes. Do some measurements once we
// have multiple slices here and adjust the calculations as required.
let picture_texture = WholeTextureArray {
size: *tile_size,
filter: TextureFilter::Nearest,
format: PICTURE_TILE_FORMAT,
texture_id: CacheTextureId(next_texture_id),
slices: {
let num_x = (initial_size.width + tile_size.width - 1) / tile_size.width;
let num_y = (initial_size.height + tile_size.height - 1) / tile_size.height;
let count = (num_x * num_y).max(1).min(16) as usize;
info!("Initializing picture texture with {}x{} slices", num_x, num_y);
vec![WholeTextureSlice { uv_rect_handle: None }; count]
},
has_depth: true,
};
next_texture_id += 1;
pending_updates.push_alloc(picture_texture.texture_id, picture_texture.to_info());
picture_textures.push(picture_texture);
}
TextureCache {
shared_textures: SharedTextures::new(),
picture_textures,
reached_reclaim_threshold: None,
entries: FreeList::new(),
max_texture_size,
max_texture_layers,
debug_flags: DebugFlags::empty(),
next_id: CacheTextureId(next_texture_id),
pending_updates,
now: FrameStamp::INVALID,
per_doc_data: FastHashMap::default(),
doc_data: PerDocumentData::new(),
require_frame_build: false,
}
}
/// Creates a TextureCache and sets it up with a valid `FrameStamp`, which
/// is useful for avoiding panics when instantiating the `TextureCache`
/// directly from unit test code.
#[cfg(test)]
pub fn new_for_testing(max_texture_size: i32, max_texture_layers: usize) -> Self {
let mut cache = Self::new(max_texture_size, max_texture_layers, &[], DeviceIntSize::zero());
let mut now = FrameStamp::first(DocumentId::new(IdNamespace(1), 1));
now.advance();
cache.begin_frame(now);
cache
}
pub fn set_debug_flags(&mut self, flags: DebugFlags) {
self.debug_flags = flags;
}
/// Clear all entries of the specified kind.
fn clear_kind(&mut self, kind: EntryKind) {
let mut per_doc_data = mem::replace(&mut self.per_doc_data, FastHashMap::default());
for (&_, doc_data) in per_doc_data.iter_mut() {
let entry_handles = mem::replace(
doc_data.handles.select(kind),
Vec::new(),
);
for handle in entry_handles {
let entry = self.entries.free(handle);
entry.evict();
self.free(&entry);
}
}
self.pending_updates.note_clear();
self.per_doc_data = per_doc_data;
self.require_frame_build = true;
}
fn clear_standalone(&mut self) {
debug_assert!(!self.now.is_valid());
self.clear_kind(EntryKind::Standalone);
}
fn clear_picture(&mut self) {
self.clear_kind(EntryKind::Picture);
for picture_texture in &mut self.picture_textures {
if let Some(texture_id) = picture_texture.reset(PICTURE_TEXTURE_ADD_SLICES) {
self.pending_updates.push_reset(texture_id, picture_texture.to_info());
}
}
}
fn clear_shared(&mut self) {
self.unset_doc_data();
self.clear_kind(EntryKind::Shared);
self.shared_textures.clear(&mut self.pending_updates);
self.set_doc_data();
}
/// Clear all entries in the texture cache. This is a fairly drastic
/// step that should only be called very rarely.
pub fn clear_all(&mut self) {
self.clear_standalone();
self.clear_picture();
self.clear_shared();
}
fn set_doc_data(&mut self) {
let document_id = self.now.document_id();
self.doc_data = self.per_doc_data
.remove(&document_id)
.unwrap_or_else(PerDocumentData::new);
}
fn unset_doc_data(&mut self) {
self.per_doc_data.insert(self.now.document_id(),
mem::replace(&mut self.doc_data, PerDocumentData::new()));
}
pub fn prepare_for_frames(&mut self, time: SystemTime) {
self.maybe_reclaim_shared_memory(time);
}
pub fn bookkeep_after_frames(&mut self) {
self.require_frame_build = false;
}
pub fn requires_frame_build(&self) -> bool {
self.require_frame_build
}
/// Called at the beginning of each frame.
pub fn begin_frame(&mut self, stamp: FrameStamp) {
debug_assert!(!self.now.is_valid());
self.now = stamp;
self.set_doc_data();
self.maybe_do_periodic_gc();
}
fn maybe_reclaim_shared_memory(&mut self, time: SystemTime) {
// If we've had a sufficient number of unused layers for a sufficiently
// long time, just blow the whole cache away to shrink it.
//
// We could do this more intelligently with a resize+blit, but that would
// add complexity for a rare case.
//
// This function must be called before the first begin_frame() for a group
// of documents, otherwise documents could end up ignoring the
// self.require_frame_build flag which is set if we end up calling
// clear_shared.
debug_assert!(!self.now.is_valid());
if self.shared_textures.empty_region_bytes() >= RECLAIM_THRESHOLD_BYTES {
self.reached_reclaim_threshold.get_or_insert(time);
} else {
self.reached_reclaim_threshold = None;
}
if let Some(t) = self.reached_reclaim_threshold {
let dur = time.duration_since(t).unwrap_or_default();
if dur >= Duration::from_secs(5) {
self.clear_shared();
self.reached_reclaim_threshold = None;
}
}
}
/// Called at the beginning of each frame to periodically GC by expiring
/// old shared entries. If necessary, the shared memory opened up as a
/// result of expiring these entries will be reclaimed before the next
/// group of document frames.
fn maybe_do_periodic_gc(&mut self) {
debug_assert!(self.now.is_valid());
// Normally the shared cache only gets GCed when we fail to allocate.
// However, we also perform a periodic, conservative GC to ensure that
// we recover unused memory in bounded time, rather than having it
// depend on allocation patterns of subsequent content.
let time_since_last_gc = self.now.time()
.duration_since(self.doc_data.last_shared_cache_expiration.time())
.unwrap_or_default();
let do_periodic_gc = time_since_last_gc >= Duration::from_secs(5) &&
self.shared_textures.size_in_bytes() >= RECLAIM_THRESHOLD_BYTES * 2;
if do_periodic_gc {
let threshold = EvictionThresholdBuilder::new(self.now)
.max_frames(1)
.max_time_s(10)
.build();
self.maybe_expire_old_shared_entries(threshold);
}
}
pub fn end_frame(&mut self, texture_cache_profile: &mut TextureCacheProfileCounters) {
debug_assert!(self.now.is_valid());
// Expire standalone entries.
//
// Most of the time, standalone cache entries correspond to images whose
// width or height is greater than the region size in the shared cache, i.e.
// 512 pixels. Cached render tasks also frequently get standalone entries,
// but those use the Eviction::Eager policy (for now). So the tradeoff there
// is largely around reducing texture upload jank while keeping memory usage
// at an acceptable level.
let threshold = self.default_eviction();
self.expire_old_entries(EntryKind::Standalone, threshold);
self.expire_old_entries(EntryKind::Picture, threshold);
self.shared_textures.array_a8_linear
.update_profile(&mut texture_cache_profile.pages_a8_linear);
self.shared_textures.array_a16_linear
.update_profile(&mut texture_cache_profile.pages_a16_linear);
self.shared_textures.array_rgba8_linear
.update_profile(&mut texture_cache_profile.pages_rgba8_linear);
self.shared_textures.array_rgba8_nearest
.update_profile(&mut texture_cache_profile.pages_rgba8_nearest);
// For now, this profile counter just accumulates the slices and bytes
// from all picture cache texture arrays.
let mut picture_slices = 0;
let mut picture_bytes = 0;
for picture_texture in &self.picture_textures {
picture_slices += picture_texture.slices.len();
picture_bytes += picture_texture.size_in_bytes();
}
texture_cache_profile.pages_picture.set(picture_slices, picture_bytes);
self.unset_doc_data();
self.now = FrameStamp::INVALID;
}
// Request an item in the texture cache. All images that will
// be used on a frame *must* have request() called on their
// handle, to update the last used timestamp and ensure
// that resources are not flushed from the cache too early.
//
// Returns true if the image needs to be uploaded to the
// texture cache (either never uploaded, or has been
// evicted on a previous frame).
pub fn request(&mut self, handle: &TextureCacheHandle, gpu_cache: &mut GpuCache) -> bool {
match self.entries.get_opt_mut(handle) {
// If an image is requested that is already in the cache,
// refresh the GPU cache data associated with this item.
Some(entry) => {
entry.last_access = self.now;
entry.update_gpu_cache(gpu_cache);
false
}
None => true,
}
}
// Returns true if the image needs to be uploaded to the
// texture cache (either never uploaded, or has been
// evicted on a previous frame).
pub fn needs_upload(&self, handle: &TextureCacheHandle) -> bool {
self.entries.get_opt(handle).is_none()
}
pub fn max_texture_size(&self) -> i32 {
self.max_texture_size
}
#[cfg(feature = "replay")]
pub fn max_texture_layers(&self) -> usize {
self.max_texture_layers
}
#[cfg(feature = "replay")]
pub fn picture_tile_sizes(&self) -> Vec<DeviceIntSize> {
self.picture_textures.iter().map(|pt| pt.size).collect()
}
pub fn pending_updates(&mut self) -> TextureUpdateList {
mem::replace(&mut self.pending_updates, TextureUpdateList::new())
}
// Update the data stored by a given texture cache handle.
pub fn update(
&mut self,
handle: &mut TextureCacheHandle,
descriptor: ImageDescriptor,
filter: TextureFilter,
data: Option<CachedImageData>,
user_data: [f32; 3],
mut dirty_rect: ImageDirtyRect,
gpu_cache: &mut GpuCache,
eviction_notice: Option<&EvictionNotice>,
uv_rect_kind: UvRectKind,
eviction: Eviction,
) {
debug_assert!(self.now.is_valid());
// Determine if we need to allocate texture cache memory
// for this item. We need to reallocate if any of the following
// is true:
// - Never been in the cache
// - Has been in the cache but was evicted.
// - Exists in the cache but dimensions / format have changed.
let realloc = match self.entries.get_opt(handle) {
Some(entry) => {
entry.size != descriptor.size || entry.format != descriptor.format
}
None => {
// Not allocated, or was previously allocated but has been evicted.
true
}
};
if realloc {
let params = CacheAllocParams { descriptor, filter, user_data, uv_rect_kind };
self.allocate(¶ms, handle);
// If we reallocated, we need to upload the whole item again.
dirty_rect = DirtyRect::All;
}
let entry = self.entries.get_opt_mut(handle)
.expect("BUG: handle must be valid now");
// Install the new eviction notice for this update, if applicable.
entry.eviction_notice = eviction_notice.cloned();
entry.uv_rect_kind = uv_rect_kind;
// Invalidate the contents of the resource rect in the GPU cache.
// This ensures that the update_gpu_cache below will add
// the new information to the GPU cache.
//TODO: only invalidate if the parameters change?
gpu_cache.invalidate(&entry.uv_rect_handle);
// Upload the resource rect and texture array layer.
entry.update_gpu_cache(gpu_cache);
entry.eviction = eviction;
// Create an update command, which the render thread processes
// to upload the new image data into the correct location
// in GPU memory.
if let Some(data) = data {
let (layer_index, origin) = entry.details.describe();
let op = TextureCacheUpdate::new_update(
data,
&descriptor,
origin,
entry.size,
entry.texture_id,
layer_index as i32,
&dirty_rect,
);
self.pending_updates.push_update(op);
}
}
// Check if a given texture handle has a valid allocation
// in the texture cache.
pub fn is_allocated(&self, handle: &TextureCacheHandle) -> bool {
self.entries.get_opt(handle).is_some()
}
// Return the allocated size of the texture handle's associated data,
// or otherwise indicate the handle is invalid.
pub fn get_allocated_size(&self, handle: &TextureCacheHandle) -> Option<usize> {
self.entries.get_opt(handle).map(|entry| {
(entry.format.bytes_per_pixel() * entry.size.area()) as usize
})
}
// Retrieve the details of an item in the cache. This is used
// during batch creation to provide the resource rect address
// to the shaders and texture ID to the batching logic.
// This function will assert in debug modes if the caller
// tries to get a handle that was not requested this frame.
pub fn get(&self, handle: &TextureCacheHandle) -> CacheItem {
let (texture_id, layer_index, uv_rect, uv_rect_handle) = self.get_cache_location(handle);
CacheItem {
uv_rect_handle,
texture_id: TextureSource::TextureCache(texture_id),
uv_rect,
texture_layer: layer_index as i32,
}
}
/// A more detailed version of get(). This allows access to the actual
/// device rect of the cache allocation.
///
/// Returns a tuple identifying the texture, the layer, the region,
/// and its GPU handle.
pub fn get_cache_location(
&self,
handle: &TextureCacheHandle,
) -> (CacheTextureId, LayerIndex, DeviceIntRect, GpuCacheHandle) {
let entry = self.entries
.get_opt(handle)
.expect("BUG: was dropped from cache or not updated!");
debug_assert_eq!(entry.last_access, self.now);
let (layer_index, origin) = entry.details.describe();
(entry.texture_id,
layer_index as usize,
DeviceIntRect::new(origin, entry.size),
entry.uv_rect_handle)
}
pub fn mark_unused(&mut self, handle: &TextureCacheHandle) {
if let Some(entry) = self.entries.get_opt_mut(handle) {
// Set last accessed stamp invalid to ensure it gets cleaned up
// next time we expire entries.
entry.last_access = FrameStamp::INVALID;
entry.eviction = Eviction::Auto;
}
}
/// Returns the default eviction policy.
///
/// These parameters come from very rough instrumentation of hits in the
/// shared cache, with simple browsing on a few pages. In rough terms, more
/// than 99.5% of cache hits occur for entries that were used in the previous
/// frame. This is obviously the dominant case, but we still want good behavior
/// in long-tail cases (i.e. a large image is scrolled off-screen and on again).
/// If we exclude immediately-reused (first frame) entries, 70% of the remaining
/// hits happen within the first 200 frames. So we can be relatively agressive
/// about eviction without sacrificing much in terms of cache performance.
/// The one wrinkle is that animation-heavy pages do tend to extend the
/// distribution, presumably because they churn through FrameIds faster than
/// their more-static counterparts. As such, we _also_ provide a time floor
/// (which was not measured with the same degree of rigour).
fn default_eviction(&self) -> EvictionThreshold {
EvictionThresholdBuilder::new(self.now)
.max_frames(200)
.max_time_s(3)
.scale_by_pressure()
.build()
}
/// Shared eviction code for standalone and shared entries.
///
/// See `EvictionThreshold` for more details on policy.
fn expire_old_entries(&mut self, kind: EntryKind, threshold: EvictionThreshold) {
debug_assert!(self.now.is_valid());
// Iterate over the entries in reverse order, evicting the ones older than
// the frame age threshold. Reverse order avoids iterator invalidation when
// removing entries.