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"
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 "third_party/khronos/GLES2/gl2.h"
33 #include "ui/compositor/compositor.h"
34 #include "ui/compositor/compositor_constants.h"
35 #include "ui/compositor/compositor_switches.h"
36 #include "ui/gfx/native_widget_types.h"
37 #include "ui/gfx/size.h"
40 #include "content/browser/compositor/software_output_device_win.h"
41 #elif defined(USE_OZONE)
42 #include "content/browser/compositor/software_output_device_ozone.h"
43 #elif defined(USE_X11)
44 #include "content/browser/compositor/software_output_device_x11.h"
47 using cc::ContextProvider;
48 using gpu::gles2::GLES2Interface;
52 struct GpuProcessTransportFactory::PerCompositorData {
54 scoped_refptr<ReflectorImpl> reflector;
57 class OwnedTexture : public ui::Texture, ImageTransportFactoryObserver {
59 OwnedTexture(const scoped_refptr<ContextProvider>& provider,
60 const gfx::Size& size,
61 float device_scale_factor,
63 : ui::Texture(true, size, device_scale_factor),
65 texture_id_(texture_id) {
66 ImageTransportFactory::GetInstance()->AddObserver(this);
69 // ui::Texture overrides:
70 virtual unsigned int PrepareTexture() OVERRIDE {
71 // It's possible that we may have lost the context owning our
72 // texture but not yet fired the OnLostResources callback, so poll to see if
74 if (provider_ && provider_->IsContextLost())
79 // ImageTransportFactory overrides:
80 virtual void OnLostResources() OVERRIDE {
86 virtual ~OwnedTexture() {
87 ImageTransportFactory::GetInstance()->RemoveObserver(this);
92 void DeleteTexture() {
94 provider_->ContextGL()->DeleteTextures(1, &texture_id_);
99 scoped_refptr<cc::ContextProvider> provider_;
103 DISALLOW_COPY_AND_ASSIGN(OwnedTexture);
106 class ImageTransportClientTexture : public OwnedTexture {
108 ImageTransportClientTexture(const scoped_refptr<ContextProvider>& provider,
109 float device_scale_factor,
111 : OwnedTexture(provider,
116 virtual void Consume(const std::string& mailbox_name,
117 const gfx::Size& new_size) OVERRIDE {
118 DCHECK(mailbox_name.size() == GL_MAILBOX_SIZE_CHROMIUM);
119 mailbox_name_ = mailbox_name;
120 if (mailbox_name.empty())
123 DCHECK(provider_ && texture_id_);
124 GLES2Interface* gl = provider_->ContextGL();
125 gl->BindTexture(GL_TEXTURE_2D, texture_id_);
126 gl->ConsumeTextureCHROMIUM(
127 GL_TEXTURE_2D, reinterpret_cast<const GLbyte*>(mailbox_name.c_str()));
129 gl->ShallowFlushCHROMIUM();
132 virtual std::string Produce() OVERRIDE { return mailbox_name_; }
135 virtual ~ImageTransportClientTexture() {}
138 std::string mailbox_name_;
139 DISALLOW_COPY_AND_ASSIGN(ImageTransportClientTexture);
142 GpuProcessTransportFactory::GpuProcessTransportFactory()
143 : callback_factory_(this) {
144 output_surface_proxy_ = new BrowserCompositorOutputSurfaceProxy(
145 &output_surface_map_);
148 GpuProcessTransportFactory::~GpuProcessTransportFactory() {
149 DCHECK(per_compositor_data_.empty());
151 // Make sure the lost context callback doesn't try to run during destruction.
152 callback_factory_.InvalidateWeakPtrs();
155 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
156 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext() {
157 return CreateContextCommon(0);
160 scoped_ptr<cc::SoftwareOutputDevice> CreateSoftwareOutputDevice(
161 ui::Compositor* compositor) {
163 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceWin(
165 #elif defined(USE_OZONE)
166 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceOzone(
168 #elif defined(USE_X11)
169 return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceX11(
174 return scoped_ptr<cc::SoftwareOutputDevice>();
177 scoped_ptr<cc::OutputSurface> GpuProcessTransportFactory::CreateOutputSurface(
178 ui::Compositor* compositor, bool software_fallback) {
179 PerCompositorData* data = per_compositor_data_[compositor];
181 data = CreatePerCompositorData(compositor);
183 bool force_software_renderer = false;
185 if (::GetProp(compositor->widget(), kForceSoftwareCompositor)) {
186 force_software_renderer = reinterpret_cast<bool>(
187 ::RemoveProp(compositor->widget(), kForceSoftwareCompositor));
191 scoped_refptr<ContextProviderCommandBuffer> context_provider;
193 // Software fallback does not happen on Chrome OS.
194 #if defined(OS_CHROMEOS)
195 software_fallback = false;
198 CommandLine* command_line = CommandLine::ForCurrentProcess();
199 if (!command_line->HasSwitch(switches::kUIEnableSoftwareCompositing) &&
200 !force_software_renderer && !software_fallback) {
201 context_provider = ContextProviderCommandBuffer::Create(
202 GpuProcessTransportFactory::CreateContextCommon(data->surface_id),
206 UMA_HISTOGRAM_BOOLEAN("Aura.CreatedGpuBrowserCompositor", !!context_provider);
208 if (!context_provider.get()) {
209 if (ui::Compositor::WasInitializedWithThread()) {
210 LOG(FATAL) << "Failed to create UI context, but can't use software"
211 " compositing with browser threaded compositing. Aborting.";
214 scoped_ptr<SoftwareBrowserCompositorOutputSurface> surface(
215 new SoftwareBrowserCompositorOutputSurface(
216 output_surface_proxy_,
217 CreateSoftwareOutputDevice(compositor),
218 per_compositor_data_[compositor]->surface_id,
219 &output_surface_map_,
220 base::MessageLoopProxy::current().get(),
221 compositor->AsWeakPtr()));
222 return surface.PassAs<cc::OutputSurface>();
225 scoped_refptr<base::SingleThreadTaskRunner> compositor_thread_task_runner =
226 ui::Compositor::GetCompositorMessageLoop();
227 if (!compositor_thread_task_runner.get())
228 compositor_thread_task_runner = base::MessageLoopProxy::current();
230 // Here we know the GpuProcessHost has been set up, because we created a
232 output_surface_proxy_->ConnectToGpuProcessHost(
233 compositor_thread_task_runner.get());
235 scoped_ptr<BrowserCompositorOutputSurface> surface(
236 new GpuBrowserCompositorOutputSurface(
238 per_compositor_data_[compositor]->surface_id,
239 &output_surface_map_,
240 base::MessageLoopProxy::current().get(),
241 compositor->AsWeakPtr()));
242 if (data->reflector.get()) {
243 data->reflector->CreateSharedTexture();
244 data->reflector->AttachToOutputSurface(surface.get());
247 return surface.PassAs<cc::OutputSurface>();
250 scoped_refptr<ui::Reflector> GpuProcessTransportFactory::CreateReflector(
251 ui::Compositor* source,
253 PerCompositorData* data = per_compositor_data_[source];
256 if (data->reflector.get())
257 RemoveObserver(data->reflector.get());
259 data->reflector = new ReflectorImpl(
260 source, target, &output_surface_map_, data->surface_id);
261 AddObserver(data->reflector.get());
262 return data->reflector;
265 void GpuProcessTransportFactory::RemoveReflector(
266 scoped_refptr<ui::Reflector> reflector) {
267 ReflectorImpl* reflector_impl =
268 static_cast<ReflectorImpl*>(reflector.get());
269 PerCompositorData* data =
270 per_compositor_data_[reflector_impl->mirrored_compositor()];
272 RemoveObserver(reflector_impl);
273 data->reflector->Shutdown();
274 data->reflector = NULL;
277 void GpuProcessTransportFactory::RemoveCompositor(ui::Compositor* compositor) {
278 PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
279 if (it == per_compositor_data_.end())
281 PerCompositorData* data = it->second;
283 GpuSurfaceTracker::Get()->RemoveSurface(data->surface_id);
285 per_compositor_data_.erase(it);
286 if (per_compositor_data_.empty())
290 bool GpuProcessTransportFactory::DoesCreateTestContexts() { return false; }
292 ui::ContextFactory* GpuProcessTransportFactory::AsContextFactory() {
296 gfx::GLSurfaceHandle GpuProcessTransportFactory::GetSharedSurfaceHandle() {
297 // TODO(sievers): crbug.com/329737
298 // Creating the context here hurts startup performance.
299 // Remove this once all tests are happy.
300 SharedMainThreadContextProvider();
302 gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
303 gfx::kNullPluginWindow, gfx::TEXTURE_TRANSPORT);
304 handle.parent_client_id =
305 BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
309 scoped_refptr<ui::Texture> GpuProcessTransportFactory::CreateTransportClient(
310 float device_scale_factor) {
311 scoped_refptr<cc::ContextProvider> provider =
312 SharedMainThreadContextProvider();
315 GLuint texture_id = 0;
316 provider->ContextGL()->GenTextures(1, &texture_id);
317 scoped_refptr<ImageTransportClientTexture> image(
318 new ImageTransportClientTexture(
319 provider, device_scale_factor, texture_id));
323 scoped_refptr<ui::Texture> GpuProcessTransportFactory::CreateOwnedTexture(
324 const gfx::Size& size,
325 float device_scale_factor,
326 unsigned int texture_id) {
327 scoped_refptr<cc::ContextProvider> provider =
328 SharedMainThreadContextProvider();
331 scoped_refptr<OwnedTexture> image(new OwnedTexture(
332 provider, size, device_scale_factor, texture_id));
336 GLHelper* GpuProcessTransportFactory::GetGLHelper() {
338 scoped_refptr<cc::ContextProvider> provider =
339 SharedMainThreadContextProvider();
341 gl_helper_.reset(new GLHelper(provider->ContextGL(),
342 provider->ContextSupport()));
344 return gl_helper_.get();
347 void GpuProcessTransportFactory::AddObserver(
348 ImageTransportFactoryObserver* observer) {
349 observer_list_.AddObserver(observer);
352 void GpuProcessTransportFactory::RemoveObserver(
353 ImageTransportFactoryObserver* observer) {
354 observer_list_.RemoveObserver(observer);
357 scoped_refptr<cc::ContextProvider>
358 GpuProcessTransportFactory::OffscreenCompositorContextProvider() {
359 // Don't check for DestroyedOnMainThread() here. We hear about context
360 // loss for this context through the lost context callback. If the context
361 // is lost, we want to leave this ContextProvider available until the lost
362 // context notification is sent to the ImageTransportFactoryObserver clients.
363 if (offscreen_compositor_contexts_.get())
364 return offscreen_compositor_contexts_;
366 offscreen_compositor_contexts_ = ContextProviderCommandBuffer::Create(
367 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext(),
368 "Compositor-Offscreen");
370 return offscreen_compositor_contexts_;
373 scoped_refptr<cc::ContextProvider>
374 GpuProcessTransportFactory::SharedMainThreadContextProvider() {
375 if (shared_main_thread_contexts_.get())
376 return shared_main_thread_contexts_;
378 if (ui::Compositor::WasInitializedWithThread()) {
379 // In threaded compositing mode, we have to create our own context for the
380 // main thread since the compositor's context will be bound to the
381 // compositor thread.
382 shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
383 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext(),
384 "Offscreen-MainThread");
386 // In single threaded compositing mode, we can just reuse the compositor's
388 shared_main_thread_contexts_ =
389 static_cast<ContextProviderCommandBuffer*>(
390 OffscreenCompositorContextProvider().get());
393 if (shared_main_thread_contexts_) {
394 shared_main_thread_contexts_->SetLostContextCallback(
395 base::Bind(&GpuProcessTransportFactory::
396 OnLostMainThreadSharedContextInsideCallback,
397 callback_factory_.GetWeakPtr()));
398 if (!shared_main_thread_contexts_->BindToCurrentThread()) {
399 shared_main_thread_contexts_ = NULL;
400 offscreen_compositor_contexts_ = NULL;
403 return shared_main_thread_contexts_;
406 GpuProcessTransportFactory::PerCompositorData*
407 GpuProcessTransportFactory::CreatePerCompositorData(
408 ui::Compositor* compositor) {
409 DCHECK(!per_compositor_data_[compositor]);
411 gfx::AcceleratedWidget widget = compositor->widget();
412 GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get();
414 PerCompositorData* data = new PerCompositorData;
415 data->surface_id = tracker->AddSurfaceForNativeWidget(widget);
416 tracker->SetSurfaceHandle(
418 gfx::GLSurfaceHandle(widget, gfx::NATIVE_DIRECT));
420 per_compositor_data_[compositor] = data;
425 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
426 GpuProcessTransportFactory::CreateContextCommon(int surface_id) {
427 if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor())
428 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
429 blink::WebGraphicsContext3D::Attributes attrs;
430 attrs.shareResources = true;
432 attrs.stencil = false;
433 attrs.antialias = false;
434 attrs.noAutomaticFlushes = true;
435 CauseForGpuLaunch cause =
436 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
437 scoped_refptr<GpuChannelHost> gpu_channel_host(
438 BrowserGpuChannelHostFactory::instance()->EstablishGpuChannelSync(cause));
439 if (!gpu_channel_host)
440 return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
441 GURL url("chrome://gpu/GpuProcessTransportFactory::CreateContextCommon");
442 scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
443 new WebGraphicsContext3DCommandBufferImpl(
446 gpu_channel_host.get(),
449 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits()));
450 return context.Pass();
453 void GpuProcessTransportFactory::OnLostMainThreadSharedContextInsideCallback() {
454 base::MessageLoop::current()->PostTask(
456 base::Bind(&GpuProcessTransportFactory::OnLostMainThreadSharedContext,
457 callback_factory_.GetWeakPtr()));
460 void GpuProcessTransportFactory::OnLostMainThreadSharedContext() {
461 LOG(ERROR) << "Lost UI shared context.";
463 // Keep old resources around while we call the observers, but ensure that
464 // new resources are created if needed.
465 // Kill shared contexts for both threads in tandem so they are always in
466 // the same share group.
467 scoped_refptr<cc::ContextProvider> lost_offscreen_compositor_contexts =
468 offscreen_compositor_contexts_;
469 scoped_refptr<cc::ContextProvider> lost_shared_main_thread_contexts =
470 shared_main_thread_contexts_;
471 offscreen_compositor_contexts_ = NULL;
472 shared_main_thread_contexts_ = NULL;
474 scoped_ptr<GLHelper> lost_gl_helper = gl_helper_.Pass();
476 FOR_EACH_OBSERVER(ImageTransportFactoryObserver,
480 // Kill things that use the shared context before killing the shared context.
481 lost_gl_helper.reset();
482 lost_offscreen_compositor_contexts = NULL;
483 lost_shared_main_thread_contexts = NULL;
486 } // namespace content