summaryrefslogtreecommitdiff
path: root/chromium/gpu/command_buffer/service/shared_image/shared_image_factory.cc
blob: 8f2866169bc79a46f53abbaf2fbb5e53575320cc (plain)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gpu/command_buffer/service/shared_image/shared_image_factory.h"

#include <inttypes.h>
#include <memory>

#include "base/trace_event/memory_dump_manager.h"
#include "build/build_config.h"
#include "build/chromecast_buildflags.h"
#include "build/chromeos_buildflags.h"
#include "components/viz/common/resources/resource_format_utils.h"
#include "gpu/command_buffer/common/gpu_memory_buffer_support.h"
#include "gpu/command_buffer/common/shared_image_trace_utils.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder.h"
#include "gpu/command_buffer/service/image_factory.h"
#include "gpu/command_buffer/service/service_utils.h"
#include "gpu/command_buffer/service/shared_context_state.h"
#include "gpu/command_buffer/service/shared_image/compound_image_backing.h"
#include "gpu/command_buffer/service/shared_image/gl_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/gl_texture_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/raw_draw_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/shared_image_backing.h"
#include "gpu/command_buffer/service/shared_image/shared_image_manager.h"
#include "gpu/command_buffer/service/shared_image/shared_image_representation.h"
#include "gpu/command_buffer/service/shared_image/shared_memory_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/wrapped_sk_image_backing_factory.h"
#include "gpu/config/gpu_preferences.h"
#include "ui/base/ui_base_features.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_switches.h"
#include "ui/gl/trace_util.h"

#if BUILDFLAG(ENABLE_VULKAN)
#include "components/viz/common/gpu/vulkan_context_provider.h"
#include "gpu/command_buffer/service/shared_image/angle_vulkan_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/external_vk_image_backing_factory.h"
#include "gpu/vulkan/vulkan_device_queue.h"
#endif  // BUILDFLAG(ENABLE_VULKAN)

#if defined(USE_OZONE)
#include "gpu/command_buffer/service/shared_image/ozone_image_backing_factory.h"
#include "ui/ozone/public/gl_ozone.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/surface_factory_ozone.h"
#endif

#if BUILDFLAG(IS_MAC)
#include "gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.h"
#endif

#if BUILDFLAG(IS_WIN)
#include "gpu/command_buffer/service/dxgi_shared_handle_manager.h"
#include "gpu/command_buffer/service/shared_image/d3d_image_backing_factory.h"
#include "ui/gl/gl_angle_util_win.h"
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(IS_FUCHSIA)
#include <lib/zx/channel.h>
#include "gpu/vulkan/vulkan_device_queue.h"
#include "gpu/vulkan/vulkan_implementation.h"
#endif  // BUILDFLAG(IS_FUCHSIA)

#if BUILDFLAG(IS_ANDROID)
#include "base/android/android_hardware_buffer_compat.h"
#include "gpu/command_buffer/service/shared_image/ahardwarebuffer_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/egl_image_backing_factory.h"
#endif

