ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / browser / compositor / gpu_process_transport_factory.cc
blob3658c2517fc08be94194a8d0ac057144d86630fa
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 "base/threading/thread.h"
15 #include "cc/output/compositor_frame.h"
16 #include "cc/output/output_surface.h"
17 #include "cc/surfaces/onscreen_display_client.h"
18 #include "cc/surfaces/surface_display_output_surface.h"
19 #include "cc/surfaces/surface_manager.h"
20 #include "content/browser/compositor/browser_compositor_output_surface.h"
21 #include "content/browser/compositor/gpu_browser_compositor_output_surface.h"
22 #include "content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h"
23 #include "content/browser/compositor/reflector_impl.h"
24 #include "content/browser/compositor/software_browser_compositor_output_surface.h"
25 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
26 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
27 #include "content/browser/gpu/compositor_util.h"
28 #include "content/browser/gpu/gpu_data_manager_impl.h"
29 #include "content/browser/gpu/gpu_surface_tracker.h"
30 #include "content/browser/renderer_host/render_widget_host_impl.h"
31 #include "content/common/gpu/client/context_provider_command_buffer.h"
32 #include "content/common/gpu/client/gl_helper.h"
33 #include "content/common/gpu/client/gpu_channel_host.h"
34 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
35 #include "content/common/gpu/gpu_process_launch_causes.h"
36 #include "content/common/host_shared_bitmap_manager.h"
37 #include "content/public/common/content_switches.h"
38 #include "gpu/GLES2/gl2extchromium.h"
39 #include "gpu/command_buffer/client/gles2_interface.h"
40 #include "gpu/command_buffer/common/mailbox.h"
41 #include "third_party/khronos/GLES2/gl2.h"
42 #include "ui/compositor/compositor.h"
43 #include "ui/compositor/compositor_constants.h"
44 #include "ui/compositor/compositor_switches.h"
45 #include "ui/gfx/geometry/size.h"
46 #include "ui/gfx/native_widget_types.h"
48 #if defined(OS_WIN)
49 #include "content/browser/compositor/software_output_device_win.h"
50 #elif defined(USE_OZONE)
51 #include "content/browser/compositor/overlay_candidate_validator_ozone.h"
52 #include "content/browser/compositor/software_output_device_ozone.h"
53 #include "ui/ozone/public/surface_factory_ozone.h"
54 #elif defined(USE_X11)
55 #include "content/browser/compositor/software_output_device_x11.h"
56 #elif defined(OS_MACOSX)
57 #include "content/browser/compositor/software_output_device_mac.h"
58 #endif
60 using cc::ContextProvider;
61 using gpu::gles2::GLES2Interface;
63 static const int kNumRetriesBeforeSoftwareFallback = 4;
65 namespace content {
67 struct GpuProcessTransportFactory::PerCompositorData {
68 int surface_id;
69 BrowserCompositorOutputSurface* surface;
70 ReflectorImpl* reflector;
71 scoped_ptr<cc::OnscreenDisplayClient> display_client;
73 PerCompositorData() : surface_id(0), surface(nullptr), reflector(nullptr) {}
76 GpuProcessTransportFactory::GpuProcessTransportFactory()
77 : next_surface_id_namespace_(1u),
78 callback_factory_(this) {
79 if (UseSurfacesEnabled())
80 surface_manager_ = make_scoped_ptr(new cc::SurfaceManager);
83 GpuProcessTransportFactory::~GpuProcessTransportFactory() {
84 DCHECK(per_compositor_data_.empty());
86 // Make sure the lost context callback doesn't try to run during destruction.
87 callback_factory_.InvalidateWeakPtrs();
90 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
91 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext() {
92 CauseForGpuLaunch cause =
93 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
94 scoped_refptr<GpuChannelHost> gpu_channel_host(
95 BrowserGpuChannelHostFactory::instance()->EstablishGpuChannelSync(cause));
96 return CreateContextCommon(gpu_channel_host, 0);
99 scoped_ptr<cc::SoftwareOutputDevice> CreateSoftwareOutputDevice(
100 ui::Compositor* compositor) {
101 #if defined(OS_WIN)
102 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceWin(
103 compositor));
104 #elif defined(USE_OZONE)
105 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceOzone(
106 compositor));
107 #elif defined(USE_X11)
108 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceX11(
109 compositor));
110 #elif defined(OS_MACOSX)
111 return scoped_ptr<cc::SoftwareOutputDevice>(
112 new SoftwareOutputDeviceMac(compositor));
113 #else
114 NOTREACHED();
115 return scoped_ptr<cc::SoftwareOutputDevice>();
116 #endif
119 scoped_ptr<cc::OverlayCandidateValidator> CreateOverlayCandidateValidator(
120 gfx::AcceleratedWidget widget) {
121 #if defined(USE_OZONE)
122 ui::OverlayCandidatesOzone* overlay_candidates =
123 ui::SurfaceFactoryOzone::GetInstance()->GetOverlayCandidates(widget);
124 if (overlay_candidates &&
125 base::CommandLine::ForCurrentProcess()->HasSwitch(
126 switches::kEnableHardwareOverlays)) {
127 return scoped_ptr<cc::OverlayCandidateValidator>(
128 new OverlayCandidateValidatorOzone(widget, overlay_candidates));
130 #endif
131 return scoped_ptr<cc::OverlayCandidateValidator>();
134 static bool ShouldCreateGpuOutputSurface(ui::Compositor* compositor) {
135 #if defined(OS_CHROMEOS)
136 // Software fallback does not happen on Chrome OS.
137 return true;
138 #endif
140 #if defined(OS_WIN)
141 if (::GetProp(compositor->widget(), kForceSoftwareCompositor) &&
142 ::RemoveProp(compositor->widget(), kForceSoftwareCompositor))
143 return false;
144 #endif
146 return GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor();
149 void GpuProcessTransportFactory::CreateOutputSurface(
150 base::WeakPtr<ui::Compositor> compositor) {
151 DCHECK(!!compositor);
152 PerCompositorData* data = per_compositor_data_[compositor.get()];
153 if (!data) {
154 data = CreatePerCompositorData(compositor.get());
155 } else {
156 // TODO(piman): Use GpuSurfaceTracker to map ids to surfaces instead of an
157 // output_surface_map_ here.
158 output_surface_map_.Remove(data->surface_id);
159 data->surface = nullptr;
162 bool create_gpu_output_surface =
163 ShouldCreateGpuOutputSurface(compositor.get());
164 if (create_gpu_output_surface) {
165 CauseForGpuLaunch cause =
166 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
167 BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel(
168 cause, base::Bind(&GpuProcessTransportFactory::EstablishedGpuChannel,
169 callback_factory_.GetWeakPtr(), compositor,
170 create_gpu_output_surface, 0));
171 } else {
172 EstablishedGpuChannel(compositor, create_gpu_output_surface, 0);
176 void GpuProcessTransportFactory::EstablishedGpuChannel(
177 base::WeakPtr<ui::Compositor> compositor,
178 bool create_gpu_output_surface,
179 int num_attempts) {
180 if (!compositor)
181 return;
182 PerCompositorData* data = per_compositor_data_[compositor.get()];
183 DCHECK(data);
185 if (num_attempts > kNumRetriesBeforeSoftwareFallback) {
186 #if defined(OS_CHROMEOS)
187 LOG(FATAL) << "Unable to create a UI graphics context, and cannot use "
188 << "software compositing on ChromeOS.";
189 #endif
190 create_gpu_output_surface = false;
193 scoped_refptr<ContextProviderCommandBuffer> context_provider;
194 if (create_gpu_output_surface) {
195 scoped_refptr<GpuChannelHost> gpu_channel_host =
196 BrowserGpuChannelHostFactory::instance()->GetGpuChannel();
197 if (gpu_channel_host.get()) {
198 context_provider = ContextProviderCommandBuffer::Create(
199 GpuProcessTransportFactory::CreateContextCommon(gpu_channel_host,
200 data->surface_id),
201 "Compositor");
202 if (context_provider && !context_provider->BindToCurrentThread())
203 context_provider = nullptr;
206 UMA_HISTOGRAM_BOOLEAN("Aura.CreatedGpuBrowserCompositor",
207 !!context_provider.get());
209 if (!context_provider) {
210 // Try again.
211 CauseForGpuLaunch cause =
212 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
213 BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel(
214 cause, base::Bind(&GpuProcessTransportFactory::EstablishedGpuChannel,
215 callback_factory_.GetWeakPtr(), compositor,
216 create_gpu_output_surface, num_attempts + 1));
217 return;
221 scoped_ptr<BrowserCompositorOutputSurface> surface;
222 if (!create_gpu_output_surface) {
223 surface = make_scoped_ptr(new SoftwareBrowserCompositorOutputSurface(
224 CreateSoftwareOutputDevice(compositor.get()),
225 compositor->vsync_manager()));
226 } else {
227 DCHECK(context_provider);
228 #if defined(USE_OZONE)
229 if (ui::SurfaceFactoryOzone::GetInstance()
230 ->CanShowPrimaryPlaneAsOverlay()) {
231 surface =
232 make_scoped_ptr(new GpuSurfacelessBrowserCompositorOutputSurface(
233 context_provider, data->surface_id, compositor->vsync_manager(),
234 CreateOverlayCandidateValidator(compositor->widget()), GL_RGB,
235 BrowserGpuMemoryBufferManager::current()));
236 } else
237 #endif
239 surface = make_scoped_ptr(new GpuBrowserCompositorOutputSurface(
240 context_provider, compositor->vsync_manager(),
241 CreateOverlayCandidateValidator(compositor->widget())));
245 // TODO(piman): Use GpuSurfaceTracker to map ids to surfaces instead of an
246 // output_surface_map_ here.
247 output_surface_map_.AddWithID(surface.get(), data->surface_id);
248 data->surface = surface.get();
249 if (data->reflector)
250 data->reflector->OnSourceSurfaceReady(data->surface);
252 if (!UseSurfacesEnabled()) {
253 compositor->SetOutputSurface(surface.Pass());
254 return;
257 // This gets a bit confusing. Here we have a ContextProvider in the |surface|
258 // configured to render directly to this widget. We need to make an
259 // OnscreenDisplayClient associated with that context, then return a
260 // SurfaceDisplayOutputSurface set up to draw to the display's surface.
261 cc::SurfaceManager* manager = surface_manager_.get();
262 scoped_ptr<cc::OnscreenDisplayClient> display_client(
263 new cc::OnscreenDisplayClient(
264 surface.Pass(), manager, HostSharedBitmapManager::current(),
265 BrowserGpuMemoryBufferManager::current(),
266 compositor->GetRendererSettings(), compositor->task_runner()));
268 scoped_ptr<cc::SurfaceDisplayOutputSurface> output_surface(
269 new cc::SurfaceDisplayOutputSurface(
270 manager, compositor->surface_id_allocator(), context_provider));
271 display_client->set_surface_output_surface(output_surface.get());
272 output_surface->set_display_client(display_client.get());
273 display_client->display()->Resize(compositor->size());
274 data->display_client = display_client.Pass();
275 compositor->SetOutputSurface(output_surface.Pass());
278 scoped_ptr<ui::Reflector> GpuProcessTransportFactory::CreateReflector(
279 ui::Compositor* source_compositor,
280 ui::Layer* target_layer) {
281 PerCompositorData* source_data = per_compositor_data_[source_compositor];
282 DCHECK(source_data);
284 scoped_ptr<ReflectorImpl> reflector(
285 new ReflectorImpl(source_compositor, target_layer));
286 source_data->reflector = reflector.get();
287 if (BrowserCompositorOutputSurface* source_surface = source_data->surface)
288 reflector->OnSourceSurfaceReady(source_surface);
289 return reflector.Pass();
292 void GpuProcessTransportFactory::RemoveReflector(ui::Reflector* reflector) {
293 ReflectorImpl* reflector_impl = static_cast<ReflectorImpl*>(reflector);
294 PerCompositorData* data =
295 per_compositor_data_[reflector_impl->mirrored_compositor()];
296 DCHECK(data);
297 data->reflector->Shutdown();
298 data->reflector = nullptr;
301 void GpuProcessTransportFactory::RemoveCompositor(ui::Compositor* compositor) {
302 PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
303 if (it == per_compositor_data_.end())
304 return;
305 PerCompositorData* data = it->second;
306 DCHECK(data);
307 // TODO(piman): Use GpuSurfaceTracker to map ids to surfaces instead of an
308 // output_surface_map_ here.
309 if (data->surface)
310 output_surface_map_.Remove(data->surface_id);
311 GpuSurfaceTracker::Get()->RemoveSurface(data->surface_id);
312 delete data;
313 per_compositor_data_.erase(it);
314 if (per_compositor_data_.empty()) {
315 // Destroying the GLHelper may cause some async actions to be cancelled,
316 // causing things to request a new GLHelper. Due to crbug.com/176091 the
317 // GLHelper created in this case would be lost/leaked if we just reset()
318 // on the |gl_helper_| variable directly. So instead we call reset() on a
319 // local scoped_ptr.
320 scoped_ptr<GLHelper> helper = gl_helper_.Pass();
322 // If there are any observer left at this point, make sure they clean up
323 // before we destroy the GLHelper.
324 FOR_EACH_OBSERVER(
325 ImageTransportFactoryObserver, observer_list_, OnLostResources());
327 helper.reset();
328 DCHECK(!gl_helper_) << "Destroying the GLHelper should not cause a new "
329 "GLHelper to be created.";
333 bool GpuProcessTransportFactory::DoesCreateTestContexts() { return false; }
335 uint32 GpuProcessTransportFactory::GetImageTextureTarget() {
336 return BrowserGpuChannelHostFactory::GetImageTextureTarget();
339 cc::SharedBitmapManager* GpuProcessTransportFactory::GetSharedBitmapManager() {
340 return HostSharedBitmapManager::current();
343 gpu::GpuMemoryBufferManager*
344 GpuProcessTransportFactory::GetGpuMemoryBufferManager() {
345 return BrowserGpuMemoryBufferManager::current();
348 ui::ContextFactory* GpuProcessTransportFactory::GetContextFactory() {
349 return this;
352 gfx::GLSurfaceHandle GpuProcessTransportFactory::GetSharedSurfaceHandle() {
353 gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
354 gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
355 handle.parent_client_id =
356 BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
357 return handle;
360 scoped_ptr<cc::SurfaceIdAllocator>
361 GpuProcessTransportFactory::CreateSurfaceIdAllocator() {
362 return make_scoped_ptr(
363 new cc::SurfaceIdAllocator(next_surface_id_namespace_++));
366 void GpuProcessTransportFactory::ResizeDisplay(ui::Compositor* compositor,
367 const gfx::Size& size) {
368 PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
369 if (it == per_compositor_data_.end())
370 return;
371 PerCompositorData* data = it->second;
372 DCHECK(data);
373 if (data->display_client)
374 data->display_client->display()->Resize(size);
377 cc::SurfaceManager* GpuProcessTransportFactory::GetSurfaceManager() {
378 return surface_manager_.get();
381 GLHelper* GpuProcessTransportFactory::GetGLHelper() {
382 if (!gl_helper_ && !per_compositor_data_.empty()) {
383 scoped_refptr<cc::ContextProvider> provider =
384 SharedMainThreadContextProvider();
385 if (provider.get())
386 gl_helper_.reset(new GLHelper(provider->ContextGL(),
387 provider->ContextSupport()));
389 return gl_helper_.get();
392 void GpuProcessTransportFactory::AddObserver(
393 ImageTransportFactoryObserver* observer) {
394 observer_list_.AddObserver(observer);
397 void GpuProcessTransportFactory::RemoveObserver(
398 ImageTransportFactoryObserver* observer) {
399 observer_list_.RemoveObserver(observer);
402 #if defined(OS_MACOSX)
403 void GpuProcessTransportFactory::OnSurfaceDisplayed(int surface_id) {
404 BrowserCompositorOutputSurface* surface = output_surface_map_.Lookup(
405 surface_id);
406 if (surface)
407 surface->OnSurfaceDisplayed();
410 void GpuProcessTransportFactory::OnCompositorRecycled(
411 ui::Compositor* compositor) {
412 PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
413 if (it == per_compositor_data_.end())
414 return;
415 PerCompositorData* data = it->second;
416 DCHECK(data);
417 BrowserCompositorOutputSurface* surface =
418 output_surface_map_.Lookup(data->surface_id);
419 if (surface)
420 surface->OnSurfaceRecycled();
423 bool GpuProcessTransportFactory::SurfaceShouldNotShowFramesAfterRecycle(
424 int surface_id) const {
425 BrowserCompositorOutputSurface* surface =
426 output_surface_map_.Lookup(surface_id);
427 if (surface)
428 return surface->ShouldNotShowFramesAfterRecycle();
429 return false;
431 #endif
433 scoped_refptr<cc::ContextProvider>
434 GpuProcessTransportFactory::SharedMainThreadContextProvider() {
435 if (shared_main_thread_contexts_.get())
436 return shared_main_thread_contexts_;
438 // In threaded compositing mode, we have to create our own context for the
439 // main thread since the compositor's context will be bound to the
440 // compositor thread. When not in threaded mode, we still need a separate
441 // context so that skia and gl_helper don't step on each other.
442 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
443 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext(),
444 "Offscreen-MainThread");
446 if (shared_main_thread_contexts_.get()) {
447 shared_main_thread_contexts_->SetLostContextCallback(
448 base::Bind(&GpuProcessTransportFactory::
449 OnLostMainThreadSharedContextInsideCallback,
450 callback_factory_.GetWeakPtr()));
451 if (!shared_main_thread_contexts_->BindToCurrentThread())
452 shared_main_thread_contexts_ = NULL;
454 return shared_main_thread_contexts_;
457 GpuProcessTransportFactory::PerCompositorData*
458 GpuProcessTransportFactory::CreatePerCompositorData(
459 ui::Compositor* compositor) {
460 DCHECK(!per_compositor_data_[compositor]);
462 gfx::AcceleratedWidget widget = compositor->widget();
463 GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get();
465 PerCompositorData* data = new PerCompositorData;
466 data->surface_id = tracker->AddSurfaceForNativeWidget(widget);
467 tracker->SetSurfaceHandle(
468 data->surface_id,
469 gfx::GLSurfaceHandle(widget, gfx::NATIVE_DIRECT));
471 per_compositor_data_[compositor] = data;
473 return data;
476 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
477 GpuProcessTransportFactory::CreateContextCommon(
478 scoped_refptr<GpuChannelHost> gpu_channel_host,
479 int surface_id) {
480 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor())
481 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
482 blink::WebGraphicsContext3D::Attributes attrs;
483 attrs.shareResources = true;
484 attrs.depth = false;
485 attrs.stencil = false;
486 attrs.antialias = false;
487 attrs.noAutomaticFlushes = true;
488 bool lose_context_when_out_of_memory = true;
489 if (!gpu_channel_host.get()) {
490 LOG(ERROR) << "Failed to establish GPU channel.";
491 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
493 GURL url("chrome://gpu/GpuProcessTransportFactory::CreateContextCommon");
494 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
495 new WebGraphicsContext3DCommandBufferImpl(
496 surface_id,
497 url,
498 gpu_channel_host.get(),
499 attrs,
500 lose_context_when_out_of_memory,
501 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
502 NULL));
503 return context.Pass();
506 void GpuProcessTransportFactory::OnLostMainThreadSharedContextInsideCallback() {
507 base::MessageLoop::current()->PostTask(
508 FROM_HERE,
509 base::Bind(&GpuProcessTransportFactory::OnLostMainThreadSharedContext,
510 callback_factory_.GetWeakPtr()));
513 void GpuProcessTransportFactory::OnLostMainThreadSharedContext() {
514 LOG(ERROR) << "Lost UI shared context.";
516 // Keep old resources around while we call the observers, but ensure that
517 // new resources are created if needed.
518 // Kill shared contexts for both threads in tandem so they are always in
519 // the same share group.
520 scoped_refptr<cc::ContextProvider> lost_shared_main_thread_contexts =
521 shared_main_thread_contexts_;
522 shared_main_thread_contexts_ = NULL;
524 scoped_ptr<GLHelper> lost_gl_helper = gl_helper_.Pass();
526 FOR_EACH_OBSERVER(ImageTransportFactoryObserver,
527 observer_list_,
528 OnLostResources());
530 // Kill things that use the shared context before killing the shared context.
531 lost_gl_helper.reset();
532 lost_shared_main_thread_contexts = NULL;
535 } // namespace content