/
direct_renderer.cc
1161 lines (1003 loc) · 45.9 KB
/
direct_renderer.cc
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/viz/service/display/direct_renderer.h"
#include <limits.h>
#include <stddef.h>
#include <utility>
#include <vector>
#include "base/auto_reset.h"
#include "base/containers/circular_deque.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/timer/elapsed_timer.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "cc/base/math_util.h"
#include "cc/paint/filter_operations.h"
#include "components/viz/common/display/renderer_settings.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "components/viz/common/frame_sinks/copy_output_util.h"
#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h"
#include "components/viz/common/quads/compositor_render_pass_draw_quad.h"
#include "components/viz/common/quads/draw_quad.h"
#include "components/viz/common/quads/solid_color_draw_quad.h"
#include "components/viz/common/resources/platform_color.h"
#include "components/viz/common/resources/resource_format_utils.h"
#include "components/viz/common/viz_utils.h"
#include "components/viz/service/display/bsp_tree.h"
#include "components/viz/service/display/bsp_walk_action.h"
#include "components/viz/service/display/output_surface.h"
#include "components/viz/service/display/skia_output_surface.h"
#include "gpu/command_buffer/common/capabilities.h"
#include "media/base/video_util.h"
#include "ui/gfx/geometry/quad_f.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/geometry/transform_util.h"
namespace {
// Returns the bounding box that contains the specified rounded corner.
gfx::RectF ComputeRoundedCornerBoundingBox(const gfx::RRectF& rrect,
const gfx::RRectF::Corner corner) {
auto radii = rrect.GetCornerRadii(corner);
gfx::RectF bounding_box(radii.x(), radii.y());
switch (corner) {
case gfx::RRectF::Corner::kUpperLeft:
bounding_box.Offset(rrect.rect().x(), rrect.rect().y());
break;
case gfx::RRectF::Corner::kUpperRight:
bounding_box.Offset(rrect.rect().right() - radii.x(), rrect.rect().y());
break;
case gfx::RRectF::Corner::kLowerRight:
bounding_box.Offset(rrect.rect().right() - radii.x(),
rrect.rect().bottom() - radii.y());
break;
case gfx::RRectF::Corner::kLowerLeft:
bounding_box.Offset(rrect.rect().x(), rrect.rect().bottom() - radii.y());
break;
}
return bounding_box;
}
} // namespace
namespace viz {
DirectRenderer::DrawingFrame::DrawingFrame() = default;
DirectRenderer::DrawingFrame::~DrawingFrame() = default;
DirectRenderer::SwapFrameData::SwapFrameData() = default;
DirectRenderer::SwapFrameData::~SwapFrameData() = default;
DirectRenderer::SwapFrameData::SwapFrameData(SwapFrameData&&) = default;
DirectRenderer::SwapFrameData& DirectRenderer::SwapFrameData::operator=(
SwapFrameData&&) = default;
DirectRenderer::DirectRenderer(const RendererSettings* settings,
const DebugRendererSettings* debug_settings,
OutputSurface* output_surface,
DisplayResourceProvider* resource_provider,
OverlayProcessorInterface* overlay_processor)
: settings_(settings),
debug_settings_(debug_settings),
output_surface_(output_surface),
resource_provider_(resource_provider),
overlay_processor_(overlay_processor),
allow_undamaged_nonroot_render_pass_to_skip_(base::FeatureList::IsEnabled(
features::kAllowUndamagedNonrootRenderPassToSkip)) {
DCHECK(output_surface_);
}
DirectRenderer::~DirectRenderer() = default;
void DirectRenderer::Initialize() {
use_partial_swap_ = settings_->partial_swap_enabled && CanPartialSwap();
initialized_ = true;
}
// static
gfx::RectF DirectRenderer::QuadVertexRect() {
return gfx::RectF(-0.5f, -0.5f, 1.f, 1.f);
}
// static
void DirectRenderer::QuadRectTransform(gfx::Transform* quad_rect_transform,
const gfx::Transform& quad_transform,
const gfx::RectF& quad_rect) {
*quad_rect_transform = quad_transform;
quad_rect_transform->Translate(0.5 * quad_rect.width() + quad_rect.x(),
0.5 * quad_rect.height() + quad_rect.y());
quad_rect_transform->Scale(quad_rect.width(), quad_rect.height());
}
void DirectRenderer::InitializeViewport(DrawingFrame* frame,
const gfx::Rect& draw_rect,
const gfx::Rect& viewport_rect,
const gfx::Size& surface_size) {
DCHECK_GE(viewport_rect.x(), 0);
DCHECK_GE(viewport_rect.y(), 0);
DCHECK_LE(viewport_rect.right(), surface_size.width());
DCHECK_LE(viewport_rect.bottom(), surface_size.height());
bool flip_y = FlippedFramebuffer();
if (flip_y) {
frame->target_to_device_transform = gfx::OrthoProjectionTransform(
draw_rect.x(), draw_rect.right(), draw_rect.bottom(), draw_rect.y());
} else {
frame->target_to_device_transform = gfx::OrthoProjectionTransform(
draw_rect.x(), draw_rect.right(), draw_rect.y(), draw_rect.bottom());
}
gfx::Rect window_rect = viewport_rect;
if (flip_y)
window_rect.set_y(surface_size.height() - viewport_rect.bottom());
frame->target_to_device_transform.PostConcat(
gfx::WindowTransform(window_rect.x(), window_rect.y(),
window_rect.width(), window_rect.height()));
current_draw_rect_ = draw_rect;
current_viewport_rect_ = viewport_rect;
current_surface_size_ = surface_size;
current_window_space_viewport_ = window_rect;
}
gfx::Rect DirectRenderer::MoveFromDrawToWindowSpace(
const gfx::Rect& draw_rect) const {
gfx::Rect window_rect = draw_rect;
window_rect -= current_draw_rect_.OffsetFromOrigin();
window_rect += current_viewport_rect_.OffsetFromOrigin();
if (FlippedFramebuffer())
window_rect.set_y(current_surface_size_.height() - window_rect.bottom());
return window_rect;
}
const DrawQuad* DirectRenderer::CanPassBeDrawnDirectly(
const AggregatedRenderPass* pass) {
return nullptr;
}
void DirectRenderer::SetVisible(bool visible) {
DCHECK(initialized_);
if (visible_ == visible)
return;
visible_ = visible;
DidChangeVisibility();
}
void DirectRenderer::ReallocatedFrameBuffers() {
next_frame_needs_full_frame_redraw_ = true;
}
void DirectRenderer::Reshape(
const OutputSurface::ReshapeParams& reshape_params) {
output_surface_->Reshape(reshape_params);
}
void DirectRenderer::DecideRenderPassAllocationsForFrame(
const AggregatedRenderPassList& render_passes_in_draw_order) {
DCHECK(render_pass_bypass_quads_.empty());
auto& root_render_pass = render_passes_in_draw_order.back();
base::flat_map<AggregatedRenderPassId, RenderPassRequirements>
render_passes_in_frame;
for (const auto& pass : render_passes_in_draw_order) {
// If there's a copy request, we need an explicit renderpass backing so
// only try to draw directly if there are no copy requests.
bool is_root = pass == root_render_pass;
if (!is_root && pass->copy_requests.empty()) {
if (const DrawQuad* quad = CanPassBeDrawnDirectly(pass.get())) {
// If the render pass is drawn directly, it will not be drawn from as
// a render pass so it's not added to the map.
render_pass_bypass_quads_[pass->id] = quad;
continue;
}
}
render_passes_in_frame[pass->id] =
CalculateRenderPassRequirements(pass.get());
}
UMA_HISTOGRAM_COUNTS_1000(
"Compositing.Display.FlattenedRenderPassCount",
base::saturated_cast<int>(render_passes_in_draw_order.size() -
render_pass_bypass_quads_.size()));
UpdateRenderPassTextures(render_passes_in_draw_order, render_passes_in_frame);
}
void DirectRenderer::DrawFrame(
AggregatedRenderPassList* render_passes_in_draw_order,
float device_scale_factor,
const gfx::Size& device_viewport_size,
const gfx::DisplayColorSpaces& display_color_spaces,
SurfaceDamageRectList surface_damage_rect_list) {
DCHECK(visible_);
TRACE_EVENT0("viz,benchmark", "DirectRenderer::DrawFrame");
UMA_HISTOGRAM_COUNTS_1M(
"Renderer4.renderPassCount",
base::saturated_cast<int>(render_passes_in_draw_order->size()));
auto* root_render_pass = render_passes_in_draw_order->back().get();
DCHECK(root_render_pass);
current_frame_valid_ = true;
current_frame_ = DrawingFrame();
current_frame()->render_passes_in_draw_order = render_passes_in_draw_order;
current_frame()->root_render_pass = root_render_pass;
current_frame()->root_damage_rect = root_render_pass->damage_rect;
if (overlay_processor_) {
current_frame()->root_damage_rect.Union(
overlay_processor_->GetAndResetOverlayDamage());
}
if (auto* ink_renderer =
GetDelegatedInkPointRenderer(/*create_if_necessary=*/false)) {
// The path must be finalized before GetDamageRect() can return an accurate
// rect that will allow the old trail to be removed and the new trail to
// be drawn at the same time.
ink_renderer->FinalizePathForDraw();
gfx::Rect delegated_ink_damage_rect = ink_renderer->GetDamageRect();
// The viewport could have changed size since the presentation area was
// created and propagated, such as if is window was resized. Intersect the
// viewport here to ensure the damage rect doesn't extend beyond the current
// viewport.
delegated_ink_damage_rect.Intersect(gfx::Rect(device_viewport_size));
current_frame()->root_damage_rect.Union(delegated_ink_damage_rect);
}
current_frame()->root_damage_rect.Intersect(gfx::Rect(device_viewport_size));
current_frame()->device_viewport_size = device_viewport_size;
current_frame()->display_color_spaces = display_color_spaces;
output_surface_->SetNeedsMeasureNextDrawLatency();
BeginDrawingFrame();
// RenderPass owns filters, backdrop_filters, etc., and will outlive this
// function call. So it is safe to store pointers in these maps.
for (const auto& pass : *render_passes_in_draw_order) {
if (!pass->filters.IsEmpty()) {
render_pass_filters_[pass->id] = &pass->filters;
if (pass->filters.HasFilterThatMovesPixels())
has_pixel_moving_foreground_filters_ = true;
}
if (!pass->backdrop_filters.IsEmpty()) {
render_pass_backdrop_filters_[pass->id] = &pass->backdrop_filters;
render_pass_backdrop_filter_bounds_[pass->id] =
pass->backdrop_filter_bounds;
if (pass->backdrop_filters.HasFilterThatMovesPixels()) {
backdrop_filter_output_rects_[pass->id] =
cc::MathUtil::MapEnclosingClippedRect(
pass->transform_to_root_target, pass->output_rect);
}
}
}
bool frame_has_alpha =
current_frame()->root_render_pass->has_transparent_background;
gfx::ColorSpace frame_color_space = RootRenderPassColorSpace();
gfx::BufferFormat frame_buffer_format =
current_frame()->display_color_spaces.GetOutputBufferFormat(
current_frame()->root_render_pass->content_color_usage,
frame_has_alpha);
gfx::Size surface_resource_size =
CalculateSizeForOutputSurface(device_viewport_size);
if (overlay_processor_) {
// Display transform and viewport size are needed for overlay validator on
// Android SurfaceControl, and viewport size is need on Windows. These need
// to be called before ProcessForOverlays.
overlay_processor_->SetDisplayTransformHint(
output_surface_->GetDisplayTransform());
overlay_processor_->SetViewportSize(device_viewport_size);
// Before ProcessForOverlay calls into the hardware to ask about whether the
// overlay setup can be handled, we need to set up the primary plane.
OverlayProcessorInterface::OutputSurfaceOverlayPlane* primary_plane =
nullptr;
if (output_surface_->IsDisplayedAsOverlayPlane()) {
current_frame()->output_surface_plane =
overlay_processor_->ProcessOutputSurfaceAsOverlay(
device_viewport_size, surface_resource_size, frame_buffer_format,
frame_color_space, frame_has_alpha, 1.0f /*opacity*/,
GetPrimaryPlaneOverlayTestingMailbox());
primary_plane = &(current_frame()->output_surface_plane.value());
}
// Attempt to replace some or all of the quads of the root render pass with
// overlays.
base::ElapsedTimer overlay_processing_timer;
overlay_processor_->ProcessForOverlays(
resource_provider_, render_passes_in_draw_order,
output_surface_->color_matrix(), render_pass_filters_,
render_pass_backdrop_filters_, std::move(surface_damage_rect_list),
primary_plane, ¤t_frame()->overlay_list,
¤t_frame()->root_damage_rect,
¤t_frame()->root_content_bounds);
auto overlay_processing_time = overlay_processing_timer.Elapsed();
constexpr auto kMinTime = base::Microseconds(5);
constexpr auto kMaxTime = base::Milliseconds(10);
constexpr int kTimeBuckets = 50;
UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
"Compositing.DirectRenderer.OverlayProcessingUs",
overlay_processing_time, kMinTime, kMaxTime, kTimeBuckets);
// If we promote any quad to an underlay then the main plane must support
// alpha.
// TODO(ccameron): We should update |frame_color_space|, and
// |frame_buffer_format| based on the change in |frame_has_alpha|.
if (current_frame()->output_surface_plane) {
frame_has_alpha |= current_frame()->output_surface_plane->enable_blending;
root_render_pass->has_transparent_background = frame_has_alpha;
}
overlay_processor_->AdjustOutputSurfaceOverlay(
&(current_frame()->output_surface_plane));
}
// Only reshape when we know we are going to draw. Otherwise, the reshape
// can leave the window at the wrong size if we never draw and the proper
// viewport size is never set.
skipped_render_pass_ids_.clear();
bool needs_full_frame_redraw = false;
auto display_transform = output_surface_->GetDisplayTransform();
OutputSurface::ReshapeParams reshape_params;
reshape_params.size = surface_resource_size;
reshape_params.device_scale_factor = device_scale_factor;
reshape_params.color_space = frame_color_space;
reshape_params.sdr_white_level = CurrentFrameSDRWhiteLevel();
reshape_params.format = frame_buffer_format;
reshape_params.alpha_type =
frame_has_alpha ? kPremul_SkAlphaType : kOpaque_SkAlphaType;
if (next_frame_needs_full_frame_redraw_ ||
reshape_params != reshape_params_ ||
display_transform != reshape_display_transform_) {
next_frame_needs_full_frame_redraw_ = false;
reshape_params_ = reshape_params;
reshape_display_transform_ = display_transform;
Reshape(reshape_params);
#if BUILDFLAG(IS_APPLE)
// For Mac, all render passes will be promoted to CALayer, the redraw full
// frame is for the main surface only.
// TODO(penghuang): verify this logic with SkiaRenderer.
if (!output_surface_->capabilities().supports_surfaceless)
needs_full_frame_redraw = true;
#elif BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN)
// If compositing is delegated, then there will be no output_surface_plane,
// and we should not trigger a redraw of the root render pass.
// Pixel tests will not be displayed as overlay planes, so they need redraw.
if (current_frame()->output_surface_plane ||
!output_surface_->IsDisplayedAsOverlayPlane()) {
needs_full_frame_redraw = true;
}
#else
// The entire surface has to be redrawn if reshape is requested.
needs_full_frame_redraw = true;
#endif
}
// DecideRenderPassAllocationsForFrame needs
// current_frame()->display_color_spaces to decide the color space
// of each render pass. Overlay processing is also allowed to modify the
// render pass backing requirements due to e.g. a underlay promotion. On
// Windows, the root render pass' size is based on the |reshape_params_|.
DecideRenderPassAllocationsForFrame(*render_passes_in_draw_order);
// Draw all non-root render passes except for the root render pass.
for (const auto& pass : *render_passes_in_draw_order) {
if (pass.get() == root_render_pass)
break;
DrawRenderPassAndExecuteCopyRequests(pass.get());
}
bool skip_drawing_root_render_pass =
current_frame()->root_damage_rect.IsEmpty() && use_partial_swap_ &&
!needs_full_frame_redraw;
// If partial swap is not used, and the frame can not be skipped, the whole
// frame has to be redrawn.
if (!use_partial_swap_ && !skip_drawing_root_render_pass)
needs_full_frame_redraw = true;
// If we need to redraw the frame, the whole output should be considered
// damaged.
if (needs_full_frame_redraw)
current_frame()->root_damage_rect = gfx::Rect(device_viewport_size);
if (!skip_drawing_root_render_pass)
DrawRenderPassAndExecuteCopyRequests(root_render_pass);
if (overlay_processor_)
overlay_processor_->TakeOverlayCandidates(¤t_frame()->overlay_list);
FinishDrawingFrame();
if (overlay_processor_)
overlay_processor_->ScheduleOverlays(resource_provider_);
// Total non-root render pass count, excluding root render pass and bypassed
// render passes.
auto nonroot_render_pass_count = render_passes_in_draw_order->size() - 1 -
render_pass_bypass_quads_.size();
if (nonroot_render_pass_count > 0) {
UMA_HISTOGRAM_BOOLEAN(
"Compositing.DirectRenderer.SkipAllNonRootRenderPassesPerFrame",
skipped_render_pass_ids_.size() == nonroot_render_pass_count);
}
// The current drawing frame is valid only during the duration of this
// function. Clear the pointers held inside to avoid holding dangling
// pointers.
current_frame()->render_passes_in_draw_order = nullptr;
current_frame()->root_render_pass = nullptr;
render_passes_in_draw_order->clear();
render_pass_filters_.clear();
render_pass_backdrop_filters_.clear();
render_pass_backdrop_filter_bounds_.clear();
render_pass_bypass_quads_.clear();
backdrop_filter_output_rects_.clear();
has_pixel_moving_foreground_filters_ = false;
current_frame_valid_ = false;
}
gfx::Rect DirectRenderer::GetCurrentFramebufferDamage() const {
return output_surface_->GetCurrentFramebufferDamage();
}
gfx::Rect DirectRenderer::GetTargetDamageBoundingRect() const {
gfx::Rect bounding_rect = GetCurrentFramebufferDamage();
if (overlay_processor_) {
bounding_rect.Union(
overlay_processor_->GetPreviousFrameOverlaysBoundingRect());
}
return bounding_rect;
}
gfx::Rect DirectRenderer::DeviceViewportRectInDrawSpace() const {
gfx::Rect device_viewport_rect(current_frame()->device_viewport_size);
device_viewport_rect -= current_viewport_rect_.OffsetFromOrigin();
device_viewport_rect += current_draw_rect_.OffsetFromOrigin();
return device_viewport_rect;
}
gfx::Rect DirectRenderer::OutputSurfaceRectInDrawSpace() const {
if (current_frame()->current_render_pass ==
current_frame()->root_render_pass) {
return DeviceViewportRectInDrawSpace();
} else {
return current_frame()->current_render_pass->output_rect;
}
}
bool DirectRenderer::ShouldSkipQuad(const DrawQuad& quad,
const gfx::Rect& render_pass_scissor) {
if (render_pass_scissor.IsEmpty())
return true;
gfx::Rect target_rect = cc::MathUtil::MapEnclosingClippedRect(
quad.shared_quad_state->quad_to_target_transform, quad.visible_rect);
if (quad.shared_quad_state->clip_rect)
target_rect.Intersect(*quad.shared_quad_state->clip_rect);
target_rect.Intersect(render_pass_scissor);
return target_rect.IsEmpty();
}
void DirectRenderer::SetScissorStateForQuad(
const DrawQuad& quad,
const gfx::Rect& render_pass_scissor,
bool use_render_pass_scissor) {
if (use_render_pass_scissor) {
gfx::Rect quad_scissor_rect = render_pass_scissor;
if (quad.shared_quad_state->clip_rect)
quad_scissor_rect.Intersect(*quad.shared_quad_state->clip_rect);
SetScissorTestRectInDrawSpace(quad_scissor_rect);
return;
} else if (quad.shared_quad_state->clip_rect) {
SetScissorTestRectInDrawSpace(*quad.shared_quad_state->clip_rect);
return;
}
EnsureScissorTestDisabled();
}
void DirectRenderer::SetScissorTestRectInDrawSpace(
const gfx::Rect& draw_space_rect) {
gfx::Rect window_space_rect = MoveFromDrawToWindowSpace(draw_space_rect);
SetScissorTestRect(window_space_rect);
}
void DirectRenderer::DoDrawPolygon(const DrawPolygon& poly,
const gfx::Rect& render_pass_scissor,
bool use_render_pass_scissor) {
SetScissorStateForQuad(*poly.original_ref(), render_pass_scissor,
use_render_pass_scissor);
// If the poly has not been split, then it is just a normal DrawQuad,
// and we should save any extra processing that would have to be done.
if (!poly.is_split()) {
DoDrawQuad(poly.original_ref(), nullptr);
return;
}
std::vector<gfx::QuadF> quads;
poly.ToQuads2D(&quads);
for (size_t i = 0; i < quads.size(); ++i) {
DoDrawQuad(poly.original_ref(), &quads[i]);
}
}
const cc::FilterOperations* DirectRenderer::FiltersForPass(
AggregatedRenderPassId render_pass_id) const {
auto it = render_pass_filters_.find(render_pass_id);
return it == render_pass_filters_.end() ? nullptr : it->second;
}
const cc::FilterOperations* DirectRenderer::BackdropFiltersForPass(
AggregatedRenderPassId render_pass_id) const {
auto it = render_pass_backdrop_filters_.find(render_pass_id);
return it == render_pass_backdrop_filters_.end() ? nullptr : it->second;
}
const absl::optional<gfx::RRectF> DirectRenderer::BackdropFilterBoundsForPass(
AggregatedRenderPassId render_pass_id) const {
auto it = render_pass_backdrop_filter_bounds_.find(render_pass_id);
return it == render_pass_backdrop_filter_bounds_.end()
? absl::optional<gfx::RRectF>()
: it->second;
}
void DirectRenderer::FlushPolygons(
base::circular_deque<std::unique_ptr<DrawPolygon>>* poly_list,
const gfx::Rect& render_pass_scissor,
bool use_render_pass_scissor) {
if (poly_list->empty()) {
return;
}
BspTree bsp_tree(poly_list);
BspWalkActionDrawPolygon action_handler(this, render_pass_scissor,
use_render_pass_scissor);
bsp_tree.TraverseWithActionHandler(&action_handler);
DCHECK(poly_list->empty());
}
void DirectRenderer::DrawRenderPassAndExecuteCopyRequests(
AggregatedRenderPass* render_pass) {
if (render_pass_bypass_quads_.find(render_pass->id) !=
render_pass_bypass_quads_.end()) {
return;
}
// Repeated draw to simulate a slower device for the evaluation of performance
// improvements in UI effects.
for (int i = 0; i < settings_->slow_down_compositing_scale_factor; ++i)
DrawRenderPass(render_pass);
for (auto& request : render_pass->copy_requests) {
// Finalize the source subrect (output_rect, result_bounds,
// sampling_bounds), as the entirety of the RenderPass's output optionally
// clamped to the requested copy area. Then, compute the result rect
// (result_selection), which is the selection clamped to the maximum
// possible result bounds. If there will be zero pixels of output or the
// scaling ratio was not reasonable, do not proceed.
gfx::Rect output_rect = render_pass->output_rect;
if (request->has_area())
output_rect.Intersect(request->area());
copy_output::RenderPassGeometry geometry;
geometry.result_bounds =
request->is_scaled() ? copy_output::ComputeResultRect(
gfx::Rect(output_rect.size()),
request->scale_from(), request->scale_to())
: gfx::Rect(output_rect.size());
// Result bounds may not satisfy the pixel format requirements for the
// CopyOutputRequest - we need to adjust them to something that will be
// compatible. Formats other than RGBA have this restriction.
geometry.result_selection =
request->result_format() == CopyOutputRequest::ResultFormat::RGBA
? geometry.result_bounds
: media::MinimallyShrinkRectForI420(geometry.result_bounds);
if (request->has_result_selection())
geometry.result_selection.Intersect(request->result_selection());
if (geometry.result_selection.IsEmpty())
continue;
geometry.sampling_bounds = MoveFromDrawToWindowSpace(output_rect);
geometry.readback_offset =
MoveFromDrawToWindowSpace(geometry.result_selection +
output_rect.OffsetFromOrigin())
.OffsetFromOrigin();
CopyDrawnRenderPass(geometry, std::move(request));
}
}
void DirectRenderer::DrawRenderPass(const AggregatedRenderPass* render_pass) {
TRACE_EVENT0("viz", "DirectRenderer::DrawRenderPass");
bool can_skip_rp = CanSkipRenderPass(render_pass);
if (render_pass != current_frame()->root_render_pass) {
UMA_HISTOGRAM_BOOLEAN("Compositing.DirectRenderer.SkipNonRootRenderPass",
can_skip_rp);
}
if (can_skip_rp) {
skipped_render_pass_ids_.insert(render_pass->id);
int pixel_size =
render_pass->output_rect.width() * render_pass->output_rect.height();
UMA_HISTOGRAM_COUNTS_10M(
"Compositing.DirectRenderer.SkippedNonRootRenderPassOutputSize",
pixel_size);
return;
}
UseRenderPass(render_pass);
// TODO(crbug.com/582554): This change applies only when Vulkan is enabled and
// it will be removed once SkiaRenderer has complete support for Vulkan.
if (current_frame()->current_render_pass !=
current_frame()->root_render_pass &&
!IsRenderPassResourceAllocated(render_pass->id))
return;
const gfx::Rect surface_rect_in_draw_space = OutputSurfaceRectInDrawSpace();
gfx::Rect render_pass_scissor_in_draw_space = surface_rect_in_draw_space;
bool is_root_render_pass =
current_frame()->current_render_pass == current_frame()->root_render_pass;
if (use_partial_swap_) {
render_pass_scissor_in_draw_space.Intersect(
ComputeScissorRectForRenderPass(current_frame()->current_render_pass));
}
const bool render_pass_is_clipped =
!render_pass_scissor_in_draw_space.Contains(surface_rect_in_draw_space);
// The SetDrawRectangleCHROMIUM spec requires that the scissor bit is always
// set on the root framebuffer or else the rendering may modify something
// outside the damage rectangle, even if the damage rectangle is the size of
// the full backbuffer.
const bool supports_dc_layers =
output_surface_->capabilities().supports_dc_layers;
const bool render_pass_requires_scissor =
render_pass_is_clipped || (supports_dc_layers && is_root_render_pass);
const bool should_clear_surface =
!is_root_render_pass || settings_->should_clear_root_render_pass;
const gfx::Rect render_pass_update_rect = MoveFromDrawToWindowSpace(
render_pass_requires_scissor ? render_pass_scissor_in_draw_space
: surface_rect_in_draw_space);
BeginDrawingRenderPass(should_clear_surface, render_pass_update_rect);
if (is_root_render_pass)
last_root_render_pass_scissor_rect_ = render_pass_scissor_in_draw_space;
const QuadList& quad_list = render_pass->quad_list;
base::circular_deque<std::unique_ptr<DrawPolygon>> poly_list;
int next_polygon_id = 0;
int last_sorting_context_id = 0;
for (auto it = quad_list.BackToFrontBegin(); it != quad_list.BackToFrontEnd();
++it) {
const DrawQuad& quad = **it;
if (ShouldSkipQuad(quad, render_pass_is_clipped
? render_pass_scissor_in_draw_space
: surface_rect_in_draw_space)) {
continue;
}
if (last_sorting_context_id != quad.shared_quad_state->sorting_context_id) {
last_sorting_context_id = quad.shared_quad_state->sorting_context_id;
FlushPolygons(&poly_list, render_pass_scissor_in_draw_space,
render_pass_requires_scissor);
}
// This layer is in a 3D sorting context so we add it to the list of
// polygons to go into the BSP tree.
if (quad.shared_quad_state->sorting_context_id != 0) {
// TODO(danakj): It's sad to do a malloc here to compare. Maybe construct
// this on the stack and move it into the list.
auto new_polygon = std::make_unique<DrawPolygon>(
*it, gfx::RectF(quad.visible_rect),
quad.shared_quad_state->quad_to_target_transform, next_polygon_id++);
if (new_polygon->normal().LengthSquared() > 0.0) {
poly_list.push_back(std::move(new_polygon));
}
continue;
}
// We are not in a 3d sorting context, so we should draw the quad normally.
SetScissorStateForQuad(quad, render_pass_scissor_in_draw_space,
render_pass_requires_scissor);
if (OverlayCandidate::RequiresOverlay(&quad)) {
// We cannot composite this quad properly, replace it with solid black.
SolidColorDrawQuad solid_black;
solid_black.SetAll(quad.shared_quad_state, quad.rect, quad.rect,
/*needs_blending=*/false, SkColors::kBlack,
/*force_anti_aliasing_off=*/true);
DoDrawQuad(&solid_black, nullptr);
continue;
}
DoDrawQuad(&quad, nullptr);
}
FlushPolygons(&poly_list, render_pass_scissor_in_draw_space,
render_pass_requires_scissor);
FinishDrawingRenderPass();
if (render_pass->generate_mipmap)
GenerateMipmap();
}
bool DirectRenderer::CanSkipRenderPass(
const AggregatedRenderPass* render_pass) const {
if (render_pass == current_frame()->root_render_pass)
return false;
// If the RenderPass wants to be cached, then we only draw it if we need to.
// When damage is present, then we can't skip the RenderPass. Or if the
// texture does not exist (first frame, or was deleted) then we can't skip
// the RenderPass.
if (render_pass->cache_render_pass ||
allow_undamaged_nonroot_render_pass_to_skip_) {
// TODO(crbug.com/1346502): Fix CopyOutputRequest and allow the render pass
// with copy request to skip.
if (render_pass->has_damage_from_contributing_content ||
!render_pass->copy_requests.empty()) {
return false;
}
return IsRenderPassResourceAllocated(render_pass->id);
}
return false;
}
DirectRenderer::RenderPassRequirements
DirectRenderer::CalculateRenderPassRequirements(
const AggregatedRenderPass* render_pass) const {
bool is_root = render_pass == current_frame()->root_render_pass;
RenderPassRequirements requirements;
if (is_root) {
requirements.size = surface_size_for_swap_buffers();
requirements.generate_mipmap = false;
requirements.color_space = reshape_color_space();
requirements.format = GetResourceFormat(reshape_buffer_format());
// All root render pass backings allocated by the renderer needs to
// eventually go into some composition tree. Other things that own/allocate
// the root pass backing include the output device and buffer queue.
requirements.is_scanout = true;
#if BUILDFLAG(IS_WIN)
requirements.scanout_dcomp_surface =
render_pass->needs_synchronous_dcomp_commit;
// On Windows, the root render pass can be made transparent due to overlay
// processing promoting a quad as an underlay. If the format we picked does
// not have alpha bits, we ned to change to one that does.
if (render_pass->has_transparent_background &&
AlphaBits(requirements.format) == 0) {
requirements.format =
GetColorSpaceResourceFormat(requirements.color_space);
}
#endif
} else {
requirements.size = CalculateTextureSizeForRenderPass(render_pass);
requirements.generate_mipmap = render_pass->generate_mipmap;
requirements.color_space = RenderPassColorSpace(render_pass);
requirements.format = GetColorSpaceResourceFormat(requirements.color_space);
}
if (render_pass->has_transparent_background) {
DCHECK_GT(AlphaBits(requirements.format), 0);
}
return requirements;
}
void DirectRenderer::UseRenderPass(const AggregatedRenderPass* render_pass) {
bool is_root = render_pass == current_frame()->root_render_pass;
current_frame()->current_render_pass = render_pass;
// The root render pass will be either bound to the buffer allocated by
// the SkiaOutputSurface, or if the renderer allocatates images then the root
// render pass buffer will be allocated in
// AllocateRenderPassResourceIfNeeded(), and bound in
// BindFramebufferToTexture().
if (is_root && !output_surface_->capabilities().renderer_allocates_images) {
BindFramebufferToOutputSurface();
if (output_surface_->capabilities().supports_dc_layers)
output_surface_->SetDrawRectangle(current_frame()->root_damage_rect);
InitializeViewport(current_frame(), render_pass->output_rect,
gfx::Rect(current_frame()->device_viewport_size),
current_frame()->device_viewport_size);
return;
}
DirectRenderer::RenderPassRequirements requirements =
CalculateRenderPassRequirements(render_pass);
// We should not change the buffer size for the root render pass.
if (!is_root) {
requirements.size.Enlarge(enlarge_pass_texture_amount_.width(),
enlarge_pass_texture_amount_.height());
}
AllocateRenderPassResourceIfNeeded(render_pass->id, requirements);
// TODO(crbug.com/582554): This change applies only when Vulkan is enabled and
// it will be removed once SkiaRenderer has complete support for Vulkan.
if (!IsRenderPassResourceAllocated(render_pass->id))
return;
BindFramebufferToTexture(render_pass->id);
InitializeViewport(current_frame(), render_pass->output_rect,
gfx::Rect(render_pass->output_rect.size()),
// If the render pass backing is cached, we might have
// bigger size comparing to the size that was generated.
GetRenderPassBackingPixelSize(render_pass->id));
}
gfx::Rect DirectRenderer::ComputeScissorRectForRenderPass(
const AggregatedRenderPass* render_pass) const {
const AggregatedRenderPass* root_render_pass =
current_frame()->root_render_pass;
gfx::Rect root_damage_rect = current_frame()->root_damage_rect;
// If |frame_buffer_damage|, which is carried over from the previous frame
// when we want to preserve buffer content, is not empty, we should add it
// to both root and non-root render passes.
gfx::Rect frame_buffer_damage = GetCurrentFramebufferDamage();
if (render_pass == root_render_pass) {
base::CheckedNumeric<int64_t> display_area =
current_frame()->device_viewport_size.GetCheckedArea();
base::CheckedNumeric<int64_t> root_damage_area =
root_damage_rect.size().GetCheckedArea();
if (display_area.IsValid() && root_damage_area.IsValid()) {
DCHECK_GT(static_cast<int64_t>(display_area.ValueOrDie()), 0);
{
base::CheckedNumeric<int64_t> frame_buffer_damage_area =
frame_buffer_damage.size().GetCheckedArea();
int64_t percentage = ((frame_buffer_damage_area * 100ll) / display_area)
.ValueOrDefault(INT_MAX);
UMA_HISTOGRAM_PERCENTAGE(
"Compositing.DirectRenderer.PartialSwap.FrameBufferDamage",
percentage);
}
{
int64_t percentage =
((root_damage_area * 100ll) / display_area).ValueOrDie();
UMA_HISTOGRAM_PERCENTAGE(
"Compositing.DirectRenderer.PartialSwap.RootDamage", percentage);
}
root_damage_rect.Union(frame_buffer_damage);
// If the root damage rect intersects any child render pass that has a
// pixel-moving backdrop filter, expand the damage to include the entire
// child pass. See crbug.com/986206 for context.
if ((!backdrop_filter_output_rects_.empty() ||
has_pixel_moving_foreground_filters_) &&
!root_damage_rect.IsEmpty()) {
for (auto* quad : root_render_pass->quad_list) {
// Sanity check: we should not have a Compositor
// CompositorRenderPassDrawQuad here.
DCHECK_NE(quad->material, DrawQuad::Material::kCompositorRenderPass);
if (auto* rpdq = quad->DynamicCast<AggregatedRenderPassDrawQuad>()) {
// For render pass with pixel moving backdrop filters.
if (auto iter =
backdrop_filter_output_rects_.find(rpdq->render_pass_id);
iter != backdrop_filter_output_rects_.end()) {
gfx::Rect this_output_rect = iter->second;
if (root_damage_rect.Intersects(this_output_rect))
root_damage_rect.Union(this_output_rect);
}
// For render pass with pixel moving foreground filters.
const cc::FilterOperations* foreground_filters =
FiltersForPass(rpdq->render_pass_id);
if (foreground_filters &&
foreground_filters->HasFilterThatMovesPixels()) {
gfx::Rect expanded_rect =
GetExpandedRectWithPixelMovingForegroundFilter(
*rpdq, *foreground_filters);
if (root_damage_rect.Intersects(expanded_rect))
root_damage_rect.Union(expanded_rect);
}
}
}
}
// Total damage after all adjustments.
base::CheckedNumeric<int64_t> total_damage_area =
root_damage_rect.size().GetCheckedArea();
{
int64_t percentage = ((total_damage_area * 100ll) / display_area)
.ValueOrDefault(INT_MAX);
UMA_HISTOGRAM_PERCENTAGE(
"Compositing.DirectRenderer.PartialSwap.TotalDamage", percentage);
}
{
int64_t percentage =
(((total_damage_area - root_damage_area) * 100ll) / display_area)
.ValueOrDefault(INT_MAX);
UMA_HISTOGRAM_PERCENTAGE(
"Compositing.DirectRenderer.PartialSwap.ExtraDamage", percentage);
}
}
return root_damage_rect;
}
// If the root damage rect has been expanded due to overlays, all the other
// damage rect calculations are incorrect.
if (!root_render_pass->damage_rect.Contains(root_damage_rect))
return render_pass->output_rect;
DCHECK(render_pass->copy_requests.empty() ||
(render_pass->damage_rect == render_pass->output_rect));
// For the non-root render pass.
gfx::Rect damage_rect = render_pass->damage_rect;
if (!frame_buffer_damage.IsEmpty()) {
gfx::Transform inverse_transform;
if (render_pass->transform_to_root_target.GetInverse(&inverse_transform)) {
// |frame_buffer_damage| is in the root target space. Transform the damage
// from the root to the non-root space before it's added.
gfx::Rect frame_buffer_damage_in_render_pass_space =
cc::MathUtil::MapEnclosingClippedRect(inverse_transform,
frame_buffer_damage);
damage_rect.Union(frame_buffer_damage_in_render_pass_space);
}
}
return damage_rect;
}
gfx::Size DirectRenderer::CalculateTextureSizeForRenderPass(
const AggregatedRenderPass* render_pass) const {
// Round the size of the render pass backings to a multiple of 64 pixels. This
// reduces memory fragmentation. https://crbug.com/146070. This also allows
// backings to be more easily reused during a resize operation.
int width = render_pass->output_rect.width();
int height = render_pass->output_rect.height();
if (!settings_->dont_round_texture_sizes_for_pixel_tests) {
constexpr int multiple = 64;
width = cc::MathUtil::CheckedRoundUp(width, multiple);
height = cc::MathUtil::CheckedRoundUp(height, multiple);
}
return gfx::Size(width, height);
}
// TODO(fangzhoug): There should be metrics recording the amount of unused
// buffer area and number of reallocations to quantify the trade-off.
gfx::Size DirectRenderer::CalculateSizeForOutputSurface(
const gfx::Size& requested_viewport_size) {
// We're not able to clip back buffers if output surface does not support
// clipping.
if (requested_viewport_size == surface_size_for_swap_buffers() ||
!output_surface_->capabilities().supports_viewporter ||
settings_->dont_round_texture_sizes_for_pixel_tests) {
device_viewport_size_ = requested_viewport_size;
return requested_viewport_size;
}
// If 1 second has passed since last |device_viewport_size_| change, shrink
// OutputSurface size to |device_viewport_size_|.
if (device_viewport_size_ == requested_viewport_size &&
(base::TimeTicks::Now() - last_viewport_resize_time_) >=