Reland "Non-SFI mode: Switch to newlib. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / components / view_manager / gles2 / command_buffer_driver.cc
blobb67873041c354b1ae9a9980df42bb73a492d2881
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/mojo_buffer_backing.h"
12 #include "gpu/command_buffer/common/constants.h"
13 #include "gpu/command_buffer/common/value_state.h"
14 #include "gpu/command_buffer/service/command_buffer_service.h"
15 #include "gpu/command_buffer/service/context_group.h"
16 #include "gpu/command_buffer/service/gles2_cmd_decoder.h"
17 #include "gpu/command_buffer/service/gpu_scheduler.h"
18 #include "gpu/command_buffer/service/image_factory.h"
19 #include "gpu/command_buffer/service/image_manager.h"
20 #include "gpu/command_buffer/service/mailbox_manager.h"
21 #include "gpu/command_buffer/service/memory_tracking.h"
22 #include "gpu/command_buffer/service/sync_point_manager.h"
23 #include "gpu/command_buffer/service/valuebuffer_manager.h"
24 #include "mojo/converters/geometry/geometry_type_converters.h"
25 #include "mojo/platform_handle/platform_handle_functions.h"
26 #include "ui/gfx/gpu_memory_buffer.h"
27 #include "ui/gfx/vsync_provider.h"
28 #include "ui/gl/gl_context.h"
29 #include "ui/gl/gl_image_shared_memory.h"
30 #include "ui/gl/gl_surface.h"
32 namespace gles2 {
34 namespace {
36 class MemoryTrackerStub : public gpu::gles2::MemoryTracker {
37 public:
38 MemoryTrackerStub() {}
40 void TrackMemoryAllocatedChange(
41 size_t old_size,
42 size_t new_size,
43 gpu::gles2::MemoryTracker::Pool pool) override {}
45 bool EnsureGPUMemoryAvailable(size_t size_needed) override { return true; };
47 private:
48 ~MemoryTrackerStub() override {}
50 DISALLOW_COPY_AND_ASSIGN(MemoryTrackerStub);
53 } // anonymous namespace
55 CommandBufferDriver::Client::~Client() {
58 CommandBufferDriver::CommandBufferDriver(
59 gfx::GLShareGroup* share_group,
60 gpu::gles2::MailboxManager* mailbox_manager,
61 gpu::SyncPointManager* sync_point_manager)
62 : CommandBufferDriver(gfx::kNullAcceleratedWidget,
63 share_group,
64 mailbox_manager,
65 sync_point_manager,
66 base::Callback<void(CommandBufferDriver*)>()) {
69 CommandBufferDriver::CommandBufferDriver(
70 gfx::AcceleratedWidget widget,
71 gfx::GLShareGroup* share_group,
72 gpu::gles2::MailboxManager* mailbox_manager,
73 gpu::SyncPointManager* sync_point_manager,
74 const base::Callback<void(CommandBufferDriver*)>& destruct_callback)
75 : client_(nullptr),
76 widget_(widget),
77 share_group_(share_group),
78 mailbox_manager_(mailbox_manager),
79 sync_point_manager_(sync_point_manager),
80 destruct_callback_(destruct_callback),
81 weak_factory_(this) {
84 CommandBufferDriver::~CommandBufferDriver() {
85 DestroyDecoder();
86 if (!destruct_callback_.is_null())
87 destruct_callback_.Run(this);
90 void CommandBufferDriver::Initialize(
91 mojo::CommandBufferSyncClientPtr sync_client,
92 mojo::CommandBufferLostContextObserverPtr loss_observer,
93 mojo::ScopedSharedBufferHandle shared_state) {
94 sync_client_ = sync_client.Pass();
95 loss_observer_ = loss_observer.Pass();
96 bool success = DoInitialize(shared_state.Pass());
97 mojo::GpuCapabilitiesPtr capabilities =
98 success ? mojo::GpuCapabilities::From(decoder_->GetCapabilities())
99 : mojo::GpuCapabilities::New();
100 sync_client_->DidInitialize(success, capabilities.Pass());
103 bool CommandBufferDriver::DoInitialize(
104 mojo::ScopedSharedBufferHandle shared_state) {
105 if (widget_ == gfx::kNullAcceleratedWidget)
106 surface_ = gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size(1, 1));
107 else {
108 surface_ = gfx::GLSurface::CreateViewGLSurface(widget_);
109 if (auto vsync_provider = surface_->GetVSyncProvider()) {
110 vsync_provider->GetVSyncParameters(
111 base::Bind(&CommandBufferDriver::OnUpdateVSyncParameters,
112 weak_factory_.GetWeakPtr()));
116 if (!surface_.get())
117 return false;
119 // TODO(piman): virtual contexts, gpu preference.
120 context_ = gfx::GLContext::CreateGLContext(share_group_.get(), surface_.get(),
121 gfx::PreferIntegratedGpu);
122 if (!context_.get())
123 return false;
125 if (!context_->MakeCurrent(surface_.get()))
126 return false;
128 // TODO(piman): ShaderTranslatorCache is currently per-ContextGroup but
129 // only needs to be per-thread.
130 bool bind_generates_resource = false;
131 scoped_refptr<gpu::gles2::ContextGroup> context_group =
132 new gpu::gles2::ContextGroup(
133 mailbox_manager_.get(), new MemoryTrackerStub,
134 new gpu::gles2::ShaderTranslatorCache, nullptr, nullptr, nullptr,
135 bind_generates_resource);
137 command_buffer_.reset(
138 new gpu::CommandBufferService(context_group->transfer_buffer_manager()));
139 bool result = command_buffer_->Initialize();
140 DCHECK(result);
142 decoder_.reset(::gpu::gles2::GLES2Decoder::Create(context_group.get()));
143 scheduler_.reset(new gpu::GpuScheduler(command_buffer_.get(), decoder_.get(),
144 decoder_.get()));
145 decoder_->set_engine(scheduler_.get());
146 decoder_->SetResizeCallback(
147 base::Bind(&CommandBufferDriver::OnResize, base::Unretained(this)));
148 decoder_->SetWaitSyncPointCallback(base::Bind(
149 &CommandBufferDriver::OnWaitSyncPoint, base::Unretained(this)));
151 gpu::gles2::DisallowedFeatures disallowed_features;
153 // TODO(piman): attributes.
154 std::vector<int32> attrib_vector;
155 if (!decoder_->Initialize(surface_, context_, false /* offscreen */,
156 gfx::Size(1, 1), disallowed_features,
157 attrib_vector))
158 return false;
160 command_buffer_->SetPutOffsetChangeCallback(base::Bind(
161 &gpu::GpuScheduler::PutChanged, base::Unretained(scheduler_.get())));
162 command_buffer_->SetGetBufferChangeCallback(base::Bind(
163 &gpu::GpuScheduler::SetGetBuffer, base::Unretained(scheduler_.get())));
164 command_buffer_->SetParseErrorCallback(
165 base::Bind(&CommandBufferDriver::OnParseError, base::Unretained(this)));
167 // TODO(piman): other callbacks
169 const size_t kSize = sizeof(gpu::CommandBufferSharedState);
170 scoped_ptr<gpu::BufferBacking> backing(
171 gles2::MojoBufferBacking::Create(shared_state.Pass(), kSize));
172 if (!backing)
173 return false;
175 command_buffer_->SetSharedStateBuffer(backing.Pass());
176 return true;
179 void CommandBufferDriver::SetGetBuffer(int32_t buffer) {
180 command_buffer_->SetGetBuffer(buffer);
183 void CommandBufferDriver::Flush(int32_t put_offset) {
184 if (!context_)
185 return;
186 if (!context_->MakeCurrent(surface_.get())) {
187 DLOG(WARNING) << "Context lost";
188 OnContextLost(gpu::error::kUnknown);
189 return;
191 command_buffer_->Flush(put_offset);
194 void CommandBufferDriver::DestroyWindow() {
195 DestroyDecoder();
196 surface_ = nullptr;
197 context_ = nullptr;
198 destruct_callback_.Reset();
201 void CommandBufferDriver::MakeProgress(int32_t last_get_offset) {
202 // TODO(piman): handle out-of-order.
203 sync_client_->DidMakeProgress(
204 mojo::CommandBufferState::From(command_buffer_->GetLastState()));
207 void CommandBufferDriver::RegisterTransferBuffer(
208 int32_t id,
209 mojo::ScopedSharedBufferHandle transfer_buffer,
210 uint32_t size) {
211 // Take ownership of the memory and map it into this process.
212 // This validates the size.
213 scoped_ptr<gpu::BufferBacking> backing(
214 gles2::MojoBufferBacking::Create(transfer_buffer.Pass(), size));
215 if (!backing) {
216 DVLOG(0) << "Failed to map shared memory.";
217 return;
219 command_buffer_->RegisterTransferBuffer(id, backing.Pass());
222 void CommandBufferDriver::DestroyTransferBuffer(int32_t id) {
223 command_buffer_->DestroyTransferBuffer(id);
226 void CommandBufferDriver::Echo(const mojo::Callback<void()>& callback) {
227 callback.Run();
230 void CommandBufferDriver::CreateImage(int32_t id,
231 mojo::ScopedHandle memory_handle,
232 int32 type,
233 mojo::SizePtr size,
234 int32_t format,
235 int32_t internal_format) {
236 gpu::gles2::ImageManager* image_manager = decoder_->GetImageManager();
237 if (image_manager->LookupImage(id)) {
238 LOG(ERROR) << "Image already exists with same ID.";
239 return;
242 gfx::GpuMemoryBuffer::Format gpu_format =
243 static_cast<gfx::GpuMemoryBuffer::Format>(format);
244 if (!gpu::ImageFactory::IsGpuMemoryBufferFormatSupported(
245 gpu_format, decoder_->GetCapabilities())) {
246 LOG(ERROR) << "Format is not supported.";
247 return;
250 gfx::Size gfx_size = size.To<gfx::Size>();
251 if (!gpu::ImageFactory::IsImageSizeValidForGpuMemoryBufferFormat(
252 gfx_size, gpu_format)) {
253 LOG(ERROR) << "Invalid image size for format.";
254 return;
257 if (!gpu::ImageFactory::IsImageFormatCompatibleWithGpuMemoryBufferFormat(
258 internal_format, gpu_format)) {
259 LOG(ERROR) << "Incompatible image format.";
260 return;
263 if (type != gfx::SHARED_MEMORY_BUFFER) {
264 NOTIMPLEMENTED();
265 return;
268 gfx::GpuMemoryBufferHandle gfx_handle;
269 // TODO(jam): create mojo enum for this and converter
270 gfx_handle.type = static_cast<gfx::GpuMemoryBufferType>(type);
271 gfx_handle.id = id;
273 MojoPlatformHandle platform_handle;
274 MojoResult extract_result = MojoExtractPlatformHandle(
275 memory_handle.release().value(),
276 &platform_handle);
277 if (extract_result != MOJO_RESULT_OK) {
278 NOTREACHED();
279 return;
282 #if defined(OS_WIN)
283 gfx_handle.handle = platform_handle;
284 #else
285 gfx_handle.handle = base::FileDescriptor(platform_handle, false);
286 #endif
288 scoped_refptr<gfx::GLImageSharedMemory> image =
289 new gfx::GLImageSharedMemory(gfx_size, internal_format);
290 // TODO(jam): also need a mojo enum for this enum
291 if (!image->Initialize(gfx_handle, gpu_format)) {
292 NOTREACHED();
293 return;
296 image_manager->AddImage(image.get(), id);
299 void CommandBufferDriver::DestroyImage(int32_t id) {
300 gpu::gles2::ImageManager* image_manager = decoder_->GetImageManager();
301 if (!image_manager->LookupImage(id)) {
302 LOG(ERROR) << "Image with ID doesn't exist.";
303 return;
305 image_manager->RemoveImage(id);
308 void CommandBufferDriver::OnParseError() {
309 gpu::CommandBuffer::State state = command_buffer_->GetLastState();
310 OnContextLost(state.context_lost_reason);
313 void CommandBufferDriver::OnResize(gfx::Size size, float scale_factor) {
314 surface_->Resize(size);
317 bool CommandBufferDriver::OnWaitSyncPoint(uint32_t sync_point) {
318 if (!sync_point)
319 return true;
320 if (sync_point_manager_->IsSyncPointRetired(sync_point))
321 return true;
322 scheduler_->SetScheduled(false);
323 sync_point_manager_->AddSyncPointCallback(
324 sync_point, base::Bind(&CommandBufferDriver::OnSyncPointRetired,
325 weak_factory_.GetWeakPtr()));
326 return scheduler_->IsScheduled();
329 void CommandBufferDriver::OnSyncPointRetired() {
330 scheduler_->SetScheduled(true);
333 void CommandBufferDriver::OnContextLost(uint32_t reason) {
334 loss_observer_->DidLoseContext(reason);
335 client_->DidLoseContext();
338 void CommandBufferDriver::OnUpdateVSyncParameters(
339 const base::TimeTicks timebase,
340 const base::TimeDelta interval) {
341 client_->UpdateVSyncParameters(timebase, interval);
344 void CommandBufferDriver::DestroyDecoder() {
345 if (decoder_) {
346 bool have_context = decoder_->MakeCurrent();
347 decoder_->Destroy(have_context);
348 decoder_.reset();
352 } // namespace gles2