Run more tests on Linux GN via swarming where possible
[chromium-blink-merge.git] / components / view_manager / gles2 / command_buffer_driver.cc
blob8e86a86cbc237d6d438c12a6e7bacf53c49d02b2
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/view_manager/gles2/command_buffer_driver.h"
7 #include "base/bind.h"
8 #include "base/macros.h"
9 #include "base/memory/shared_memory.h"
10 #include "components/view_manager/gles2/command_buffer_type_conversions.h"
11 #include "components/view_manager/gles2/gpu_state.h"
12 #include "components/view_manager/gles2/mojo_buffer_backing.h"
13 #include "gpu/command_buffer/common/constants.h"
14 #include "gpu/command_buffer/common/value_state.h"
15 #include "gpu/command_buffer/service/command_buffer_service.h"
16 #include "gpu/command_buffer/service/context_group.h"
17 #include "gpu/command_buffer/service/gles2_cmd_decoder.h"
18 #include "gpu/command_buffer/service/gpu_scheduler.h"
19 #include "gpu/command_buffer/service/image_factory.h"
20 #include "gpu/command_buffer/service/image_manager.h"
21 #include "gpu/command_buffer/service/mailbox_manager.h"
22 #include "gpu/command_buffer/service/memory_tracking.h"
23 #include "gpu/command_buffer/service/sync_point_manager.h"
24 #include "gpu/command_buffer/service/valuebuffer_manager.h"
25 #include "mojo/converters/geometry/geometry_type_converters.h"
26 #include "mojo/platform_handle/platform_handle_functions.h"
27 #include "ui/gfx/gpu_memory_buffer.h"
28 #include "ui/gfx/vsync_provider.h"
29 #include "ui/gl/gl_context.h"
30 #include "ui/gl/gl_image_shared_memory.h"
31 #include "ui/gl/gl_surface.h"
33 namespace gles2 {
35 namespace {
37 class MemoryTrackerStub : public gpu::gles2::MemoryTracker {
38 public:
39 MemoryTrackerStub() {}
41 void TrackMemoryAllocatedChange(
42 size_t old_size,
43 size_t new_size,
44 gpu::gles2::MemoryTracker::Pool pool) override {}
46 bool EnsureGPUMemoryAvailable(size_t size_needed) override { return true; };
48 private:
49 ~MemoryTrackerStub() override {}
51 DISALLOW_COPY_AND_ASSIGN(MemoryTrackerStub);
54 } // anonymous namespace
56 CommandBufferDriver::Client::~Client() {
59 CommandBufferDriver::CommandBufferDriver(scoped_refptr<GpuState> gpu_state)
60 : CommandBufferDriver(gfx::kNullAcceleratedWidget,
61 gpu_state,
62 base::Callback<void(CommandBufferDriver*)>()) {}
64 CommandBufferDriver::CommandBufferDriver(
65 gfx::AcceleratedWidget widget,
66 scoped_refptr<GpuState> gpu_state,
67 const base::Callback<void(CommandBufferDriver*)>& destruct_callback)
68 : client_(nullptr),
69 widget_(widget),
70 gpu_state_(gpu_state),
71 destruct_callback_(destruct_callback),
72 weak_factory_(this) {
75 CommandBufferDriver::~CommandBufferDriver() {
76 DestroyDecoder();
77 if (!destruct_callback_.is_null())
78 destruct_callback_.Run(this);
81 void CommandBufferDriver::Initialize(
82 mojo::CommandBufferSyncClientPtr sync_client,
83 mojo::CommandBufferLostContextObserverPtr loss_observer,
84 mojo::ScopedSharedBufferHandle shared_state) {
85 sync_client_ = sync_client.Pass();
86 loss_observer_ = loss_observer.Pass();
87 bool success = DoInitialize(shared_state.Pass());
88 mojo::GpuCapabilitiesPtr capabilities =
89 success ? mojo::GpuCapabilities::From(decoder_->GetCapabilities())
90 : mojo::GpuCapabilities::New();
91 sync_client_->DidInitialize(success, capabilities.Pass());
94 bool CommandBufferDriver::MakeCurrent() {
95 if (!decoder_)
96 return false;
97 if (decoder_->MakeCurrent())
98 return true;
99 DLOG(ERROR) << "Context lost because MakeCurrent failed.";
100 gpu::error::ContextLostReason reason =
101 static_cast<gpu::error::ContextLostReason>(
102 decoder_->GetContextLostReason());
103 command_buffer_->SetContextLostReason(reason);
104 command_buffer_->SetParseError(gpu::error::kLostContext);
105 OnContextLost(reason);
106 return false;
109 bool CommandBufferDriver::DoInitialize(
110 mojo::ScopedSharedBufferHandle shared_state) {
111 if (widget_ == gfx::kNullAcceleratedWidget)
112 surface_ = gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size(1, 1));
113 else {
114 surface_ = gfx::GLSurface::CreateViewGLSurface(widget_);
115 if (auto vsync_provider = surface_->GetVSyncProvider()) {
116 vsync_provider->GetVSyncParameters(
117 base::Bind(&CommandBufferDriver::OnUpdateVSyncParameters,
118 weak_factory_.GetWeakPtr()));
122 if (!surface_.get())
123 return false;
125 // TODO(piman): virtual contexts, gpu preference.
126 context_ = gfx::GLContext::CreateGLContext(
127 gpu_state_->share_group(), surface_.get(), gfx::PreferIntegratedGpu);
128 if (!context_.get())
129 return false;
131 if (!context_->MakeCurrent(surface_.get()))
132 return false;
134 // TODO(piman): ShaderTranslatorCache is currently per-ContextGroup but
135 // only needs to be per-thread.
136 bool bind_generates_resource = false;
137 scoped_refptr<gpu::gles2::ContextGroup> context_group =
138 new gpu::gles2::ContextGroup(
139 gpu_state_->mailbox_manager(), new MemoryTrackerStub,
140 new gpu::gles2::ShaderTranslatorCache, nullptr, nullptr, nullptr,
141 bind_generates_resource);
143 command_buffer_.reset(
144 new gpu::CommandBufferService(context_group->transfer_buffer_manager()));
145 bool result = command_buffer_->Initialize();
146 DCHECK(result);
148 decoder_.reset(::gpu::gles2::GLES2Decoder::Create(context_group.get()));
149 scheduler_.reset(new gpu::GpuScheduler(command_buffer_.get(), decoder_.get(),
150 decoder_.get()));
151 decoder_->set_engine(scheduler_.get());
152 decoder_->SetResizeCallback(
153 base::Bind(&CommandBufferDriver::OnResize, base::Unretained(this)));
154 decoder_->SetWaitSyncPointCallback(base::Bind(
155 &CommandBufferDriver::OnWaitSyncPoint, base::Unretained(this)));
157 gpu::gles2::DisallowedFeatures disallowed_features;
159 // TODO(piman): attributes.
160 std::vector<int32> attrib_vector;
161 if (!decoder_->Initialize(surface_, context_, false /* offscreen */,
162 gfx::Size(1, 1), disallowed_features,
163 attrib_vector))
164 return false;
166 command_buffer_->SetPutOffsetChangeCallback(base::Bind(
167 &gpu::GpuScheduler::PutChanged, base::Unretained(scheduler_.get())));
168 command_buffer_->SetGetBufferChangeCallback(base::Bind(
169 &gpu::GpuScheduler::SetGetBuffer, base::Unretained(scheduler_.get())));
170 command_buffer_->SetParseErrorCallback(
171 base::Bind(&CommandBufferDriver::OnParseError, base::Unretained(this)));
173 // TODO(piman): other callbacks
175 const size_t kSize = sizeof(gpu::CommandBufferSharedState);
176 scoped_ptr<gpu::BufferBacking> backing(
177 gles2::MojoBufferBacking::Create(shared_state.Pass(), kSize));
178 if (!backing)
179 return false;
181 command_buffer_->SetSharedStateBuffer(backing.Pass());
182 return true;
185 void CommandBufferDriver::SetGetBuffer(int32_t buffer) {
186 command_buffer_->SetGetBuffer(buffer);
189 void CommandBufferDriver::Flush(int32_t put_offset) {
190 if (!context_)
191 return;
192 if (!context_->MakeCurrent(surface_.get())) {
193 DLOG(WARNING) << "Context lost";
194 OnContextLost(gpu::error::kUnknown);
195 return;
197 command_buffer_->Flush(put_offset);
200 void CommandBufferDriver::DestroyWindow() {
201 DestroyDecoder();
202 surface_ = nullptr;
203 context_ = nullptr;
204 destruct_callback_.Reset();
207 void CommandBufferDriver::MakeProgress(int32_t last_get_offset) {
208 // TODO(piman): handle out-of-order.
209 sync_client_->DidMakeProgress(
210 mojo::CommandBufferState::From(command_buffer_->GetLastState()));
213 void CommandBufferDriver::RegisterTransferBuffer(
214 int32_t id,
215 mojo::ScopedSharedBufferHandle transfer_buffer,
216 uint32_t size) {
217 // Take ownership of the memory and map it into this process.
218 // This validates the size.
219 scoped_ptr<gpu::BufferBacking> backing(
220 gles2::MojoBufferBacking::Create(transfer_buffer.Pass(), size));
221 if (!backing) {
222 DVLOG(0) << "Failed to map shared memory.";
223 return;
225 command_buffer_->RegisterTransferBuffer(id, backing.Pass());
228 void CommandBufferDriver::DestroyTransferBuffer(int32_t id) {
229 command_buffer_->DestroyTransferBuffer(id);
232 void CommandBufferDriver::Echo(const mojo::Callback<void()>& callback) {
233 callback.Run();
236 void CommandBufferDriver::CreateImage(int32_t id,
237 mojo::ScopedHandle memory_handle,
238 int32 type,
239 mojo::SizePtr size,
240 int32_t format,
241 int32_t internal_format) {
242 if (!MakeCurrent())
243 return;
245 gpu::gles2::ImageManager* image_manager = decoder_->GetImageManager();
246 if (image_manager->LookupImage(id)) {
247 LOG(ERROR) << "Image already exists with same ID.";
248 return;
251 gfx::GpuMemoryBuffer::Format gpu_format =
252 static_cast<gfx::GpuMemoryBuffer::Format>(format);
253 if (!gpu::ImageFactory::IsGpuMemoryBufferFormatSupported(
254 gpu_format, decoder_->GetCapabilities())) {
255 LOG(ERROR) << "Format is not supported.";
256 return;
259 gfx::Size gfx_size = size.To<gfx::Size>();
260 if (!gpu::ImageFactory::IsImageSizeValidForGpuMemoryBufferFormat(
261 gfx_size, gpu_format)) {
262 LOG(ERROR) << "Invalid image size for format.";
263 return;
266 if (!gpu::ImageFactory::IsImageFormatCompatibleWithGpuMemoryBufferFormat(
267 internal_format, gpu_format)) {
268 LOG(ERROR) << "Incompatible image format.";
269 return;
272 if (type != gfx::SHARED_MEMORY_BUFFER) {
273 NOTIMPLEMENTED();
274 return;
277 gfx::GpuMemoryBufferHandle gfx_handle;
278 // TODO(jam): create mojo enum for this and converter
279 gfx_handle.type = static_cast<gfx::GpuMemoryBufferType>(type);
280 gfx_handle.id = id;
282 MojoPlatformHandle platform_handle;
283 MojoResult extract_result = MojoExtractPlatformHandle(
284 memory_handle.release().value(),
285 &platform_handle);
286 if (extract_result != MOJO_RESULT_OK) {
287 NOTREACHED();
288 return;
291 #if defined(OS_WIN)
292 gfx_handle.handle = platform_handle;
293 #else
294 gfx_handle.handle = base::FileDescriptor(platform_handle, false);
295 #endif
297 scoped_refptr<gfx::GLImageSharedMemory> image =
298 new gfx::GLImageSharedMemory(gfx_size, internal_format);
299 // TODO(jam): also need a mojo enum for this enum
300 if (!image->Initialize(gfx_handle, gpu_format)) {
301 NOTREACHED();
302 return;
305 image_manager->AddImage(image.get(), id);
308 void CommandBufferDriver::DestroyImage(int32_t id) {
309 gpu::gles2::ImageManager* image_manager = decoder_->GetImageManager();
310 if (!image_manager->LookupImage(id)) {
311 LOG(ERROR) << "Image with ID doesn't exist.";
312 return;
314 if (!MakeCurrent())
315 return;
316 image_manager->RemoveImage(id);
319 void CommandBufferDriver::OnParseError() {
320 gpu::CommandBuffer::State state = command_buffer_->GetLastState();
321 OnContextLost(state.context_lost_reason);
324 void CommandBufferDriver::OnResize(gfx::Size size, float scale_factor) {
325 surface_->Resize(size);
328 bool CommandBufferDriver::OnWaitSyncPoint(uint32_t sync_point) {
329 if (!sync_point)
330 return true;
331 if (gpu_state_->sync_point_manager()->IsSyncPointRetired(sync_point))
332 return true;
333 scheduler_->SetScheduled(false);
334 gpu_state_->sync_point_manager()->AddSyncPointCallback(
335 sync_point, base::Bind(&CommandBufferDriver::OnSyncPointRetired,
336 weak_factory_.GetWeakPtr()));
337 return scheduler_->IsScheduled();
340 void CommandBufferDriver::OnSyncPointRetired() {
341 scheduler_->SetScheduled(true);
344 void CommandBufferDriver::OnContextLost(uint32_t reason) {
345 loss_observer_->DidLoseContext(reason);
346 client_->DidLoseContext();
349 void CommandBufferDriver::OnUpdateVSyncParameters(
350 const base::TimeTicks timebase,
351 const base::TimeDelta interval) {
352 client_->UpdateVSyncParameters(timebase, interval);
355 void CommandBufferDriver::DestroyDecoder() {
356 if (decoder_) {
357 bool have_context = decoder_->MakeCurrent();
358 decoder_->Destroy(have_context);
359 decoder_.reset();
363 } // namespace gles2