Upstream version 5.34.92.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 "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"
38
39 #if defined(OS_WIN)
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"
45 #endif
46
47 using cc::ContextProvider;
48 using gpu::gles2::GLES2Interface;
49
50 namespace content {
51
52 struct GpuProcessTransportFactory::PerCompositorData {
53   int surface_id;
54   scoped_refptr<ReflectorImpl> reflector;
55 };
56
57 class OwnedTexture : public ui::Texture, ImageTransportFactoryObserver {
58  public:
59   OwnedTexture(const scoped_refptr<ContextProvider>& provider,
60                const gfx::Size& size,
61                float device_scale_factor,
62                GLuint texture_id)
63       : ui::Texture(true, size, device_scale_factor),
64         provider_(provider),
65         texture_id_(texture_id) {
66     ImageTransportFactory::GetInstance()->AddObserver(this);
67   }
68
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
73     // it's still valid.
74     if (provider_ && provider_->IsContextLost())
75       texture_id_ = 0u;
76     return texture_id_;
77   }
78
79   // ImageTransportFactory overrides:
80   virtual void OnLostResources() OVERRIDE {
81     DeleteTexture();
82     provider_ = NULL;
83   }
84
85  protected:
86   virtual ~OwnedTexture() {
87     ImageTransportFactory::GetInstance()->RemoveObserver(this);
88     DeleteTexture();
89   }
90
91  protected:
92   void DeleteTexture() {
93     if (texture_id_) {
94       provider_->ContextGL()->DeleteTextures(1, &texture_id_);
95       texture_id_ = 0;
96     }
97   }
98
99   scoped_refptr<cc::ContextProvider> provider_;
100   GLuint texture_id_;
101
102  private:
103   DISALLOW_COPY_AND_ASSIGN(OwnedTexture);
104 };
105
106 class ImageTransportClientTexture : public OwnedTexture {
107  public:
108   ImageTransportClientTexture(const scoped_refptr<ContextProvider>& provider,
109                               float device_scale_factor,
110                               GLuint texture_id)
111       : OwnedTexture(provider,
112                      gfx::Size(0, 0),
113                      device_scale_factor,
114                      texture_id) {}
115
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())
121       return;
122
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()));
128     size_ = new_size;
129     gl->ShallowFlushCHROMIUM();
130   }
131
132   virtual std::string Produce() OVERRIDE { return mailbox_name_; }
133
134  protected:
135   virtual ~ImageTransportClientTexture() {}
136
137  private:
138   std::string mailbox_name_;
139   DISALLOW_COPY_AND_ASSIGN(ImageTransportClientTexture);
140 };
141
142 GpuProcessTransportFactory::GpuProcessTransportFactory()
143     : callback_factory_(this) {
144   output_surface_proxy_ = new BrowserCompositorOutputSurfaceProxy(
145       &output_surface_map_);
146 }
147
148 GpuProcessTransportFactory::~GpuProcessTransportFactory() {
149   DCHECK(per_compositor_data_.empty());
150
151   // Make sure the lost context callback doesn't try to run during destruction.
152   callback_factory_.InvalidateWeakPtrs();
153 }
154
155 scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
156 GpuProcessTransportFactory::CreateOffscreenCommandBufferContext() {
157   return CreateContextCommon(0);
158 }
159
160 scoped_ptr<cc::SoftwareOutputDevice> CreateSoftwareOutputDevice(
161     ui::Compositor* compositor) {
162 #if defined(OS_WIN)
163   return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceWin(
164       compositor));
165 #elif defined(USE_OZONE)
166   return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceOzone(
167       compositor));
168 #elif defined(USE_X11)
169   return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceX11(
170       compositor));
171 #endif
172
173   NOTREACHED();
174   return scoped_ptr<cc::SoftwareOutputDevice>();
175 }
176
177 scoped_ptr<cc::OutputSurface> GpuProcessTransportFactory::CreateOutputSurface(
178     ui::Compositor* compositor, bool software_fallback) {
179   PerCompositorData* data = per_compositor_data_[compositor];
180   if (!data)
181     data = CreatePerCompositorData(compositor);
182
183   bool force_software_renderer = false;
184 #if defined(OS_WIN)
185   if (::GetProp(compositor->widget(), kForceSoftwareCompositor)) {
186     force_software_renderer = reinterpret_cast<bool>(
187         ::RemoveProp(compositor->widget(), kForceSoftwareCompositor));
188   }
189 #endif
190
191   scoped_refptr<ContextProviderCommandBuffer> context_provider;
192
193   // Software fallback does not happen on Chrome OS.
194 #if defined(OS_CHROMEOS)
195   software_fallback = false;
196 #endif
197
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),
203         "Compositor");
204   }
205
206   UMA_HISTOGRAM_BOOLEAN("Aura.CreatedGpuBrowserCompositor", !!context_provider);
207
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.";
212     }
213
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>();
223   }
224
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();
229
230   // Here we know the GpuProcessHost has been set up, because we created a
231   // context.
232   output_surface_proxy_->ConnectToGpuProcessHost(
233       compositor_thread_task_runner.get());
234
235   scoped_ptr<BrowserCompositorOutputSurface> surface(
236       new GpuBrowserCompositorOutputSurface(
237           context_provider,
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());
245   }
246
247   return surface.PassAs<cc::OutputSurface>();
248 }
249
250 scoped_refptr<ui::Reflector> GpuProcessTransportFactory::CreateReflector(
251     ui::Compositor* source,
252     ui::Layer* target) {
253   PerCompositorData* data = per_compositor_data_[source];
254   DCHECK(data);
255
256   if (data->reflector.get())
257     RemoveObserver(data->reflector.get());
258
259   data->reflector = new ReflectorImpl(
260       source, target, &output_surface_map_, data->surface_id);
261   AddObserver(data->reflector.get());
262   return data->reflector;
263 }
264
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()];
271   DCHECK(data);
272   RemoveObserver(reflector_impl);
273   data->reflector->Shutdown();
274   data->reflector = NULL;
275 }
276
277 void GpuProcessTransportFactory::RemoveCompositor(ui::Compositor* compositor) {
278   PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
279   if (it == per_compositor_data_.end())
280     return;
281   PerCompositorData* data = it->second;
282   DCHECK(data);
283   GpuSurfaceTracker::Get()->RemoveSurface(data->surface_id);
284   delete data;
285   per_compositor_data_.erase(it);
286   if (per_compositor_data_.empty())
287     gl_helper_.reset();
288 }
289
290 bool GpuProcessTransportFactory::DoesCreateTestContexts() { return false; }
291
292 ui::ContextFactory* GpuProcessTransportFactory::AsContextFactory() {
293   return this;
294 }
295
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();
301
302   gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
303       gfx::kNullPluginWindow, gfx::TEXTURE_TRANSPORT);
304   handle.parent_client_id =
305       BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
306   return handle;
307 }
308
309 scoped_refptr<ui::Texture> GpuProcessTransportFactory::CreateTransportClient(
310     float device_scale_factor) {
311   scoped_refptr<cc::ContextProvider> provider =
312       SharedMainThreadContextProvider();
313   if (!provider.get())
314     return NULL;
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));
320   return image;
321 }
322
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();
329   if (!provider.get())
330     return NULL;
331   scoped_refptr<OwnedTexture> image(new OwnedTexture(
332       provider, size, device_scale_factor, texture_id));
333   return image;
334 }
335
336 GLHelper* GpuProcessTransportFactory::GetGLHelper() {
337   if (!gl_helper_) {
338     scoped_refptr<cc::ContextProvider> provider =
339         SharedMainThreadContextProvider();
340     if (provider.get())
341       gl_helper_.reset(new GLHelper(provider->ContextGL(),
342                                     provider->ContextSupport()));
343   }
344   return gl_helper_.get();
345 }
346
347 void GpuProcessTransportFactory::AddObserver(
348     ImageTransportFactoryObserver* observer) {
349   observer_list_.AddObserver(observer);
350 }
351
352 void GpuProcessTransportFactory::RemoveObserver(
353     ImageTransportFactoryObserver* observer) {
354   observer_list_.RemoveObserver(observer);
355 }
356
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_;
365
366   offscreen_compositor_contexts_ = ContextProviderCommandBuffer::Create(
367       GpuProcessTransportFactory::CreateOffscreenCommandBufferContext(),
368       "Compositor-Offscreen");
369
370   return offscreen_compositor_contexts_;
371 }
372
373 scoped_refptr<cc::ContextProvider>
374 GpuProcessTransportFactory::SharedMainThreadContextProvider() {
375   if (shared_main_thread_contexts_.get())
376     return shared_main_thread_contexts_;
377
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");
385   } else {
386     // In single threaded compositing mode, we can just reuse the compositor's
387     // shared context.
388     shared_main_thread_contexts_ =
389         static_cast<ContextProviderCommandBuffer*>(
390             OffscreenCompositorContextProvider().get());
391   }
392
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;
401     }
402   }
403   return shared_main_thread_contexts_;
404 }
405
406 GpuProcessTransportFactory::PerCompositorData*
407 GpuProcessTransportFactory::CreatePerCompositorData(
408     ui::Compositor* compositor) {
409   DCHECK(!per_compositor_data_[compositor]);
410
411   gfx::AcceleratedWidget widget = compositor->widget();
412   GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get();
413
414   PerCompositorData* data = new PerCompositorData;
415   data->surface_id = tracker->AddSurfaceForNativeWidget(widget);
416   tracker->SetSurfaceHandle(
417       data->surface_id,
418       gfx::GLSurfaceHandle(widget, gfx::NATIVE_DIRECT));
419
420   per_compositor_data_[compositor] = data;
421
422   return data;
423 }
424
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;
431   attrs.depth = false;
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(
444           surface_id,
445           url,
446           gpu_channel_host.get(),
447           attrs,
448           false,
449           WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits()));
450   return context.Pass();
451 }
452
453 void GpuProcessTransportFactory::OnLostMainThreadSharedContextInsideCallback() {
454   base::MessageLoop::current()->PostTask(
455       FROM_HERE,
456       base::Bind(&GpuProcessTransportFactory::OnLostMainThreadSharedContext,
457                  callback_factory_.GetWeakPtr()));
458 }
459
460 void GpuProcessTransportFactory::OnLostMainThreadSharedContext() {
461   LOG(ERROR) << "Lost UI shared context.";
462
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;
473
474   scoped_ptr<GLHelper> lost_gl_helper = gl_helper_.Pass();
475
476   FOR_EACH_OBSERVER(ImageTransportFactoryObserver,
477                     observer_list_,
478                     OnLostResources());
479
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;
484 }
485
486 }  // namespace content