forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skia_output_surface_impl_on_gpu.cc
1860 lines (1633 loc) · 69.5 KB
/
skia_output_surface_impl_on_gpu.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 2018 The Chromium Authors. All rights reserved.
// 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_embedder/skia_output_surface_impl_on_gpu.h"
#include "base/atomic_sequence_num.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/optional.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/trace_event.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/resources/resource_format_utils.h"
#include "components/viz/common/skia_helper.h"
#include "components/viz/common/viz_utils.h"
#include "components/viz/service/display/dc_layer_overlay.h"
#include "components/viz/service/display/gl_renderer_copier.h"
#include "components/viz/service/display/output_surface_frame.h"
#include "components/viz/service/display/overlay_candidate.h"
#include "components/viz/service/display/texture_deleter.h"
#include "components/viz/service/display_embedder/direct_context_provider.h"
#include "components/viz/service/display_embedder/image_context_impl.h"
#include "components/viz/service/display_embedder/output_presenter_gl.h"
#include "components/viz/service/display_embedder/skia_output_device.h"
#include "components/viz/service/display_embedder/skia_output_device_buffer_queue.h"
#include "components/viz/service/display_embedder/skia_output_device_gl.h"
#include "components/viz/service/display_embedder/skia_output_device_offscreen.h"
#include "components/viz/service/display_embedder/skia_output_device_webview.h"
#include "components/viz/service/display_embedder/skia_output_surface_dependency.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "gpu/command_buffer/common/swap_buffers_complete_params.h"
#include "gpu/command_buffer/service/context_state.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder_passthrough.h"
#include "gpu/command_buffer/service/gr_shader_cache.h"
#include "gpu/command_buffer/service/mailbox_manager.h"
#include "gpu/command_buffer/service/memory_tracking.h"
#include "gpu/command_buffer/service/scheduler.h"
#include "gpu/command_buffer/service/service_utils.h"
#include "gpu/command_buffer/service/shared_image_factory.h"
#include "gpu/command_buffer/service/shared_image_representation.h"
#include "gpu/command_buffer/service/skia_utils.h"
#include "gpu/command_buffer/service/texture_base.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "gpu/config/gpu_preferences.h"
#include "gpu/ipc/common/command_buffer_id.h"
#include "gpu/ipc/common/gpu_client_ids.h"
#include "gpu/ipc/common/gpu_peak_memory.h"
#include "gpu/ipc/common/gpu_surface_lookup.h"
#include "gpu/vulkan/buildflags.h"
#include "skia/buildflags.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkDeferredDisplayList.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_gl_api_implementation.h"
#include "ui/gl/gl_surface.h"
#include "ui/gl/gl_version_info.h"
#include "ui/gl/init/gl_factory.h"
#if BUILDFLAG(ENABLE_VULKAN)
#include "components/viz/service/display_embedder/skia_output_device_vulkan.h"
#include "gpu/vulkan/vulkan_util.h"
#endif
#if (BUILDFLAG(ENABLE_VULKAN) || BUILDFLAG(SKIA_USE_DAWN)) && defined(USE_X11)
#include "components/viz/service/display_embedder/skia_output_device_x11.h"
#endif
#if defined(USE_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_window_surface.h"
#include "ui/ozone/public/surface_factory_ozone.h"
#endif
#if BUILDFLAG(SKIA_USE_DAWN)
#include "components/viz/common/gpu/dawn_context_provider.h"
#if defined(OS_WIN)
#include "components/viz/service/display_embedder/skia_output_device_dawn.h"
#endif
#endif
#if defined(USE_OZONE) || defined(USE_X11)
#include "ui/base/ui_base_features.h"
#endif
#if defined(OS_FUCHSIA)
#include "components/viz/service/display_embedder/output_presenter_fuchsia.h"
#endif
namespace viz {
namespace {
constexpr base::TimeDelta kReadbackPollingInterval =
base::TimeDelta::FromMilliseconds(2);
template <typename... Args>
void PostAsyncTaskRepeatedly(
base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu,
const base::RepeatingCallback<void(Args...)>& callback,
Args... args) {
// Callbacks generated by this function may be executed asynchronously
// (e.g. by presentation feedback) after |impl_on_gpu| has been destroyed.
if (impl_on_gpu)
impl_on_gpu->PostTaskToClientThread(base::BindOnce(callback, args...));
}
template <typename... Args>
base::RepeatingCallback<void(Args...)> CreateSafeRepeatingCallback(
base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu,
const base::RepeatingCallback<void(Args...)>& callback) {
return base::BindRepeating(&PostAsyncTaskRepeatedly<Args...>, impl_on_gpu,
callback);
}
struct ReadPixelsContext {
ReadPixelsContext(std::unique_ptr<CopyOutputRequest> request,
const gfx::Rect& result_rect,
const gfx::ColorSpace& color_space,
base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu)
: request(std::move(request)),
result_rect(result_rect),
color_space(color_space),
impl_on_gpu(impl_on_gpu) {}
std::unique_ptr<CopyOutputRequest> request;
gfx::Rect result_rect;
gfx::ColorSpace color_space;
base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu;
};
class SharedImageSubMemoryTracker : public gpu::MemoryTracker {
public:
SharedImageSubMemoryTracker(gpu::CommandBufferId command_buffer_id,
uint64_t client_tracing_id,
Observer* observer)
: command_buffer_id_(command_buffer_id),
client_tracing_id_(client_tracing_id),
observer_(observer) {}
SharedImageSubMemoryTracker(const SharedImageSubMemoryTracker&) = delete;
SharedImageSubMemoryTracker& operator=(const SharedImageSubMemoryTracker&) =
delete;
~SharedImageSubMemoryTracker() override { DCHECK(!size_); }
// MemoryTracker implementation:
void TrackMemoryAllocatedChange(int64_t delta) override {
DCHECK(delta >= 0 || size_ >= static_cast<uint64_t>(-delta));
uint64_t old_size = size_;
size_ += delta;
DCHECK(observer_);
observer_->OnMemoryAllocatedChange(
command_buffer_id_, old_size, size_,
gpu::GpuPeakMemoryAllocationSource::SKIA);
}
uint64_t GetSize() const override { return size_; }
uint64_t ClientTracingId() const override { return client_tracing_id_; }
int ClientId() const override {
return gpu::ChannelIdFromCommandBufferId(command_buffer_id_);
}
uint64_t ContextGroupTracingId() const override {
return command_buffer_id_.GetUnsafeValue();
}
private:
gpu::CommandBufferId command_buffer_id_;
const uint64_t client_tracing_id_;
MemoryTracker::Observer* const observer_;
uint64_t size_ = 0;
};
class CopyOutputResultYUV : public CopyOutputResult {
public:
CopyOutputResultYUV(const gfx::Rect& rect,
std::unique_ptr<const SkSurface::AsyncReadResult> result)
: CopyOutputResult(Format::I420_PLANES, rect),
result_(std::move(result)) {
DCHECK_EQ(3, result_->count());
DCHECK_EQ(0, size().width() % 2);
DCHECK_EQ(0, size().height() % 2);
}
// CopyOutputResult implementation.
bool ReadI420Planes(uint8_t* y_out,
int y_out_stride,
uint8_t* u_out,
int u_out_stride,
uint8_t* v_out,
int v_out_stride) const override {
const auto CopyPlane = [](const uint8_t* src, int src_stride, int width,
int height, uint8_t* out, int out_stride) {
for (int i = 0; i < height; ++i, src += src_stride, out += out_stride) {
memcpy(out, src, width);
}
};
auto* data0 = static_cast<const uint8_t*>(result_->data(0));
auto* data1 = static_cast<const uint8_t*>(result_->data(1));
auto* data2 = static_cast<const uint8_t*>(result_->data(2));
CopyPlane(data0, result_->rowBytes(0), width(0), height(0), y_out,
y_out_stride);
CopyPlane(data1, result_->rowBytes(1), width(1), height(1), u_out,
u_out_stride);
CopyPlane(data2, result_->rowBytes(2), width(2), height(2), v_out,
v_out_stride);
return true;
}
private:
uint32_t width(int plane) const {
if (plane == 0)
return size().width();
else
return size().width() / 2;
}
uint32_t height(int plane) const {
if (plane == 0)
return size().height();
else
return size().height() / 2;
}
std::unique_ptr<const SkSurface::AsyncReadResult> result_;
};
void OnYUVReadbackDone(
void* c,
std::unique_ptr<const SkSurface::AsyncReadResult> async_result) {
std::unique_ptr<ReadPixelsContext> context(
static_cast<ReadPixelsContext*>(c));
if (context->impl_on_gpu)
context->impl_on_gpu->ReadbackDone();
if (!async_result) {
// This will automatically send an empty result.
return;
}
std::unique_ptr<CopyOutputResult> result =
std::make_unique<CopyOutputResultYUV>(context->result_rect,
std::move(async_result));
context->request->SendResult(std::move(result));
}
void DestroyAsyncReadResult(void* pixels, void* context) {
const SkSurface::AsyncReadResult* result =
static_cast<const SkSurface::AsyncReadResult*>(context);
delete result;
}
void OnRGBAReadbackDone(
void* c,
std::unique_ptr<const SkSurface::AsyncReadResult> async_result) {
std::unique_ptr<ReadPixelsContext> context(
static_cast<ReadPixelsContext*>(c));
if (context->impl_on_gpu)
context->impl_on_gpu->ReadbackDone();
if (!async_result) {
// This will automatically send an empty result.
return;
}
DCHECK_EQ(1, async_result->count());
auto info = SkImageInfo::MakeN32Premul(context->result_rect.width(),
context->result_rect.height(),
context->color_space.ToSkColorSpace());
// Passing ownership of |async_result| to DestroyAsyncReadResult.
auto* result_ptr = async_result.release();
SkBitmap bitmap;
bitmap.installPixels(info, const_cast<void*>(result_ptr->data(0)),
result_ptr->rowBytes(0), DestroyAsyncReadResult,
const_cast<SkSurface::AsyncReadResult*>(result_ptr));
std::unique_ptr<CopyOutputResult> result =
std::make_unique<CopyOutputSkBitmapResult>(context->result_rect, bitmap);
context->request->SendResult(std::move(result));
}
} // namespace
SkiaOutputSurfaceImplOnGpu::PromiseImageAccessHelper::PromiseImageAccessHelper(
SkiaOutputSurfaceImplOnGpu* impl_on_gpu)
: impl_on_gpu_(impl_on_gpu) {}
SkiaOutputSurfaceImplOnGpu::PromiseImageAccessHelper::
~PromiseImageAccessHelper() {
CHECK(image_contexts_.empty());
}
void SkiaOutputSurfaceImplOnGpu::PromiseImageAccessHelper::BeginAccess(
std::vector<ImageContextImpl*> image_contexts,
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores) {
DCHECK(begin_semaphores);
DCHECK(end_semaphores);
begin_semaphores->reserve(image_contexts.size());
// We may need one more space for the swap buffer semaphore.
end_semaphores->reserve(image_contexts.size() + 1);
image_contexts_.reserve(image_contexts.size() + image_contexts_.size());
image_contexts_.insert(image_contexts.begin(), image_contexts.end());
impl_on_gpu_->BeginAccessImages(std::move(image_contexts), begin_semaphores,
end_semaphores);
}
void SkiaOutputSurfaceImplOnGpu::PromiseImageAccessHelper::EndAccess() {
impl_on_gpu_->EndAccessImages(image_contexts_);
image_contexts_.clear();
}
// Skia gr_context() and |context_provider_| share an underlying GLContext.
// Each of them caches some GL state. Interleaving usage could make cached
// state inconsistent with GL state. Using a ScopedUseContextProvider whenever
// |context_provider_| could be accessed (e.g. processing completed queries),
// will keep cached state consistent with driver GL state.
class SkiaOutputSurfaceImplOnGpu::ScopedUseContextProvider {
public:
ScopedUseContextProvider(SkiaOutputSurfaceImplOnGpu* impl_on_gpu,
GLuint texture_client_id)
: impl_on_gpu_(impl_on_gpu) {
if (!impl_on_gpu_->MakeCurrent(true /* need_fbo0 */)) {
valid_ = false;
return;
}
// GLRendererCopier uses context_provider_->ContextGL(), which caches GL
// state and removes state setting calls that it considers redundant. To get
// to a known GL state, we first set driver GL state and then make client
// side consistent with that.
auto* api = impl_on_gpu_->api_;
api->glBindFramebufferEXTFn(GL_FRAMEBUFFER, 0);
auto* group = impl_on_gpu->context_provider_->decoder()->GetContextGroup();
if (group->use_passthrough_cmd_decoder()) {
// Passthrough decoding is not hooked into GLStateRestorer and we must
// manually reset the context into a known state after Skia is finished.
api->glUseProgramFn(0);
api->glActiveTextureFn(GL_TEXTURE0);
api->glBindBufferFn(GL_ARRAY_BUFFER, 0);
api->glBindTextureFn(GL_TEXTURE_2D, 0);
}
impl_on_gpu_->context_provider_->SetGLRendererCopierRequiredState(
texture_client_id);
}
~ScopedUseContextProvider() {
if (valid_)
impl_on_gpu_->gr_context()->resetContext();
}
bool valid() { return valid_; }
private:
SkiaOutputSurfaceImplOnGpu* const impl_on_gpu_;
bool valid_ = true;
DISALLOW_COPY_AND_ASSIGN(ScopedUseContextProvider);
};
namespace {
base::AtomicSequenceNumber g_next_command_buffer_id;
scoped_refptr<gpu::SyncPointClientState> CreateSyncPointClientState(
SkiaOutputSurfaceDependency* deps,
gpu::SequenceId sequence_id) {
auto command_buffer_id = gpu::CommandBufferId::FromUnsafeValue(
g_next_command_buffer_id.GetNext() + 1);
return deps->GetSyncPointManager()->CreateSyncPointClientState(
gpu::CommandBufferNamespace::VIZ_SKIA_OUTPUT_SURFACE, command_buffer_id,
sequence_id);
}
std::unique_ptr<gpu::SharedImageRepresentationFactory>
CreateSharedImageRepresentationFactory(SkiaOutputSurfaceDependency* deps,
gpu::MemoryTracker* memory_tracker) {
return std::make_unique<gpu::SharedImageRepresentationFactory>(
deps->GetSharedImageManager(), memory_tracker);
}
class ScopedSurfaceToTexture {
public:
ScopedSurfaceToTexture(scoped_refptr<DirectContextProvider> context_provider,
SkSurface* surface)
: context_provider_(context_provider),
client_id_(context_provider->GenClientTextureId()) {
GrBackendTexture skia_texture =
surface->getBackendTexture(SkSurface::kFlushRead_BackendHandleAccess);
GrGLTextureInfo gl_texture_info;
skia_texture.getGLTextureInfo(&gl_texture_info);
auto* group = context_provider->decoder()->GetContextGroup();
if (group->use_passthrough_cmd_decoder()) {
group->passthrough_resources()->texture_id_map.SetIDMapping(
client_id_, gl_texture_info.fID);
auto texture = base::MakeRefCounted<gpu::gles2::TexturePassthrough>(
gl_texture_info.fID, gl_texture_info.fTarget, GL_RGBA,
surface->width(), surface->height(),
/*depth=*/1, /*border=*/0,
/*format=*/GL_RGBA, /*type=*/GL_UNSIGNED_BYTE);
group->passthrough_resources()->texture_object_map.SetIDMapping(
client_id_, texture);
} else {
auto* texture_manager = context_provider_->texture_manager();
texture_ref_ =
texture_manager->CreateTexture(client_id_, gl_texture_info.fID);
texture_manager->SetTarget(texture_ref_.get(), gl_texture_info.fTarget);
texture_manager->SetLevelInfo(
texture_ref_.get(), gl_texture_info.fTarget,
/*level=*/0,
/*internal_format=*/GL_RGBA, surface->width(), surface->height(),
/*depth=*/1, /*border=*/0,
/*format=*/GL_RGBA, /*type=*/GL_UNSIGNED_BYTE,
/*cleared_rect=*/gfx::Rect(surface->width(), surface->height()));
}
}
~ScopedSurfaceToTexture() {
auto* group = context_provider_->decoder()->GetContextGroup();
// Skia owns the texture. It will delete it when it is done.
if (group->use_passthrough_cmd_decoder()) {
group->passthrough_resources()
->texture_object_map.GetServiceIDOrInvalid(client_id_)
->MarkContextLost();
} else {
texture_ref_->ForceContextLost();
}
context_provider_->DeleteClientTextureId(client_id());
}
GLuint client_id() { return client_id_; }
private:
scoped_refptr<DirectContextProvider> context_provider_;
const GLuint client_id_;
// This is only used with validating gles cmd decoder
scoped_refptr<gpu::gles2::TextureRef> texture_ref_;
DISALLOW_COPY_AND_ASSIGN(ScopedSurfaceToTexture);
};
// This SingleThreadTaskRunner runs tasks on the GPU main thread, where
// DirectContextProvider can safely service calls. It wraps all posted tasks to
// ensure that |impl_on_gpu_->context_provider_| is made current and in a known
// state when the task is run. If |impl_on_gpu| is destructed, pending tasks are
// no-oped when they are run.
class ContextCurrentTaskRunner : public base::SingleThreadTaskRunner {
public:
explicit ContextCurrentTaskRunner(
base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu)
: real_task_runner_(base::ThreadTaskRunnerHandle::Get()),
impl_on_gpu_(impl_on_gpu) {}
bool PostDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override {
return real_task_runner_->PostDelayedTask(
from_here, WrapClosure(std::move(task)), delay);
}
bool PostNonNestableDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override {
return real_task_runner_->PostNonNestableDelayedTask(
from_here, WrapClosure(std::move(task)), delay);
}
bool RunsTasksInCurrentSequence() const override {
return real_task_runner_->RunsTasksInCurrentSequence();
}
private:
base::OnceClosure WrapClosure(base::OnceClosure task) {
return base::BindOnce(
[](base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu,
base::OnceClosure task) {
if (!impl_on_gpu)
return;
SkiaOutputSurfaceImplOnGpu::ScopedUseContextProvider scoped_use(
impl_on_gpu.get(), /*texture_client_id=*/0);
if (!scoped_use.valid())
return;
std::move(task).Run();
},
impl_on_gpu_, std::move(task));
}
~ContextCurrentTaskRunner() override = default;
scoped_refptr<base::SingleThreadTaskRunner> real_task_runner_;
base::WeakPtr<SkiaOutputSurfaceImplOnGpu> impl_on_gpu_;
DISALLOW_COPY_AND_ASSIGN(ContextCurrentTaskRunner);
};
class DirectContextProviderDelegateImpl : public DirectContextProviderDelegate,
public gpu::SharedImageInterface {
public:
DirectContextProviderDelegateImpl(
const gpu::GpuPreferences& gpu_preferences,
const gpu::GpuDriverBugWorkarounds& workarounds,
const gpu::GpuFeatureInfo& gpu_feature_info,
gpu::SharedContextState* context_state,
gpu::MailboxManager* mailbox_manager,
gpu::SharedImageManager* shared_image_manager,
gpu::MemoryTracker* memory_tracker,
scoped_refptr<gpu::SyncPointClientState> sync_point_client_state)
: shared_image_manager_(shared_image_manager),
shared_image_factory_(gpu_preferences,
workarounds,
gpu_feature_info,
context_state,
mailbox_manager,
shared_image_manager,
nullptr /* image_factory */,
memory_tracker,
true /* is_using_skia_renderer */),
sync_point_client_state_(sync_point_client_state) {}
~DirectContextProviderDelegateImpl() override {
sync_point_client_state_->Destroy();
}
// SharedImageInterface implementation:
gpu::Mailbox CreateSharedImage(ResourceFormat format,
const gfx::Size& size,
const gfx::ColorSpace& color_space,
uint32_t usage,
gpu::SurfaceHandle surface_handle) override {
auto mailbox = gpu::Mailbox::GenerateForSharedImage();
if (shared_image_factory_.CreateSharedImage(
mailbox, format, size, color_space, surface_handle, usage))
return mailbox;
return gpu::Mailbox();
}
gpu::Mailbox CreateSharedImage(
ResourceFormat format,
const gfx::Size& size,
const gfx::ColorSpace& color_space,
uint32_t usage,
base::span<const uint8_t> pixel_data) override {
auto mailbox = gpu::Mailbox::GenerateForSharedImage();
if (shared_image_factory_.CreateSharedImage(mailbox, format, size,
color_space, usage, pixel_data))
return mailbox;
return gpu::Mailbox();
}
gpu::Mailbox CreateSharedImage(
gfx::GpuMemoryBuffer* gpu_memory_buffer,
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
const gfx::ColorSpace& color_space,
uint32_t usage) override {
// We do not support creating GMB backed SharedImages.
NOTIMPLEMENTED();
return gpu::Mailbox();
}
void UpdateSharedImage(const gpu::SyncToken& sync_token,
std::unique_ptr<gfx::GpuFence> acquire_fence,
const gpu::Mailbox& mailbox) override {
NOTREACHED();
}
void UpdateSharedImage(const gpu::SyncToken& sync_token,
const gpu::Mailbox& mailbox) override {
DCHECK(!ShouldWait(sync_token))
<< "Cannot UpdateSharedImage with SyncToken from different "
"command buffer.";
shared_image_factory_.UpdateSharedImage(mailbox);
}
void DestroySharedImage(const gpu::SyncToken& sync_token,
const gpu::Mailbox& mailbox) override {
DCHECK(!ShouldWait(sync_token))
<< "Cannot DestroySharedImage with SyncToken from different "
"command buffer.";
shared_image_factory_.DestroySharedImage(mailbox);
}
SwapChainMailboxes CreateSwapChain(ResourceFormat format,
const gfx::Size& size,
const gfx::ColorSpace& color_space,
uint32_t usage) override {
NOTREACHED();
return {};
}
void PresentSwapChain(const gpu::SyncToken& sync_token,
const gpu::Mailbox& mailbox) override {
NOTREACHED();
}
#if defined(OS_FUCHSIA)
void RegisterSysmemBufferCollection(gfx::SysmemBufferCollectionId id,
zx::channel token,
gfx::BufferFormat format,
gfx::BufferUsage usage) override {
NOTREACHED();
}
void ReleaseSysmemBufferCollection(
gfx::SysmemBufferCollectionId id) override {
NOTREACHED();
}
#endif // defined(OS_FUCHSIA)
gpu::SyncToken GenUnverifiedSyncToken() override {
return gpu::SyncToken(sync_point_client_state_->namespace_id(),
sync_point_client_state_->command_buffer_id(),
GenerateFenceSyncRelease());
}
gpu::SyncToken GenVerifiedSyncToken() override {
gpu::SyncToken sync_token = GenUnverifiedSyncToken();
sync_token.SetVerifyFlush();
return sync_token;
}
void WaitSyncToken(const gpu::SyncToken& sync_token) override {
NOTREACHED();
}
void Flush() override {
// No need to flush in this implementation.
}
scoped_refptr<gfx::NativePixmap> GetNativePixmap(
const gpu::Mailbox& mailbox) override {
DCHECK(shared_image_manager_->is_thread_safe());
return shared_image_manager_->GetNativePixmap(mailbox);
}
// DirectContextProviderDelegate implementation.
gpu::SharedImageManager* GetSharedImageManager() override {
return shared_image_manager_;
}
gpu::SharedImageInterface* GetSharedImageInterface() override { return this; }
gpu::CommandBufferNamespace GetNamespaceID() const override {
return sync_point_client_state_->namespace_id();
}
gpu::CommandBufferId GetCommandBufferID() const override {
return sync_point_client_state_->command_buffer_id();
}
uint64_t GenerateFenceSyncRelease() override {
uint64_t release = ++sync_fence_release_;
// Release fence immediately because the relevant GPU calls were already
// issued.
sync_point_client_state_->ReleaseFenceSync(release);
return release;
}
void SignalSyncToken(const gpu::SyncToken& sync_token,
base::OnceClosure callback) override {
base::RepeatingClosure maybe_pass_callback =
base::AdaptCallbackForRepeating(std::move(callback));
if (!sync_point_client_state_->Wait(sync_token, maybe_pass_callback)) {
maybe_pass_callback.Run();
}
}
private:
bool ShouldWait(const gpu::SyncToken& sync_token) {
// Don't wait on an invalid SyncToken.
if (!sync_token.HasData())
return false;
// Don't wait on SyncTokens our own sync tokens because we've already issued
// the relevant calls to the GPU.
return sync_point_client_state_->namespace_id() !=
sync_token.namespace_id() ||
sync_point_client_state_->command_buffer_id() !=
sync_token.command_buffer_id();
}
gpu::SharedImageManager* const shared_image_manager_;
gpu::SharedImageFactory shared_image_factory_;
scoped_refptr<gpu::SyncPointClientState> sync_point_client_state_;
uint64_t sync_fence_release_ = 0;
DISALLOW_COPY_AND_ASSIGN(DirectContextProviderDelegateImpl);
};
} // namespace
// Offscreen surfaces for render passes. It can only be accessed on GPU
// thread.
class SkiaOutputSurfaceImplOnGpu::OffscreenSurface {
public:
OffscreenSurface() = default;
OffscreenSurface(const OffscreenSurface& offscreen_surface) = delete;
OffscreenSurface(OffscreenSurface&& offscreen_surface) = default;
OffscreenSurface& operator=(const OffscreenSurface& offscreen_surface) =
delete;
OffscreenSurface& operator=(OffscreenSurface&& offscreen_surface) = default;
~OffscreenSurface() = default;
SkSurface* surface() { return surface_.get(); }
void set_surface(sk_sp<SkSurface> surface) {
surface_ = std::move(surface);
promise_texture_ = {};
}
SkPromiseImageTexture* fulfill() {
DCHECK(surface_);
if (!promise_texture_) {
promise_texture_ =
SkPromiseImageTexture::Make(surface_->getBackendTexture(
SkSurface::kFlushRead_BackendHandleAccess));
}
return promise_texture_.get();
}
sk_sp<SkSurface> TakeSurface() {
promise_texture_ = {};
return std::move(surface_);
}
private:
sk_sp<SkSurface> surface_;
sk_sp<SkPromiseImageTexture> promise_texture_;
};
SkiaOutputSurfaceImplOnGpu::ReleaseCurrent::ReleaseCurrent(
scoped_refptr<gl::GLSurface> gl_surface,
scoped_refptr<gpu::SharedContextState> context_state)
: gl_surface_(gl_surface), context_state_(context_state) {}
SkiaOutputSurfaceImplOnGpu::ReleaseCurrent::~ReleaseCurrent() {
if (context_state_ && gl_surface_)
context_state_->ReleaseCurrent(gl_surface_.get());
}
class SkiaOutputSurfaceImplOnGpu::DisplayContext : public gpu::DisplayContext {
public:
DisplayContext(SkiaOutputSurfaceDependency* deps,
SkiaOutputSurfaceImplOnGpu* owner)
: dependency_(deps), owner_(owner) {
dependency_->RegisterDisplayContext(this);
}
~DisplayContext() override { dependency_->UnregisterDisplayContext(this); }
DisplayContext(const DisplayContext&) = delete;
DisplayContext& operator=(const DisplayContext&) = delete;
// gpu::DisplayContext implementation
void MarkContextLost() override {
owner_->MarkContextLost(CONTEXT_LOST_UNKNOWN);
}
private:
SkiaOutputSurfaceDependency* const dependency_;
SkiaOutputSurfaceImplOnGpu* const owner_;
};
// static
std::unique_ptr<SkiaOutputSurfaceImplOnGpu> SkiaOutputSurfaceImplOnGpu::Create(
SkiaOutputSurfaceDependency* deps,
const RendererSettings& renderer_settings,
const gpu::SequenceId sequence_id,
DidSwapBufferCompleteCallback did_swap_buffer_complete_callback,
BufferPresentedCallback buffer_presented_callback,
ContextLostCallback context_lost_callback,
GpuVSyncCallback gpu_vsync_callback) {
TRACE_EVENT0("viz", "SkiaOutputSurfaceImplOnGpu::Create");
auto context_state = deps->GetSharedContextState();
if (!context_state)
return nullptr;
auto impl_on_gpu = std::make_unique<SkiaOutputSurfaceImplOnGpu>(
util::PassKey<SkiaOutputSurfaceImplOnGpu>(), deps,
context_state->feature_info(), renderer_settings, sequence_id,
std::move(did_swap_buffer_complete_callback),
std::move(buffer_presented_callback), std::move(context_lost_callback),
std::move(gpu_vsync_callback));
if (!impl_on_gpu->Initialize())
return nullptr;
return impl_on_gpu;
}
SkiaOutputSurfaceImplOnGpu::SkiaOutputSurfaceImplOnGpu(
util::PassKey<SkiaOutputSurfaceImplOnGpu> /* pass_key */,
SkiaOutputSurfaceDependency* deps,
scoped_refptr<gpu::gles2::FeatureInfo> feature_info,
const RendererSettings& renderer_settings,
const gpu::SequenceId sequence_id,
DidSwapBufferCompleteCallback did_swap_buffer_complete_callback,
BufferPresentedCallback buffer_presented_callback,
ContextLostCallback context_lost_callback,
GpuVSyncCallback gpu_vsync_callback)
: dependency_(std::move(deps)),
feature_info_(std::move(feature_info)),
sync_point_client_state_(
CreateSyncPointClientState(dependency_, sequence_id)),
memory_tracker_(std::make_unique<SharedImageSubMemoryTracker>(
sync_point_client_state_->command_buffer_id(),
base::trace_event::MemoryDumpManager::GetInstance()
->GetTracingProcessId(),
dependency_->GetSharedContextState()->memory_tracker())),
shared_image_representation_factory_(
CreateSharedImageRepresentationFactory(dependency_,
memory_tracker_.get())),
vulkan_context_provider_(dependency_->GetVulkanContextProvider()),
dawn_context_provider_(dependency_->GetDawnContextProvider()),
renderer_settings_(renderer_settings),
sequence_id_(sequence_id),
did_swap_buffer_complete_callback_(
std::move(did_swap_buffer_complete_callback)),
context_lost_callback_(std::move(context_lost_callback)),
gpu_vsync_callback_(std::move(gpu_vsync_callback)),
gpu_preferences_(dependency_->GetGpuPreferences()),
display_context_(std::make_unique<DisplayContext>(deps, this)),
copier_active_url_(GURL("chrome://gpu/SkiaRendererGLRendererCopier")) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
buffer_presented_callback_ = CreateSafeRepeatingCallback(
weak_ptr_, std::move(buffer_presented_callback));
}
SkiaOutputSurfaceImplOnGpu::~SkiaOutputSurfaceImplOnGpu() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// |context_provider_| and clients want either the context to be lost or made
// current on destruction.
if (context_state_ && MakeCurrent(false /* need_fbo0 */)) {
gl::ScopedProgressReporter scoped_progress_reporter(
context_state_->progress_reporter());
// This ensures any outstanding callbacks for promise images are performed.
gr_context()->flushAndSubmit();
release_current_last_.emplace(gl_surface_, context_state_);
}
if (copier_) {
context_provider_->FinishQueries();
copier_ = nullptr;
texture_deleter_ = nullptr;
context_provider_ = nullptr;
// Destroying context_provider_ will ReleaseCurrent. MakeCurrent again for
// the rest of this dtor.
MakeCurrent(false /* need_fbo0 */);
}
sync_point_client_state_->Destroy();
}
void SkiaOutputSurfaceImplOnGpu::Reshape(const gfx::Size& size,
float device_scale_factor,
const gfx::ColorSpace& color_space,
gfx::BufferFormat format,
bool use_stencil,
gfx::OverlayTransform transform) {
TRACE_EVENT0("viz", "SkiaOutputSurfaceImplOnGpu::Reshape");
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(gr_context());
if (!MakeCurrent(!dependency_->IsOffscreen() /* need_fbo0 */))
return;
size_ = size;
color_space_ = color_space;
if (!output_device_->Reshape(size_, device_scale_factor, color_space, format,
transform)) {
MarkContextLost(CONTEXT_LOST_RESHAPE_FAILED);
return;
}
}
bool SkiaOutputSurfaceImplOnGpu::FinishPaintCurrentFrame(
sk_sp<SkDeferredDisplayList> ddl,
sk_sp<SkDeferredDisplayList> overdraw_ddl,
std::vector<ImageContextImpl*> image_contexts,
std::vector<gpu::SyncToken> sync_tokens,
uint64_t sync_fence_release,
base::OnceClosure on_finished,
base::Optional<gfx::Rect> draw_rectangle) {
TRACE_EVENT0("viz", "SkiaOutputSurfaceImplOnGpu::FinishPaintCurrentFrame");
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(!scoped_output_device_paint_);
bool need_fbo0 = gl_surface_ && !gl_surface_->IsSurfaceless();
if (!MakeCurrent(need_fbo0))
return false;
if (!ddl) {
MarkContextLost(CONTEXT_LOST_UNKNOWN);
return false;
}
if (draw_rectangle) {
if (!output_device_->SetDrawRectangle(*draw_rectangle)) {
MarkContextLost(
ContextLostReason::CONTEXT_LOST_SET_DRAW_RECTANGLE_FAILED);
}
}
// We do not reset scoped_output_device_paint_ after drawing the ddl until
// SwapBuffers() is called, because we may need access to output_sk_surface()
// for CopyOutput().
scoped_output_device_paint_.emplace(output_device_.get());
DCHECK(output_sk_surface());
dependency_->ScheduleGrContextCleanup();
PullTextureUpdates(std::move(sync_tokens));
{
base::Optional<gpu::raster::GrShaderCache::ScopedCacheUse> cache_use;
if (dependency_->GetGrShaderCache()) {
cache_use.emplace(dependency_->GetGrShaderCache(),
gpu::kInProcessCommandBufferClientId);
}
std::vector<GrBackendSemaphore> begin_semaphores;
std::vector<GrBackendSemaphore> end_semaphores;
promise_image_access_helper_.BeginAccess(
std::move(image_contexts), &begin_semaphores, &end_semaphores);
if (!begin_semaphores.empty()) {
auto result = output_sk_surface()->wait(begin_semaphores.size(),
begin_semaphores.data());
DCHECK(result);
}
// Draw will only fail if the SkSurface and SkDDL are incompatible.
bool draw_success = output_sk_surface()->draw(ddl);
DCHECK(draw_success);
destroy_after_swap_.emplace_back(std::move(ddl));
if (overdraw_ddl) {
sk_sp<SkSurface> overdraw_surface = SkSurface::MakeRenderTarget(
gr_context(), overdraw_ddl->characterization(), SkBudgeted::kNo);
overdraw_surface->draw(overdraw_ddl);
destroy_after_swap_.emplace_back(std::move(overdraw_ddl));
SkPaint paint;
sk_sp<SkImage> overdraw_image = overdraw_surface->makeImageSnapshot();
sk_sp<SkColorFilter> colorFilter = SkiaHelper::MakeOverdrawColorFilter();
paint.setColorFilter(colorFilter);
// TODO(xing.xu): move below to the thread where skia record happens.
output_sk_surface()->getCanvas()->drawImage(overdraw_image.get(), 0, 0,
&paint);
}
auto end_paint_semaphores =
scoped_output_device_paint_->TakeEndPaintSemaphores();
end_semaphores.insert(end_semaphores.end(), end_paint_semaphores.begin(),
end_paint_semaphores.end());
GrFlushInfo flush_info = {
.fNumSemaphores = end_semaphores.size(),
.fSignalSemaphores = end_semaphores.data(),
};
gpu::AddVulkanCleanupTaskForSkiaFlush(vulkan_context_provider_,
&flush_info);
if (on_finished)
gpu::AddCleanupTaskForSkiaFlush(std::move(on_finished), &flush_info);
GrSemaphoresSubmitted result;
{
gl::ScopedProgressReporter scoped_progress_reporter(
context_state_->progress_reporter());
result = output_sk_surface()->flush(
SkSurface::BackendSurfaceAccess::kPresent, flush_info);
}
if (result != GrSemaphoresSubmitted::kYes &&
!(begin_semaphores.empty() && end_semaphores.empty())) {
// TODO(penghuang): handle vulkan device lost.
DLOG(ERROR) << "output_sk_surface()->flush() failed.";
return false;
}
}
ReleaseFenceSyncAndPushTextureUpdates(sync_fence_release);
return true;