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