Revert 268405 "Make sure that ScratchBuffer::Allocate() always r..."
[chromium-blink-merge.git] / content / browser / compositor / gpu_process_transport_factory.cc
blob46f1e84140dbe6f0956de8179f5491448b473218
1 // Copyright 2014 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/browser/compositor/gpu_process_transport_factory.h"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/location.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "cc/output/compositor_frame.h"
15 #include "cc/output/output_surface.h"
16 #include "content/browser/compositor/browser_compositor_output_surface.h"
17 #include "content/browser/compositor/browser_compositor_output_surface_proxy.h"
18 #include "content/browser/compositor/gpu_browser_compositor_output_surface.h"
19 #include "content/browser/compositor/reflector_impl.h"
20 #include "content/browser/compositor/software_browser_compositor_output_surface.h"
21 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
22 #include "content/browser/gpu/gpu_data_manager_impl.h"
23 #include "content/browser/gpu/gpu_surface_tracker.h"
24 #include "content/browser/renderer_host/render_widget_host_impl.h"
25 #include "content/common/gpu/client/context_provider_command_buffer.h"
26 #include "content/common/gpu/client/gl_helper.h"
27 #include "content/common/gpu/client/gpu_channel_host.h"
28 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
29 #include "content/common/gpu/gpu_process_launch_causes.h"
30 #include "gpu/GLES2/gl2extchromium.h"
31 #include "gpu/command_buffer/client/gles2_interface.h"
32 #include "gpu/command_buffer/common/mailbox.h"
33 #include "third_party/khronos/GLES2/gl2.h"
34 #include "ui/compositor/compositor.h"
35 #include "ui/compositor/compositor_constants.h"
36 #include "ui/compositor/compositor_switches.h"
37 #include "ui/gfx/native_widget_types.h"
38 #include "ui/gfx/size.h"
40 #if defined(OS_WIN)
41 #include "content/browser/compositor/software_output_device_win.h"
42 #elif defined(USE_OZONE)
43 #include "content/browser/compositor/overlay_candidate_validator_ozone.h"
44 #include "content/browser/compositor/software_output_device_ozone.h"
45 #include "ui/gfx/ozone/surface_factory_ozone.h"
46 #elif defined(USE_X11)
47 #include "content/browser/compositor/software_output_device_x11.h"
48 #endif
50 using cc::ContextProvider;
51 using gpu::gles2::GLES2Interface;
53 namespace content {
55 struct GpuProcessTransportFactory::PerCompositorData {
56 int surface_id;
57 scoped_refptr<ReflectorImpl> reflector;
60 GpuProcessTransportFactory::GpuProcessTransportFactory()
61 : callback_factory_(this) {
62 output_surface_proxy_ = new BrowserCompositorOutputSurfaceProxy(
63 &output_surface_map_);
66 GpuProcessTransportFactory::~GpuProcessTransportFactory() {
67 DCHECK(per_compositor_data_.empty());
69 // Make sure the lost context callback doesn't try to run during destruction.
70 callback_factory_.InvalidateWeakPtrs();
73 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
74 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext() {
75 return CreateContextCommon(0);
78 scoped_ptr<cc::SoftwareOutputDevice> CreateSoftwareOutputDevice(
79 ui::Compositor* compositor) {
80 #if defined(OS_WIN)
81 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceWin(
82 compositor));
83 #elif defined(USE_OZONE)
84 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceOzone(
85 compositor));
86 #elif defined(USE_X11)
87 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceX11(
88 compositor));
89 #else
90 NOTREACHED();
91 return scoped_ptr<cc::SoftwareOutputDevice>();
92 #endif
95 scoped_ptr<cc::OverlayCandidateValidator> CreateOverlayCandidateValidator(
96 gfx::AcceleratedWidget widget) {
97 #if defined(USE_OZONE)
98 gfx::OverlayCandidatesOzone* overlay_candidates =
99 gfx::SurfaceFactoryOzone::GetInstance()->GetOverlayCandidates(widget);
100 if (overlay_candidates && CommandLine::ForCurrentProcess()->HasSwitch(
101 switches::kEnableHardwareOverlays)) {
102 return scoped_ptr<cc::OverlayCandidateValidator>(
103 new OverlayCandidateValidatorOzone(widget, overlay_candidates));
105 #endif
106 return scoped_ptr<cc::OverlayCandidateValidator>();
109 scoped_ptr<cc::OutputSurface> GpuProcessTransportFactory::CreateOutputSurface(
110 ui::Compositor* compositor, bool software_fallback) {
111 PerCompositorData* data = per_compositor_data_[compositor];
112 if (!data)
113 data = CreatePerCompositorData(compositor);
115 bool create_software_renderer = software_fallback;
116 #if defined(OS_CHROMEOS)
117 // Software fallback does not happen on Chrome OS.
118 create_software_renderer = false;
119 #elif defined(OS_WIN)
120 if (::GetProp(compositor->widget(), kForceSoftwareCompositor)) {
121 if (::RemoveProp(compositor->widget(), kForceSoftwareCompositor))
122 create_software_renderer = true;
124 #endif
126 scoped_refptr<ContextProviderCommandBuffer> context_provider;
127 if (!create_software_renderer) {
128 context_provider = ContextProviderCommandBuffer::Create(
129 GpuProcessTransportFactory::CreateContextCommon(data->surface_id),
130 "Compositor");
133 UMA_HISTOGRAM_BOOLEAN("Aura.CreatedGpuBrowserCompositor", !!context_provider);
135 if (!context_provider.get()) {
136 if (ui::Compositor::WasInitializedWithThread()) {
137 LOG(FATAL) << "Failed to create UI context, but can't use software"
138 " compositing with browser threaded compositing. Aborting.";
141 scoped_ptr<SoftwareBrowserCompositorOutputSurface> surface(
142 new SoftwareBrowserCompositorOutputSurface(
143 output_surface_proxy_,
144 CreateSoftwareOutputDevice(compositor),
145 per_compositor_data_[compositor]->surface_id,
146 &output_surface_map_,
147 compositor->vsync_manager()));
148 return surface.PassAs<cc::OutputSurface>();
151 scoped_refptr<base::SingleThreadTaskRunner> compositor_thread_task_runner =
152 ui::Compositor::GetCompositorMessageLoop();
153 if (!compositor_thread_task_runner.get())
154 compositor_thread_task_runner = base::MessageLoopProxy::current();
156 // Here we know the GpuProcessHost has been set up, because we created a
157 // context.
158 output_surface_proxy_->ConnectToGpuProcessHost(
159 compositor_thread_task_runner.get());
161 scoped_ptr<BrowserCompositorOutputSurface> surface(
162 new GpuBrowserCompositorOutputSurface(
163 context_provider,
164 per_compositor_data_[compositor]->surface_id,
165 &output_surface_map_,
166 compositor->vsync_manager(),
167 CreateOverlayCandidateValidator(compositor->widget())));
168 if (data->reflector.get())
169 data->reflector->ReattachToOutputSurfaceFromMainThread(surface.get());
171 return surface.PassAs<cc::OutputSurface>();
174 scoped_refptr<ui::Reflector> GpuProcessTransportFactory::CreateReflector(
175 ui::Compositor* source,
176 ui::Layer* target) {
177 PerCompositorData* data = per_compositor_data_[source];
178 DCHECK(data);
180 data->reflector = new ReflectorImpl(
181 source, target, &output_surface_map_, data->surface_id);
182 return data->reflector;
185 void GpuProcessTransportFactory::RemoveReflector(
186 scoped_refptr<ui::Reflector> reflector) {
187 ReflectorImpl* reflector_impl =
188 static_cast<ReflectorImpl*>(reflector.get());
189 PerCompositorData* data =
190 per_compositor_data_[reflector_impl->mirrored_compositor()];
191 DCHECK(data);
192 data->reflector->Shutdown();
193 data->reflector = NULL;
196 void GpuProcessTransportFactory::RemoveCompositor(ui::Compositor* compositor) {
197 PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
198 if (it == per_compositor_data_.end())
199 return;
200 PerCompositorData* data = it->second;
201 DCHECK(data);
202 GpuSurfaceTracker::Get()->RemoveSurface(data->surface_id);
203 delete data;
204 per_compositor_data_.erase(it);
205 if (per_compositor_data_.empty()) {
206 // Destroying the GLHelper may cause some async actions to be cancelled,
207 // causing things to request a new GLHelper. Due to crbug.com/176091 the
208 // GLHelper created in this case would be lost/leaked if we just reset()
209 // on the |gl_helper_| variable directly. So instead we call reset() on a
210 // local scoped_ptr.
211 scoped_ptr<GLHelper> helper = gl_helper_.Pass();
212 helper.reset();
213 DCHECK(!gl_helper_) << "Destroying the GLHelper should not cause a new "
214 "GLHelper to be created.";
218 bool GpuProcessTransportFactory::DoesCreateTestContexts() { return false; }
220 ui::ContextFactory* GpuProcessTransportFactory::AsContextFactory() {
221 return this;
224 gfx::GLSurfaceHandle GpuProcessTransportFactory::GetSharedSurfaceHandle() {
225 gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
226 gfx::kNullPluginWindow, gfx::TEXTURE_TRANSPORT);
227 handle.parent_client_id =
228 BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
229 return handle;
232 GLHelper* GpuProcessTransportFactory::GetGLHelper() {
233 if (!gl_helper_ && !per_compositor_data_.empty()) {
234 scoped_refptr<cc::ContextProvider> provider =
235 SharedMainThreadContextProvider();
236 if (provider.get())
237 gl_helper_.reset(new GLHelper(provider->ContextGL(),
238 provider->ContextSupport()));
240 return gl_helper_.get();
243 void GpuProcessTransportFactory::AddObserver(
244 ImageTransportFactoryObserver* observer) {
245 observer_list_.AddObserver(observer);
248 void GpuProcessTransportFactory::RemoveObserver(
249 ImageTransportFactoryObserver* observer) {
250 observer_list_.RemoveObserver(observer);
253 scoped_refptr<cc::ContextProvider>
254 GpuProcessTransportFactory::SharedMainThreadContextProvider() {
255 if (shared_main_thread_contexts_.get())
256 return shared_main_thread_contexts_;
258 // In threaded compositing mode, we have to create our own context for the
259 // main thread since the compositor's context will be bound to the
260 // compositor thread. When not in threaded mode, we still need a separate
261 // context so that skia and gl_helper don't step on each other.
262 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
263 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext(),
264 "Offscreen-MainThread");
266 if (shared_main_thread_contexts_) {
267 shared_main_thread_contexts_->SetLostContextCallback(
268 base::Bind(&GpuProcessTransportFactory::
269 OnLostMainThreadSharedContextInsideCallback,
270 callback_factory_.GetWeakPtr()));
271 if (!shared_main_thread_contexts_->BindToCurrentThread())
272 shared_main_thread_contexts_ = NULL;
274 return shared_main_thread_contexts_;
277 GpuProcessTransportFactory::PerCompositorData*
278 GpuProcessTransportFactory::CreatePerCompositorData(
279 ui::Compositor* compositor) {
280 DCHECK(!per_compositor_data_[compositor]);
282 gfx::AcceleratedWidget widget = compositor->widget();
283 GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get();
285 PerCompositorData* data = new PerCompositorData;
286 data->surface_id = tracker->AddSurfaceForNativeWidget(widget);
287 tracker->SetSurfaceHandle(
288 data->surface_id,
289 gfx::GLSurfaceHandle(widget, gfx::NATIVE_DIRECT));
291 per_compositor_data_[compositor] = data;
293 return data;
296 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
297 GpuProcessTransportFactory::CreateContextCommon(int surface_id) {
298 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor())
299 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
300 blink::WebGraphicsContext3D::Attributes attrs;
301 attrs.shareResources = true;
302 attrs.depth = false;
303 attrs.stencil = false;
304 attrs.antialias = false;
305 attrs.noAutomaticFlushes = true;
306 bool lose_context_when_out_of_memory = true;
307 CauseForGpuLaunch cause =
308 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
309 scoped_refptr<GpuChannelHost> gpu_channel_host(
310 BrowserGpuChannelHostFactory::instance()->EstablishGpuChannelSync(cause));
311 if (!gpu_channel_host) {
312 LOG(ERROR) << "Failed to establish GPU channel.";
313 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
315 GURL url("chrome://gpu/GpuProcessTransportFactory::CreateContextCommon");
316 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
317 new WebGraphicsContext3DCommandBufferImpl(
318 surface_id,
319 url,
320 gpu_channel_host.get(),
321 attrs,
322 lose_context_when_out_of_memory,
323 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
324 NULL));
325 return context.Pass();
328 void GpuProcessTransportFactory::OnLostMainThreadSharedContextInsideCallback() {
329 base::MessageLoop::current()->PostTask(
330 FROM_HERE,
331 base::Bind(&GpuProcessTransportFactory::OnLostMainThreadSharedContext,
332 callback_factory_.GetWeakPtr()));
335 void GpuProcessTransportFactory::OnLostMainThreadSharedContext() {
336 LOG(ERROR) << "Lost UI shared context.";
338 // Keep old resources around while we call the observers, but ensure that
339 // new resources are created if needed.
340 // Kill shared contexts for both threads in tandem so they are always in
341 // the same share group.
342 scoped_refptr<cc::ContextProvider> lost_shared_main_thread_contexts =
343 shared_main_thread_contexts_;
344 shared_main_thread_contexts_ = NULL;
346 scoped_ptr<GLHelper> lost_gl_helper = gl_helper_.Pass();
348 FOR_EACH_OBSERVER(ImageTransportFactoryObserver,
349 observer_list_,
350 OnLostResources());
352 // Kill things that use the shared context before killing the shared context.
353 lost_gl_helper.reset();
354 lost_shared_main_thread_contexts = NULL;
357 } // namespace content