namespace gpu {

namespace {

const char* GmbTypeToString(gfx::GpuMemoryBufferType type) {
  switch (type) {
    case gfx::EMPTY_BUFFER:
      return "empty";
    case gfx::SHARED_MEMORY_BUFFER:
      return "shared_memory";
    case gfx::IO_SURFACE_BUFFER:
    case gfx::NATIVE_PIXMAP:
    case gfx::DXGI_SHARED_HANDLE:
    case gfx::ANDROID_HARDWARE_BUFFER:
      return "platform";
  }
  NOTREACHED();
}

}  // namespace

// Overrides for flat_set lookups:
bool operator<(
    const std::unique_ptr<SharedImageRepresentationFactoryRef>& lhs,
    const std::unique_ptr<SharedImageRepresentationFactoryRef>& rhs) {
  return lhs->mailbox() < rhs->mailbox();
}

bool operator<(
    const Mailbox& lhs,
    const std::unique_ptr<SharedImageRepresentationFactoryRef>& rhs) {
  return lhs < rhs->mailbox();
}

bool operator<(const std::unique_ptr<SharedImageRepresentationFactoryRef>& lhs,
               const Mailbox& rhs) {
  return lhs->mailbox() < rhs;
}

SharedImageFactory::SharedImageFactory(
    const GpuPreferences& gpu_preferences,
    const GpuDriverBugWorkarounds& workarounds,
    const GpuFeatureInfo& gpu_feature_info,
    SharedContextState* context_state,
    SharedImageManager* shared_image_manager,
    ImageFactory* image_factory,
    MemoryTracker* memory_tracker,
    bool is_for_display_compositor)
    : shared_image_manager_(shared_image_manager),
      shared_context_state_(context_state),
      memory_tracker_(std::make_unique<MemoryTypeTracker>(memory_tracker)),
      is_for_display_compositor_(is_for_display_compositor),
      gr_context_type_(context_state ? context_state->gr_context_type()
                                     : GrContextType::kGL) {
#if BUILDFLAG(IS_MAC)
  // OSX
  DCHECK(gr_context_type_ == GrContextType::kGL ||
         gr_context_type_ == GrContextType::kMetal ||
         gr_context_type_ == GrContextType::kVulkan);
#endif

  scoped_refptr<gles2::FeatureInfo> feature_info;
  if (shared_context_state_) {
    feature_info = shared_context_state_->feature_info();
  }

  if (!feature_info) {
    // For some unit tests, shared_context_state_ could be nullptr.
    bool use_passthrough = gpu_preferences.use_passthrough_cmd_decoder &&
                           gles2::PassthroughCommandDecoderSupported();
    feature_info = new gles2::FeatureInfo(workarounds, gpu_feature_info);
    feature_info->Initialize(ContextType::CONTEXT_TYPE_OPENGLES2,
                             use_passthrough, gles2::DisallowedFeatures());
  }

  auto shared_memory_backing_factory =
      std::make_unique<SharedMemoryImageBackingFactory>();
  factories_.push_back(std::move(shared_memory_backing_factory));

  if (context_state) {
    auto wrapped_sk_image_factory =
        std::make_unique<WrappedSkImageBackingFactory>(context_state);
    factories_.push_back(std::move(wrapped_sk_image_factory));
  }

  if (features::IsUsingRawDraw() && context_state) {
    auto factory = std::make_unique<RawDrawImageBackingFactory>();
    factories_.push_back(std::move(factory));
  }

  bool use_gl =
      gl::GetGLImplementation() != gl::kGLImplementationNone &&
      (!is_for_display_compositor_ || gr_context_type_ == GrContextType::kGL);
  if (use_gl) {
    auto gl_texture_backing_factory =
        std::make_unique<GLTextureImageBackingFactory>(
            gpu_preferences, workarounds, feature_info.get(),
            shared_context_state_ ? shared_context_state_->progress_reporter()
                                  : nullptr,
            /*for_cpu_upload_usage=*/false);
    factories_.push_back(std::move(gl_texture_backing_factory));
  }

#if BUILDFLAG(IS_WIN)
  if (D3DImageBackingFactory::IsD3DSharedImageSupported(gpu_preferences)) {
    // TODO(sunnyps): Should we get the device from SharedContextState instead?
    auto d3d_factory = std::make_unique<D3DImageBackingFactory>(
        gl::QueryD3D11DeviceObjectFromANGLE(),
        shared_image_manager_->dxgi_shared_handle_manager());
    d3d_backing_factory_ = d3d_factory.get();
    factories_.push_back(std::move(d3d_factory));
  }
#endif  // BUILDFLAG(IS_WIN)

#if !BUILDFLAG(IS_ANDROID)
  if (use_gl) {
    auto gl_texture_backing_factory =
        std::make_unique<GLTextureImageBackingFactory>(
            gpu_preferences, workarounds, feature_info.get(),
            shared_context_state_ ? shared_context_state_->progress_reporter()
                                  : nullptr,
            /*for_cpu_upload_usage=*/true);
    factories_.push_back(std::move(gl_texture_backing_factory));
  }
#endif

#if BUILDFLAG(ENABLE_VULKAN)
  // If Chrome and ANGLE are sharing the same vulkan device queue, AngleVulkan
  // backing will be used for interop.
  if ((gr_context_type_ == GrContextType::kVulkan) &&
      (base::FeatureList::IsEnabled(features::kVulkanFromANGLE))) {
    auto factory = std::make_unique<AngleVulkanImageBackingFactory>(
        gpu_preferences, workarounds, context_state);
    factories_.push_back(std::move(factory));
  }

#if BUILDFLAG(IS_WIN)
  if (gr_context_type_ == GrContextType::kVulkan) {
    auto external_vk_image_factory =
        std::make_unique<ExternalVkImageBackingFactory>(context_state);
    factories_.push_back(std::move(external_vk_image_factory));
  }
#endif  // BUILDFLAG(IS_WIN)
#endif  // BUILDFLAG(ENABLE_VULKAN)

#if BUILDFLAG(IS_ANDROID)
  if (use_gl) {
    auto egl_backing_factory = std::make_unique<EGLImageBackingFactory>(
        gpu_preferences, workarounds, feature_info.get());
    factories_.push_back(std::move(egl_backing_factory));
  }
  bool is_ahb_supported =
      base::AndroidHardwareBufferCompat::IsSupportAvailable();
  if (gr_context_type_ == GrContextType::kVulkan) {
    const auto& enabled_extensions = context_state->vk_context_provider()
                                         ->GetDeviceQueue()
                                         ->enabled_extensions();
    is_ahb_supported =
        is_ahb_supported &&
        gfx::HasExtension(
            enabled_extensions,
            VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
  }
  if (is_ahb_supported) {
    auto ahb_factory = std::make_unique<AHardwareBufferImageBackingFactory>(
        feature_info.get());
    factories_.push_back(std::move(ahb_factory));
  }
  if (gr_context_type_ == GrContextType::kVulkan &&
      !base::FeatureList::IsEnabled(features::kVulkanFromANGLE)) {
    auto external_vk_image_factory =
        std::make_unique<ExternalVkImageBackingFactory>(context_state);
    factories_.push_back(std::move(external_vk_image_factory));
  }
#elif defined(USE_OZONE)
  // For all Ozone platforms - Desktop Linux, ChromeOS, Fuchsia, CastOS.
  if (ui::OzonePlatform::GetInstance()
          ->GetPlatformRuntimeProperties()
          .supports_native_pixmaps) {
    auto ozone_factory = std::make_unique<OzoneImageBackingFactory>(
        context_state, workarounds, gpu_preferences);
    factories_.push_back(std::move(ozone_factory));
  }
#if BUILDFLAG(ENABLE_VULKAN)
  if (gr_context_type_ == GrContextType::kVulkan) {
    auto external_vk_image_factory =
        std::make_unique<ExternalVkImageBackingFactory>(context_state);
    factories_.push_back(std::move(external_vk_image_factory));
#if BUILDFLAG(IS_FUCHSIA)
    vulkan_context_provider_ = context_state->vk_context_provider();
#endif  // BUILDFLAG(IS_FUCHSIA)
  }
#endif  // BUILDFLAG(ENABLE_VULKAN)
#endif  // defined(USE_OZONE)

#if BUILDFLAG(IS_MAC)
  // TODO(hitawala): Temporary factory that will be replaced with Ozone and
  // other backings
  if (use_gl) {
    auto gl_image_backing_factory = std::make_unique<GLImageBackingFactory>(
        gpu_preferences, workarounds, feature_info.get(), image_factory,
        shared_context_state_ ? shared_context_state_->progress_reporter()
                              : nullptr);
    factories_.push_back(std::move(gl_image_backing_factory));
  }
#endif
}

SharedImageFactory::~SharedImageFactory() {
  DCHECK(shared_images_.empty());
}

bool SharedImageFactory::CreateSharedImage(const Mailbox& mailbox,
                                           viz::SharedImageFormat format,
                                           const gfx::Size& size,
                                           const gfx::ColorSpace& color_space,
                                           GrSurfaceOrigin surface_origin,
                                           SkAlphaType alpha_type,
                                           gpu::SurfaceHandle surface_handle,
                                           uint32_t usage) {
  DCHECK(format.is_single_plane());
  auto* factory = GetFactoryByUsage(usage, format, size,
                                    /*pixel_data=*/{}, gfx::EMPTY_BUFFER);
  if (!factory)
    return false;

  auto backing = factory->CreateSharedImage(
      mailbox, format, surface_handle, size, color_space, surface_origin,
      alpha_type, usage, IsSharedBetweenThreads(usage));
  DVLOG(1) << "CreateSharedImage[" << backing->GetName()
           << "] size=" << size.ToString()
           << " usage=" << CreateLabelForSharedImageUsage(usage)
           << " resource_format=" << format.ToString();
  return RegisterBacking(std::move(backing));
}

bool SharedImageFactory::CreateSharedImage(const Mailbox& mailbox,
                                           viz::SharedImageFormat format,
                                           const gfx::Size& size,
                                           const gfx::ColorSpace& color_space,
                                           GrSurfaceOrigin surface_origin,
                                           SkAlphaType alpha_type,
                                           uint32_t usage,
                                           base::span<const uint8_t> data) {
  DCHECK(format.is_single_plane());
  SharedImageBackingFactory* factory = nullptr;
  if (backing_factory_for_testing_) {
    factory = backing_factory_for_testing_;
  } else {
    factory = GetFactoryByUsage(usage, format, size, data, gfx::EMPTY_BUFFER);
  }
  if (!factory)
    return false;

  auto backing =
      factory->CreateSharedImage(mailbox, format, size, color_space,
                                 surface_origin, alpha_type, usage, data);
  if (backing) {
    DVLOG(1) << "CreateSharedImagePixels[" << backing->GetName()
             << "] with pixels size=" << size.ToString()
             << " usage=" << CreateLabelForSharedImageUsage(usage)
             << " resource_format=" << format.ToString();

    backing->OnWriteSucceeded();
  }
  return RegisterBacking(std::move(backing));
}

bool SharedImageFactory::CreateSharedImage(const Mailbox& mailbox,
                                           int client_id,
                                           gfx::GpuMemoryBufferHandle handle,
                                           gfx::BufferFormat format,
                                           gfx::BufferPlane plane,
                                           SurfaceHandle surface_handle,
                                           const gfx::Size& size,
                                           const gfx::ColorSpace& color_space,
                                           GrSurfaceOrigin surface_origin,
                                           SkAlphaType alpha_type,
                                           uint32_t usage) {
  auto si_format =
      viz::SharedImageFormat::SinglePlane(viz::GetResourceFormat(format));
  gfx::GpuMemoryBufferType gmb_type = handle.type;

  bool use_compound = false;
  auto* factory = GetFactoryByUsage(usage, si_format, size,
                                    /*pixel_data=*/{}, gmb_type);

  if (!factory && gmb_type == gfx::SHARED_MEMORY_BUFFER) {
    // Check if CompoundImageBacking can hold shared memory buffer plus
    // another GPU backing type to satisfy requirements.
    use_compound = true;
    factory = GetFactoryByUsage(usage | SHARED_IMAGE_USAGE_CPU_UPLOAD,
                                si_format, size,
                                /*pixel_data=*/{}, gfx::EMPTY_BUFFER);
  }

  if (!factory)
    return false;

  std::unique_ptr<SharedImageBacking> backing;
  if (use_compound) {
#if BUILDFLAG(IS_WIN)
    constexpr bool allow_shm_overlays = true;
#else
    constexpr bool allow_shm_overlays = false;
#endif
    backing = CompoundImageBacking::CreateSharedMemory(
        factory, allow_shm_overlays, mailbox, std::move(handle), format, plane,
        surface_handle, size, color_space, surface_origin, alpha_type, usage);
  } else {
    backing = factory->CreateSharedImage(
        mailbox, client_id, std::move(handle), format, plane, surface_handle,
        size, color_space, surface_origin, alpha_type, usage);
  }

  if (backing) {
    DVLOG(1) << "CreateSharedImage[" << backing->GetName()
             << "] from handle size=" << size.ToString()
             << " usage=" << CreateLabelForSharedImageUsage(usage)
             << " buffer_format=" << gfx::BufferFormatToString(format)
             << " gmb_type=" << GmbTypeToString(gmb_type);

    backing->OnWriteSucceeded();
  }
  return RegisterBacking(std::move(backing));
}

bool SharedImageFactory::UpdateSharedImage(const Mailbox& mailbox) {
  return UpdateSharedImage(mailbox, nullptr);
}

bool SharedImageFactory::UpdateSharedImage(
    const Mailbox& mailbox,
    std::unique_ptr<gfx::GpuFence> in_fence) {
  auto it = shared_images_.find(mailbox);
  if (it == shared_images_.end()) {
    LOG(ERROR) << "UpdateSharedImage: Could not find shared image mailbox";
    return false;
  }
  (*it)->Update(std::move(in_fence));
  return true;
}

bool SharedImageFactory::DestroySharedImage(const Mailbox& mailbox) {
  auto it = shared_images_.find(mailbox);
  if (it == shared_images_.end()) {
    LOG(ERROR) << "DestroySharedImage: Could not find shared image mailbox";
    return false;
  }
  shared_images_.erase(it);
  return true;
}

void SharedImageFactory::DestroyAllSharedImages(bool have_context) {
  if (!have_context) {
    for (auto& shared_image : shared_images_)
      shared_image->OnContextLost();
  }
  shared_images_.clear();
}

#if BUILDFLAG(IS_WIN)
bool SharedImageFactory::CreateSwapChain(const Mailbox& front_buffer_mailbox,
                                         const Mailbox& back_buffer_mailbox,
                                         viz::ResourceFormat format,
                                         const gfx::Size& size,
                                         const gfx::ColorSpace& color_space,
                                         GrSurfaceOrigin surface_origin,
                                         SkAlphaType alpha_type,
                                         uint32_t usage) {
  if (!D3DImageBackingFactory::IsSwapChainSupported())
    return false;

  auto backings = d3d_backing_factory_->CreateSwapChain(
      front_buffer_mailbox, back_buffer_mailbox, format, size, color_space,
      surface_origin, alpha_type, usage);
  return RegisterBacking(std::move(backings.front_buffer)) &&
         RegisterBacking(std::move(backings.back_buffer));
}

bool SharedImageFactory::PresentSwapChain(const Mailbox& mailbox) {
  if (!D3DImageBackingFactory::IsSwapChainSupported())
    return false;
  auto it = shared_images_.find(mailbox);
  if (it == shared_images_.end()) {
    DLOG(ERROR) << "PresentSwapChain: Could not find shared image mailbox";
    return false;
  }
  (*it)->PresentSwapChain();
  return true;
}
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(IS_FUCHSIA)
bool SharedImageFactory::RegisterSysmemBufferCollection(
    gfx::SysmemBufferCollectionId id,
    zx::channel token,
    gfx::BufferFormat format,
    gfx::BufferUsage usage,
    bool register_with_image_pipe) {
  decltype(buffer_collections_)::iterator it;
  bool inserted;
  std::tie(it, inserted) =
      buffer_collections_.insert(std::make_pair(id, nullptr));

  if (!inserted) {
    DLOG(ERROR) << "RegisterSysmemBufferCollection: Could not register the "
                   "same buffer collection twice.";
    return false;
  }

  // If we don't have Vulkan then just drop the token. Sysmem will inform the
  // caller about the issue. The empty entry is kept in buffer_collections_, so
  // the caller can still call ReleaseSysmemBufferCollection().
  if (!vulkan_context_provider_)
    return true;

  VkDevice device =
      vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice();
  DCHECK(device != VK_NULL_HANDLE);
  it->second = vulkan_context_provider_->GetVulkanImplementation()
                   ->RegisterSysmemBufferCollection(
                       device, id, std::move(token), format, usage, gfx::Size(),
                       0, register_with_image_pipe);

  return true;
}

bool SharedImageFactory::ReleaseSysmemBufferCollection(
    gfx::SysmemBufferCollectionId id) {
  auto removed = buffer_collections_.erase(id);
  return removed > 0;
}
#endif  // BUILDFLAG(IS_FUCHSIA)

#if BUILDFLAG(IS_WIN)
bool SharedImageFactory::CopyToGpuMemoryBuffer(const Mailbox& mailbox) {
  auto it = shared_images_.find(mailbox);
  if (it == shared_images_.end()) {
    DLOG(ERROR) << "UpdateSharedImage: Could not find shared image mailbox";
    return false;
  }
  return (*it)->CopyToGpuMemoryBuffer();
}
#endif

void SharedImageFactory::RegisterSharedImageBackingFactoryForTesting(
    SharedImageBackingFactory* factory) {
  backing_factory_for_testing_ = factory;
}

bool SharedImageFactory::IsSharedBetweenThreads(uint32_t usage) {
  // Ignore for mipmap usage.
  usage &= ~SHARED_IMAGE_USAGE_MIPMAP;
  // Ignore for delegated compositing.
  usage &= ~SHARED_IMAGE_USAGE_RASTER_DELEGATED_COMPOSITING;

  // Raw Draw backings will be write accessed on the GPU main thread, and
  // be read accessed on the compositor thread.
  if (usage & SHARED_IMAGE_USAGE_RAW_DRAW)
    return true;

  // DISPLAY is for gpu composition and SCANOUT for overlays.
  constexpr int kDisplayCompositorUsage = SHARED_IMAGE_USAGE_DISPLAY_READ |
                                          SHARED_IMAGE_USAGE_DISPLAY_WRITE |
                                          SHARED_IMAGE_USAGE_SCANOUT;

  // Image is used on display compositor gpu thread if it's used by display
  // compositor and if display compositor runs on a separate thread. Image is
  // used by display compositor if it has kDisplayCompositorUsage or is being
  // created by display compositor.
  const bool used_by_display_compositor_gpu_thread =
      ((usage & kDisplayCompositorUsage) || is_for_display_compositor_) &&
      shared_image_manager_->display_context_on_another_thread();

  // If it has usage other than kDisplayCompositorUsage OR if it is not created
  // by display compositor, it means that it is used by the gpu main thread.
  const bool used_by_main_gpu_thread =
      usage & ~kDisplayCompositorUsage || !is_for_display_compositor_;
  return used_by_display_compositor_gpu_thread && used_by_main_gpu_thread;
}

SharedImageBackingFactory* SharedImageFactory::GetFactoryByUsage(
    uint32_t usage,
    viz::SharedImageFormat format,
    const gfx::Size& size,
    base::span<const uint8_t> pixel_data,
    gfx::GpuMemoryBufferType gmb_type) {
  if (backing_factory_for_testing_)
    return backing_factory_for_testing_;

  bool share_between_threads = IsSharedBetweenThreads(usage);
  for (auto& factory : factories_) {
    if (factory->IsSupported(usage, format, size, share_between_threads,
                             gmb_type, gr_context_type_, pixel_data)) {
      return factory.get();
    }
  }

  LOG(ERROR) << "Could not find SharedImageBackingFactory with params: usage: "
             << CreateLabelForSharedImageUsage(usage)
             << ", format: " << format.ToString()
             << ", share_between_threads: " << share_between_threads
             << ", gmb_type: " << GmbTypeToString(gmb_type);
  return nullptr;
}

bool SharedImageFactory::RegisterBacking(
    std::unique_ptr<SharedImageBacking> backing) {
  if (!backing) {
    LOG(ERROR) << "CreateSharedImage: could not create backing.";
    return false;
  }

  std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image =
      shared_image_manager_->Register(std::move(backing),
                                      memory_tracker_.get());

  if (!shared_image) {
    LOG(ERROR) << "CreateSharedImage: could not register backing.";
    return false;
  }

  shared_image->RegisterImageFactory(this);

  shared_images_.emplace(std::move(shared_image));
  return true;
}

SharedImageRepresentationFactory::SharedImageRepresentationFactory(
    SharedImageManager* manager,
    MemoryTracker* tracker)
    : manager_(manager),
      tracker_(std::make_unique<MemoryTypeTracker>(tracker)) {}

SharedImageRepresentationFactory::~SharedImageRepresentationFactory() {
  DCHECK_EQ(0u, tracker_->GetMemRepresented());
}

std::unique_ptr<GLTextureImageRepresentation>
SharedImageRepresentationFactory::ProduceGLTexture(const Mailbox& mailbox) {
  return manager_->ProduceGLTexture(mailbox, tracker_.get());
}

std::unique_ptr<GLTextureImageRepresentation>
SharedImageRepresentationFactory::ProduceRGBEmulationGLTexture(
    const Mailbox& mailbox) {
  return manager_->ProduceRGBEmulationGLTexture(mailbox, tracker_.get());
}

std::unique_ptr<GLTexturePassthroughImageRepresentation>
SharedImageRepresentationFactory::ProduceGLTexturePassthrough(
    const Mailbox& mailbox) {
  return manager_->ProduceGLTexturePassthrough(mailbox, tracker_.get());
}

std::unique_ptr<SkiaImageRepresentation>
SharedImageRepresentationFactory::ProduceSkia(
    const Mailbox& mailbox,
    scoped_refptr<SharedContextState> context_state) {
  return manager_->ProduceSkia(mailbox, tracker_.get(), context_state);
}

std::unique_ptr<DawnImageRepresentation>
SharedImageRepresentationFactory::ProduceDawn(const Mailbox& mailbox,
                                              WGPUDevice device,
                                              WGPUBackendType backend_type) {
  return manager_->ProduceDawn(mailbox, tracker_.get(), device, backend_type);
}

std::unique_ptr<OverlayImageRepresentation>
SharedImageRepresentationFactory::ProduceOverlay(const gpu::Mailbox& mailbox) {
  return manager_->ProduceOverlay(mailbox, tracker_.get());
}

std::unique_ptr<MemoryImageRepresentation>
SharedImageRepresentationFactory::ProduceMemory(const gpu::Mailbox& mailbox) {
  return manager_->ProduceMemory(mailbox, tracker_.get());
}

std::unique_ptr<RasterImageRepresentation>
SharedImageRepresentationFactory::ProduceRaster(const Mailbox& mailbox) {
  return manager_->ProduceRaster(mailbox, tracker_.get());
}

#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<LegacyOverlayImageRepresentation>
SharedImageRepresentationFactory::ProduceLegacyOverlay(
    const gpu::Mailbox& mailbox) {
  return manager_->ProduceLegacyOverlay(mailbox, tracker_.get());
}
#endif

}  // namespace gpu