base/threading: remove ScopedTracker placed for experiments
[chromium-blink-merge.git] / content / common / gpu / client / webgraphicscontext3d_command_buffer_impl.cc
blob90242b6383bca8e1fd27cf722ed5c46e643055ea
1 // Copyright (c) 2012 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 "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
7 #include "third_party/khronos/GLES2/gl2.h"
8 #ifndef GL_GLEXT_PROTOTYPES
9 #define GL_GLEXT_PROTOTYPES 1
10 #endif
11 #include "third_party/khronos/GLES2/gl2ext.h"
13 #include <algorithm>
14 #include <map>
16 #include "base/atomicops.h"
17 #include "base/bind.h"
18 #include "base/command_line.h"
19 #include "base/lazy_instance.h"
20 #include "base/logging.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/profiler/scoped_tracker.h"
25 #include "base/trace_event/trace_event.h"
26 #include "content/common/gpu/client/gpu_channel_host.h"
27 #include "content/public/common/content_constants.h"
28 #include "content/public/common/content_switches.h"
29 #include "gpu/GLES2/gl2extchromium.h"
30 #include "gpu/command_buffer/client/gles2_cmd_helper.h"
31 #include "gpu/command_buffer/client/gles2_implementation.h"
32 #include "gpu/command_buffer/client/gles2_trace_implementation.h"
33 #include "gpu/command_buffer/client/transfer_buffer.h"
34 #include "gpu/command_buffer/common/constants.h"
35 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
36 #include "gpu/command_buffer/common/mailbox.h"
37 #include "gpu/skia_bindings/gl_bindings_skia_cmd_buffer.h"
38 #include "third_party/skia/include/core/SkTypes.h"
40 using blink::WGC3Denum;
42 namespace content {
44 namespace {
46 static base::LazyInstance<base::Lock>::Leaky
47 g_default_share_groups_lock = LAZY_INSTANCE_INITIALIZER;
49 typedef std::map<GpuChannelHost*,
50 scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup> >
51 ShareGroupMap;
52 static base::LazyInstance<ShareGroupMap> g_default_share_groups =
53 LAZY_INSTANCE_INITIALIZER;
55 scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup>
56 GetDefaultShareGroupForHost(GpuChannelHost* host) {
57 base::AutoLock lock(g_default_share_groups_lock.Get());
59 ShareGroupMap& share_groups = g_default_share_groups.Get();
60 ShareGroupMap::iterator it = share_groups.find(host);
61 if (it == share_groups.end()) {
62 scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup> group =
63 new WebGraphicsContext3DCommandBufferImpl::ShareGroup();
64 share_groups[host] = group;
65 return group;
67 return it->second;
70 } // namespace anonymous
72 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits::SharedMemoryLimits()
73 : command_buffer_size(kDefaultCommandBufferSize),
74 start_transfer_buffer_size(kDefaultStartTransferBufferSize),
75 min_transfer_buffer_size(kDefaultMinTransferBufferSize),
76 max_transfer_buffer_size(kDefaultMaxTransferBufferSize),
77 mapped_memory_reclaim_limit(gpu::gles2::GLES2Implementation::kNoLimit) {}
79 WebGraphicsContext3DCommandBufferImpl::ShareGroup::ShareGroup() {
82 WebGraphicsContext3DCommandBufferImpl::ShareGroup::~ShareGroup() {
83 DCHECK(contexts_.empty());
86 WebGraphicsContext3DCommandBufferImpl::WebGraphicsContext3DCommandBufferImpl(
87 int surface_id,
88 const GURL& active_url,
89 GpuChannelHost* host,
90 const Attributes& attributes,
91 bool lose_context_when_out_of_memory,
92 const SharedMemoryLimits& limits,
93 WebGraphicsContext3DCommandBufferImpl* share_context)
94 : lose_context_when_out_of_memory_(lose_context_when_out_of_memory),
95 attributes_(attributes),
96 visible_(false),
97 host_(host),
98 surface_id_(surface_id),
99 active_url_(active_url),
100 context_type_(CONTEXT_TYPE_UNKNOWN),
101 gpu_preference_(attributes.preferDiscreteGPU ? gfx::PreferDiscreteGpu
102 : gfx::PreferIntegratedGpu),
103 mem_limits_(limits),
104 weak_ptr_factory_(this) {
105 if (attributes_.webGL)
106 context_type_ = OFFSCREEN_CONTEXT_FOR_WEBGL;
107 if (share_context) {
108 DCHECK(!attributes_.shareResources);
109 share_group_ = share_context->share_group_;
110 } else {
111 share_group_ = attributes_.shareResources
112 ? GetDefaultShareGroupForHost(host)
113 : scoped_refptr<WebGraphicsContext3DCommandBufferImpl::ShareGroup>(
114 new ShareGroup());
118 WebGraphicsContext3DCommandBufferImpl::
119 ~WebGraphicsContext3DCommandBufferImpl() {
120 if (real_gl_) {
121 real_gl_->SetErrorMessageCallback(NULL);
124 Destroy();
127 bool WebGraphicsContext3DCommandBufferImpl::MaybeInitializeGL() {
128 if (initialized_)
129 return true;
131 if (initialize_failed_)
132 return false;
134 TRACE_EVENT0("gpu", "WebGfxCtx3DCmdBfrImpl::MaybeInitializeGL");
136 // TODO(vadimt): Remove ScopedTracker below once crbug.com/125248 is fixed.
137 tracked_objects::ScopedTracker tracking_profile(
138 FROM_HERE_WITH_EXPLICIT_FUNCTION(
139 "125248 WebGraphicsContext3DCommandBufferImpl::MaybeInitializeGL"));
141 if (!CreateContext(surface_id_ != 0)) {
142 Destroy();
144 initialize_failed_ = true;
145 return false;
148 command_buffer_->SetContextLostCallback(
149 base::Bind(&WebGraphicsContext3DCommandBufferImpl::OnContextLost,
150 weak_ptr_factory_.GetWeakPtr()));
152 command_buffer_->SetOnConsoleMessageCallback(
153 base::Bind(&WebGraphicsContext3DCommandBufferImpl::OnErrorMessage,
154 weak_ptr_factory_.GetWeakPtr()));
156 real_gl_->SetErrorMessageCallback(getErrorMessageCallback());
158 visible_ = true;
159 initialized_ = true;
160 return true;
163 bool WebGraphicsContext3DCommandBufferImpl::InitializeCommandBuffer(
164 bool onscreen, WebGraphicsContext3DCommandBufferImpl* share_context) {
165 if (!host_.get())
166 return false;
168 CommandBufferProxyImpl* share_group_command_buffer = NULL;
170 if (share_context) {
171 share_group_command_buffer = share_context->GetCommandBufferProxy();
174 ::gpu::gles2::ContextCreationAttribHelper attribs_for_gles2;
175 ConvertAttributes(attributes_, &attribs_for_gles2);
176 attribs_for_gles2.lose_context_when_out_of_memory =
177 lose_context_when_out_of_memory_;
178 DCHECK(attribs_for_gles2.buffer_preserved);
179 std::vector<int32> attribs;
180 attribs_for_gles2.Serialize(&attribs);
182 // Create a proxy to a command buffer in the GPU process.
183 if (onscreen) {
184 command_buffer_ =
185 host_->CreateViewCommandBuffer(surface_id_, share_group_command_buffer,
186 attribs, active_url_, gpu_preference_);
187 } else {
188 command_buffer_ = host_->CreateOffscreenCommandBuffer(
189 gfx::Size(1, 1), share_group_command_buffer, attribs, active_url_,
190 gpu_preference_);
193 if (!command_buffer_) {
194 DLOG(ERROR) << "GpuChannelHost failed to create command buffer.";
195 UmaRecordContextInitFailed(context_type_);
196 return false;
199 DVLOG_IF(1, gpu::error::IsError(command_buffer_->GetLastError()))
200 << "Context dead on arrival. Last error: "
201 << command_buffer_->GetLastError();
202 // Initialize the command buffer.
203 bool result = command_buffer_->Initialize();
204 LOG_IF(ERROR, !result) << "CommandBufferProxy::Initialize failed.";
205 if (!result)
206 UmaRecordContextInitFailed(context_type_);
207 return result;
210 bool WebGraphicsContext3DCommandBufferImpl::CreateContext(bool onscreen) {
211 TRACE_EVENT0("gpu", "WebGfxCtx3DCmdBfrImpl::CreateContext");
212 scoped_refptr<gpu::gles2::ShareGroup> gles2_share_group;
214 scoped_ptr<base::AutoLock> share_group_lock;
215 bool add_to_share_group = false;
216 if (!command_buffer_) {
217 WebGraphicsContext3DCommandBufferImpl* share_context = NULL;
219 share_group_lock.reset(new base::AutoLock(share_group_->lock()));
220 share_context = share_group_->GetAnyContextLocked();
222 if (!InitializeCommandBuffer(onscreen, share_context)) {
223 LOG(ERROR) << "Failed to initialize command buffer.";
224 return false;
227 if (share_context)
228 gles2_share_group = share_context->GetImplementation()->share_group();
230 add_to_share_group = true;
233 // Create the GLES2 helper, which writes the command buffer protocol.
234 gles2_helper_.reset(new gpu::gles2::GLES2CmdHelper(command_buffer_.get()));
235 if (!gles2_helper_->Initialize(mem_limits_.command_buffer_size)) {
236 LOG(ERROR) << "Failed to initialize GLES2CmdHelper.";
237 return false;
240 if (attributes_.noAutomaticFlushes)
241 gles2_helper_->SetAutomaticFlushes(false);
242 // Create a transfer buffer used to copy resources between the renderer
243 // process and the GPU process.
244 transfer_buffer_ .reset(new gpu::TransferBuffer(gles2_helper_.get()));
246 DCHECK(host_.get());
248 // Create the object exposing the OpenGL API.
249 const bool bind_generates_resources = false;
250 const bool support_client_side_arrays = false;
252 real_gl_.reset(new gpu::gles2::GLES2Implementation(
253 gles2_helper_.get(), gles2_share_group.get(), transfer_buffer_.get(),
254 bind_generates_resources, lose_context_when_out_of_memory_,
255 support_client_side_arrays, command_buffer_.get()));
256 setGLInterface(real_gl_.get());
258 if (!real_gl_->Initialize(
259 mem_limits_.start_transfer_buffer_size,
260 mem_limits_.min_transfer_buffer_size,
261 mem_limits_.max_transfer_buffer_size,
262 mem_limits_.mapped_memory_reclaim_limit)) {
263 LOG(ERROR) << "Failed to initialize GLES2Implementation.";
264 return false;
267 if (add_to_share_group)
268 share_group_->AddContextLocked(this);
270 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
271 switches::kEnableGpuClientTracing)) {
272 trace_gl_.reset(new gpu::gles2::GLES2TraceImplementation(GetGLInterface()));
273 setGLInterface(trace_gl_.get());
275 return true;
278 bool WebGraphicsContext3DCommandBufferImpl::InitializeOnCurrentThread() {
279 if (!MaybeInitializeGL()) {
280 DLOG(ERROR) << "Failed to initialize context.";
281 return false;
283 if (gpu::error::IsError(command_buffer_->GetLastError())) {
284 LOG(ERROR) << "Context dead on arrival. Last error: "
285 << command_buffer_->GetLastError();
286 return false;
289 return true;
292 void WebGraphicsContext3DCommandBufferImpl::Destroy() {
293 share_group_->RemoveContext(this);
295 gpu::gles2::GLES2Interface* gl = GetGLInterface();
296 if (gl) {
297 // First flush the context to ensure that any pending frees of resources
298 // are completed. Otherwise, if this context is part of a share group,
299 // those resources might leak. Also, any remaining side effects of commands
300 // issued on this context might not be visible to other contexts in the
301 // share group.
302 gl->Flush();
303 setGLInterface(NULL);
306 trace_gl_.reset();
307 real_gl_.reset();
308 transfer_buffer_.reset();
309 gles2_helper_.reset();
310 real_gl_.reset();
311 command_buffer_.reset();
313 host_ = NULL;
316 gpu::ContextSupport*
317 WebGraphicsContext3DCommandBufferImpl::GetContextSupport() {
318 return real_gl_.get();
321 bool WebGraphicsContext3DCommandBufferImpl::IsCommandBufferContextLost() {
322 // If the channel shut down unexpectedly, let that supersede the
323 // command buffer's state.
324 if (host_.get() && host_->IsLost())
325 return true;
326 gpu::CommandBuffer::State state = command_buffer_->GetLastState();
327 return gpu::error::IsError(state.error);
330 // static
331 WebGraphicsContext3DCommandBufferImpl*
332 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
333 GpuChannelHost* host,
334 const WebGraphicsContext3D::Attributes& attributes,
335 bool lose_context_when_out_of_memory,
336 const GURL& active_url,
337 const SharedMemoryLimits& limits,
338 WebGraphicsContext3DCommandBufferImpl* share_context) {
339 if (!host)
340 return NULL;
342 if (share_context && share_context->IsCommandBufferContextLost())
343 return NULL;
345 return new WebGraphicsContext3DCommandBufferImpl(
347 active_url,
348 host,
349 attributes,
350 lose_context_when_out_of_memory,
351 limits,
352 share_context);
355 void WebGraphicsContext3DCommandBufferImpl::OnContextLost() {
356 if (context_lost_callback_)
357 context_lost_callback_->onContextLost();
359 share_group_->RemoveAllContexts();
361 DCHECK(host_.get());
363 base::AutoLock lock(g_default_share_groups_lock.Get());
364 g_default_share_groups.Get().erase(host_.get());
367 gpu::CommandBuffer::State state = command_buffer_->GetLastState();
368 UmaRecordContextLost(context_type_, state.error, state.context_lost_reason);
371 } // namespace content