summaryrefslogtreecommitdiffstats
path: root/content/browser/compositor/gpu_process_transport_factory.cc
blob: e1b4cfa4a4b9015b940e4a41b1db39cc81ff926c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/compositor/gpu_process_transport_factory.h"

#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/location.h"
#include "base/metrics/histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/simple_thread.h"
#include "base/threading/thread.h"
#include "cc/output/compositor_frame.h"
#include "cc/output/output_surface.h"
#include "cc/raster/task_graph_runner.h"
#include "cc/surfaces/onscreen_display_client.h"
#include "cc/surfaces/surface_display_output_surface.h"
#include "cc/surfaces/surface_manager.h"
#include "content/browser/compositor/browser_compositor_output_surface.h"
#include "content/browser/compositor/browser_compositor_overlay_candidate_validator.h"
#include "content/browser/compositor/gpu_browser_compositor_output_surface.h"
#include "content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h"
#include "content/browser/compositor/offscreen_browser_compositor_output_surface.h"
#include "content/browser/compositor/reflector_impl.h"
#include "content/browser/compositor/software_browser_compositor_output_surface.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
#include "content/browser/gpu/compositor_util.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/gpu/client/context_provider_command_buffer.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/gpu_channel_host.h"
#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
#include "content/common/gpu/gpu_process_launch_causes.h"
#include "content/common/host_shared_bitmap_manager.h"
#include "content/public/common/content_switches.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/command_buffer/common/mailbox.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_constants.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/native_widget_types.h"

#if defined(OS_WIN)
#include "content/browser/compositor/software_output_device_win.h"
#elif defined(USE_OZONE)
#include "content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h"
#include "content/browser/compositor/software_output_device_ozone.h"
#include "ui/ozone/public/overlay_candidates_ozone.h"
#include "ui/ozone/public/overlay_manager_ozone.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/ozone_switches.h"
#elif defined(USE_X11)
#include "content/browser/compositor/software_output_device_x11.h"
#elif defined(OS_MACOSX)
#include "content/browser/compositor/software_output_device_mac.h"
#endif

using cc::ContextProvider;
using gpu::gles2::GLES2Interface;

static const int kNumRetriesBeforeSoftwareFallback = 4;

namespace content {
namespace {

class RasterThread : public base::SimpleThread {
 public:
  RasterThread(cc::TaskGraphRunner* task_graph_runner)
      : base::SimpleThread("CompositorTileWorker1"),
        task_graph_runner_(task_graph_runner) {}

  // Overridden from base::SimpleThread:
  void Run() override { task_graph_runner_->Run(); }

 private:
  cc::TaskGraphRunner* task_graph_runner_;

  DISALLOW_COPY_AND_ASSIGN(RasterThread);
};

}  // namespace

struct GpuProcessTransportFactory::PerCompositorData {
  int surface_id;
  BrowserCompositorOutputSurface* surface;
  ReflectorImpl* reflector;
  scoped_ptr<cc::OnscreenDisplayClient> display_client;

  PerCompositorData() : surface_id(0), surface(nullptr), reflector(nullptr) {}
};

GpuProcessTransportFactory::GpuProcessTransportFactory()
    : next_surface_id_namespace_(1u),
      task_graph_runner_(new cc::TaskGraphRunner),
      callback_factory_(this) {
  ui::Layer::InitializeUILayerSettings();

  if (UseSurfacesEnabled())
    surface_manager_ = make_scoped_ptr(new cc::SurfaceManager);

  if (ui::IsUIImplSidePaintingEnabled()) {
    raster_thread_.reset(new RasterThread(task_graph_runner_.get()));
    raster_thread_->Start();
  }
#if defined(OS_WIN)
  software_backing_.reset(new OutputDeviceBacking);
#endif
}

GpuProcessTransportFactory::~GpuProcessTransportFactory() {
  DCHECK(per_compositor_data_.empty());

  // Make sure the lost context callback doesn't try to run during destruction.
  callback_factory_.InvalidateWeakPtrs();

  task_graph_runner_->Shutdown();
  if (raster_thread_)
    raster_thread_->Join();
}

scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
GpuProcessTransportFactory::CreateOffscreenCommandBufferContext() {
  CauseForGpuLaunch cause =
      CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
  scoped_refptr<GpuChannelHost> gpu_channel_host(
      BrowserGpuChannelHostFactory::instance()->EstablishGpuChannelSync(cause));
  return CreateContextCommon(gpu_channel_host, 0);
}

scoped_ptr<cc::SoftwareOutputDevice>
GpuProcessTransportFactory::CreateSoftwareOutputDevice(
    ui::Compositor* compositor) {
#if defined(OS_WIN)
  return scoped_ptr<cc::SoftwareOutputDevice>(
      new SoftwareOutputDeviceWin(software_backing_.get(), compositor));
#elif defined(USE_OZONE)
  return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceOzone(
      compositor));
#elif defined(USE_X11)
  return scoped_ptr<cc::SoftwareOutputDevice>(new SoftwareOutputDeviceX11(
      compositor));
#elif defined(OS_MACOSX)
  return scoped_ptr<cc::SoftwareOutputDevice>(
      new SoftwareOutputDeviceMac(compositor));
#else
  NOTREACHED();
  return scoped_ptr<cc::SoftwareOutputDevice>();
#endif
}

scoped_ptr<BrowserCompositorOverlayCandidateValidator>
CreateOverlayCandidateValidator(gfx::AcceleratedWidget widget) {
#if defined(USE_OZONE)
  scoped_ptr<ui::OverlayCandidatesOzone> overlay_candidates =
      ui::OzonePlatform::GetInstance()
          ->GetOverlayManager()
          ->CreateOverlayCandidates(widget);
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (overlay_candidates &&
      (command_line->HasSwitch(switches::kEnableHardwareOverlays) ||
       command_line->HasSwitch(switches::kOzoneTestSingleOverlaySupport))) {
    return scoped_ptr<BrowserCompositorOverlayCandidateValidator>(
        new BrowserCompositorOverlayCandidateValidatorOzone(
            widget, overlay_candidates.Pass()));
  }
#endif
  return scoped_ptr<BrowserCompositorOverlayCandidateValidator>();
}

static bool ShouldCreateGpuOutputSurface(ui::Compositor* compositor) {
#if defined(OS_CHROMEOS)
  // Software fallback does not happen on Chrome OS.
  return true;
#endif

#if defined(OS_WIN)
  if (::GetProp(compositor->widget(), kForceSoftwareCompositor) &&
      ::RemoveProp(compositor->widget(), kForceSoftwareCompositor))
    return false;
#endif

  return GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor();
}

void GpuProcessTransportFactory::CreateOutputSurface(
    base::WeakPtr<ui::Compositor> compositor) {
  DCHECK(!!compositor);
  PerCompositorData* data = per_compositor_data_[compositor.get()];
  if (!data) {
    // TODO(robliao): Remove ScopedTracker below once https://crbug.com/466870
    // is fixed.
    tracked_objects::ScopedTracker tracking_profile1(
        FROM_HERE_WITH_EXPLICIT_FUNCTION(
            "466870 GpuProcessTransportFactory::CreateOutputSurface1"));
    data = CreatePerCompositorData(compositor.get());
  } else {
    // TODO(piman): Use GpuSurfaceTracker to map ids to surfaces instead of an
    // output_surface_map_ here.
    output_surface_map_.Remove(data->surface_id);
    data->surface = nullptr;
  }

  // TODO(robliao): Remove ScopedTracker below once https://crbug.com/466870
  // is fixed.
  tracked_objects::ScopedTracker tracking_profile2(
      FROM_HERE_WITH_EXPLICIT_FUNCTION(
          "466870 GpuProcessTransportFactory::CreateOutputSurface2"));

  bool create_gpu_output_surface =
      ShouldCreateGpuOutputSurface(compositor.get());
  if (create_gpu_output_surface) {
    // TODO(robliao): Remove ScopedTracker below once https://crbug.com/466870
    // is fixed.
    tracked_objects::ScopedTracker tracking_profile3(
        FROM_HERE_WITH_EXPLICIT_FUNCTION(
            "466870 GpuProcessTransportFactory::CreateOutputSurface3"));

    CauseForGpuLaunch cause =
        CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
    BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel(
        cause, base::Bind(&GpuProcessTransportFactory::EstablishedGpuChannel,
                          callback_factory_.GetWeakPtr(), compositor,
                          create_gpu_output_surface, 0));
  } else {
    // TODO(robliao): Remove ScopedTracker below once https://crbug.com/466870
    // is fixed.
    tracked_objects::ScopedTracker tracking_profile4(
        FROM_HERE_WITH_EXPLICIT_FUNCTION(
            "466870 GpuProcessTransportFactory::CreateOutputSurface4"));

    EstablishedGpuChannel(compositor, create_gpu_output_surface, 0);
  }
}

void GpuProcessTransportFactory::EstablishedGpuChannel(
    base::WeakPtr<ui::Compositor> compositor,
    bool create_gpu_output_surface,
    int num_attempts) {
  if (!compositor)
    return;
  PerCompositorData* data = per_compositor_data_[compositor.get()];
  DCHECK(data);

  if (num_attempts > kNumRetriesBeforeSoftwareFallback) {
#if defined(OS_CHROMEOS)
    LOG(FATAL) << "Unable to create a UI graphics context, and cannot use "
               << "software compositing on ChromeOS.";
#endif
    create_gpu_output_surface = false;
  }

  scoped_refptr<ContextProviderCommandBuffer> context_provider;
  if (create_gpu_output_surface) {
    scoped_refptr<GpuChannelHost> gpu_channel_host =
        BrowserGpuChannelHostFactory::instance()->GetGpuChannel();
    if (gpu_channel_host.get()) {
      context_provider = ContextProviderCommandBuffer::Create(
          GpuProcessTransportFactory::CreateContextCommon(gpu_channel_host,
                                                          data->surface_id),
          BROWSER_COMPOSITOR_ONSCREEN_CONTEXT);
      if (context_provider && !context_provider->BindToCurrentThread())
        context_provider = nullptr;
    }

    UMA_HISTOGRAM_BOOLEAN("Aura.CreatedGpuBrowserCompositor",
                          !!context_provider.get());

    if (!context_provider) {
      // Try again.
      CauseForGpuLaunch cause =
          CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE;
      BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel(
          cause, base::Bind(&GpuProcessTransportFactory::EstablishedGpuChannel,
                            callback_factory_.GetWeakPtr(), compositor,
                            create_gpu_output_surface, num_attempts + 1));
      return;
    }
  }

  scoped_ptr<BrowserCompositorOutputSurface> surface;
  if (!create_gpu_output_surface) {
    surface = make_scoped_ptr(new SoftwareBrowserCompositorOutputSurface(
        CreateSoftwareOutputDevice(compositor.get()),
        compositor->vsync_manager()));
  } else {
    DCHECK(context_provider);
    if (!data->surface_id) {
      surface = make_scoped_ptr(new OffscreenBrowserCompositorOutputSurface(
          context_provider, compositor->vsync_manager(),
          scoped_ptr<BrowserCompositorOverlayCandidateValidator>()));
    } else
#if defined(USE_OZONE)
        if (ui::OzonePlatform::GetInstance()
                ->GetOverlayManager()
                ->CanShowPrimaryPlaneAsOverlay()) {
      surface =
          make_scoped_ptr(new GpuSurfacelessBrowserCompositorOutputSurface(
              context_provider, data->surface_id, compositor->vsync_manager(),
              CreateOverlayCandidateValidator(compositor->widget()), GL_RGB,
              BrowserGpuMemoryBufferManager::current()));
    } else
#endif
    {
      surface = make_scoped_ptr(new GpuBrowserCompositorOutputSurface(
          context_provider, compositor->vsync_manager(),
          CreateOverlayCandidateValidator(compositor->widget())));
    }
  }

  // TODO(piman): Use GpuSurfaceTracker to map ids to surfaces instead of an
  // output_surface_map_ here.
  output_surface_map_.AddWithID(surface.get(), data->surface_id);
  data->surface = surface.get();
  if (data->reflector)
    data->reflector->OnSourceSurfaceReady(data->surface);

  if (!UseSurfacesEnabled()) {
    compositor->SetOutputSurface(surface.Pass());
    return;
  }

  // This gets a bit confusing. Here we have a ContextProvider in the |surface|
  // configured to render directly to this widget. We need to make an
  // OnscreenDisplayClient associated with that context, then return a
  // SurfaceDisplayOutputSurface set up to draw to the display's surface.
  cc::SurfaceManager* manager = surface_manager_.get();
  scoped_ptr<cc::OnscreenDisplayClient> display_client(
      new cc::OnscreenDisplayClient(
          surface.Pass(), manager, HostSharedBitmapManager::current(),
          BrowserGpuMemoryBufferManager::current(),
          compositor->GetRendererSettings(), compositor->task_runner()));

  scoped_ptr<cc::SurfaceDisplayOutputSurface> output_surface(
      new cc::SurfaceDisplayOutputSurface(
          manager, compositor->surface_id_allocator(), context_provider));
  display_client->set_surface_output_surface(output_surface.get());
  output_surface->set_display_client(display_client.get());
  display_client->display()->Resize(compositor->size());
  data->display_client = display_client.Pass();
  compositor->SetOutputSurface(output_surface.Pass());
}

scoped_ptr<ui::Reflector> GpuProcessTransportFactory::CreateReflector(
    ui::Compositor* source_compositor,
    ui::Layer* target_layer) {
  PerCompositorData* source_data = per_compositor_data_[source_compositor];
  DCHECK(source_data);

  scoped_ptr<ReflectorImpl> reflector(
      new ReflectorImpl(source_compositor, target_layer));
  source_data->reflector = reflector.get();
  if (BrowserCompositorOutputSurface* source_surface = source_data->surface)
    reflector->OnSourceSurfaceReady(source_surface);
  return reflector.Pass();
}

void GpuProcessTransportFactory::RemoveReflector(ui::Reflector* reflector) {
  ReflectorImpl* reflector_impl = static_cast<ReflectorImpl*>(reflector);
  PerCompositorData* data =
      per_compositor_data_[reflector_impl->mirrored_compositor()];
  DCHECK(data);
  data->reflector->Shutdown();
  data->reflector = nullptr;
}

void GpuProcessTransportFactory::RemoveCompositor(ui::Compositor* compositor) {
  PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
  if (it == per_compositor_data_.end())
    return;
  PerCompositorData* data = it->second;
  DCHECK(data);
  // TODO(piman): Use GpuSurfaceTracker to map ids to surfaces instead of an
  // output_surface_map_ here.
  if (data->surface)
    output_surface_map_.Remove(data->surface_id);
  if (data->surface_id)
    GpuSurfaceTracker::Get()->RemoveSurface(data->surface_id);
  delete data;
  per_compositor_data_.erase(it);
  if (per_compositor_data_.empty()) {
    // Destroying the GLHelper may cause some async actions to be cancelled,
    // causing things to request a new GLHelper. Due to crbug.com/176091 the
    // GLHelper created in this case would be lost/leaked if we just reset()
    // on the |gl_helper_| variable directly. So instead we call reset() on a
    // local scoped_ptr.
    scoped_ptr<GLHelper> helper = gl_helper_.Pass();

    // If there are any observer left at this point, make sure they clean up
    // before we destroy the GLHelper.
    FOR_EACH_OBSERVER(
        ImageTransportFactoryObserver, observer_list_, OnLostResources());

    helper.reset();
    DCHECK(!gl_helper_) << "Destroying the GLHelper should not cause a new "
                           "GLHelper to be created.";
  }
}

bool GpuProcessTransportFactory::DoesCreateTestContexts() { return false; }

uint32 GpuProcessTransportFactory::GetImageTextureTarget(
    gfx::GpuMemoryBuffer::Format format,
    gfx::GpuMemoryBuffer::Usage usage) {
  return BrowserGpuChannelHostFactory::GetImageTextureTarget(format, usage);
}

cc::SharedBitmapManager* GpuProcessTransportFactory::GetSharedBitmapManager() {
  return HostSharedBitmapManager::current();
}

gpu::GpuMemoryBufferManager*
GpuProcessTransportFactory::GetGpuMemoryBufferManager() {
  return BrowserGpuMemoryBufferManager::current();
}

cc::TaskGraphRunner* GpuProcessTransportFactory::GetTaskGraphRunner() {
  return task_graph_runner_.get();
}

ui::ContextFactory* GpuProcessTransportFactory::GetContextFactory() {
  return this;
}

gfx::GLSurfaceHandle GpuProcessTransportFactory::GetSharedSurfaceHandle() {
  gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
      gfx::kNullPluginWindow, gfx::NULL_TRANSPORT);
  handle.parent_client_id =
      BrowserGpuChannelHostFactory::instance()->GetGpuChannelId();
  return handle;
}

scoped_ptr<cc::SurfaceIdAllocator>
GpuProcessTransportFactory::CreateSurfaceIdAllocator() {
  scoped_ptr<cc::SurfaceIdAllocator> allocator =
      make_scoped_ptr(new cc::SurfaceIdAllocator(next_surface_id_namespace_++));
  if (GetSurfaceManager())
    allocator->RegisterSurfaceIdNamespace(GetSurfaceManager());
  return allocator;
}

void GpuProcessTransportFactory::ResizeDisplay(ui::Compositor* compositor,
                                               const gfx::Size& size) {
  PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
  if (it == per_compositor_data_.end())
    return;
  PerCompositorData* data = it->second;
  DCHECK(data);
  if (data->display_client)
    data->display_client->display()->Resize(size);
}

cc::SurfaceManager* GpuProcessTransportFactory::GetSurfaceManager() {
  return surface_manager_.get();
}

GLHelper* GpuProcessTransportFactory::GetGLHelper() {
  if (!gl_helper_ && !per_compositor_data_.empty()) {
    scoped_refptr<cc::ContextProvider> provider =
        SharedMainThreadContextProvider();
    if (provider.get())
      gl_helper_.reset(new GLHelper(provider->ContextGL(),
                                    provider->ContextSupport()));
  }
  return gl_helper_.get();
}

void GpuProcessTransportFactory::AddObserver(
    ImageTransportFactoryObserver* observer) {
  observer_list_.AddObserver(observer);
}

void GpuProcessTransportFactory::RemoveObserver(
    ImageTransportFactoryObserver* observer) {
  observer_list_.RemoveObserver(observer);
}

#if defined(OS_MACOSX)
void GpuProcessTransportFactory::OnSurfaceDisplayed(int surface_id) {
  BrowserCompositorOutputSurface* surface = output_surface_map_.Lookup(
      surface_id);
  if (surface)
    surface->OnSurfaceDisplayed();
}

void GpuProcessTransportFactory::SetCompositorSuspendedForRecycle(
    ui::Compositor* compositor,
    bool suspended) {
  PerCompositorDataMap::iterator it = per_compositor_data_.find(compositor);
  if (it == per_compositor_data_.end())
    return;
  PerCompositorData* data = it->second;
  DCHECK(data);
  BrowserCompositorOutputSurface* surface =
      output_surface_map_.Lookup(data->surface_id);
  if (surface)
    surface->SetSurfaceSuspendedForRecycle(suspended);
}

bool GpuProcessTransportFactory::
    SurfaceShouldNotShowFramesAfterSuspendForRecycle(int surface_id) const {
  BrowserCompositorOutputSurface* surface =
      output_surface_map_.Lookup(surface_id);
  if (surface)
    return surface->SurfaceShouldNotShowFramesAfterSuspendForRecycle();
  return false;
}
#endif

scoped_refptr<cc::ContextProvider>
GpuProcessTransportFactory::SharedMainThreadContextProvider() {
  if (shared_main_thread_contexts_.get())
    return shared_main_thread_contexts_;

  // In threaded compositing mode, we have to create our own context for the
  // main thread since the compositor's context will be bound to the
  // compositor thread. When not in threaded mode, we still need a separate
  // context so that skia and gl_helper don't step on each other.
  shared_main_thread_contexts_ = ContextProviderCommandBuffer::Create(
      GpuProcessTransportFactory::CreateOffscreenCommandBufferContext(),
      BROWSER_OFFSCREEN_MAINTHREAD_CONTEXT);

  if (shared_main_thread_contexts_.get()) {
    shared_main_thread_contexts_->SetLostContextCallback(
        base::Bind(&GpuProcessTransportFactory::
                        OnLostMainThreadSharedContextInsideCallback,
                   callback_factory_.GetWeakPtr()));
    if (!shared_main_thread_contexts_->BindToCurrentThread())
      shared_main_thread_contexts_ = NULL;
  }
  return shared_main_thread_contexts_;
}

GpuProcessTransportFactory::PerCompositorData*
GpuProcessTransportFactory::CreatePerCompositorData(
    ui::Compositor* compositor) {
  DCHECK(!per_compositor_data_[compositor]);

  gfx::AcceleratedWidget widget = compositor->widget();
  GpuSurfaceTracker* tracker = GpuSurfaceTracker::Get();

  PerCompositorData* data = new PerCompositorData;
  if (compositor->widget() == gfx::kNullAcceleratedWidget) {
    data->surface_id = 0;
  } else {
    data->surface_id = tracker->AddSurfaceForNativeWidget(widget);
    tracker->SetSurfaceHandle(data->surface_id,
                              gfx::GLSurfaceHandle(widget, gfx::NATIVE_DIRECT));
  }

  per_compositor_data_[compositor] = data;

  return data;
}

scoped_ptr<WebGraphicsContext3DCommandBufferImpl>
GpuProcessTransportFactory::CreateContextCommon(
    scoped_refptr<GpuChannelHost> gpu_channel_host,
    int surface_id) {
  if (!GpuDataManagerImpl::GetInstance()->CanUseGpuBrowserCompositor())
    return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
  blink::WebGraphicsContext3D::Attributes attrs;
  attrs.shareResources = true;
  attrs.depth = false;
  attrs.stencil = false;
  attrs.antialias = false;
  attrs.noAutomaticFlushes = true;
  bool lose_context_when_out_of_memory = true;
  if (!gpu_channel_host.get()) {
    LOG(ERROR) << "Failed to establish GPU channel.";
    return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>();
  }
  GURL url("chrome://gpu/GpuProcessTransportFactory::CreateContextCommon");
  scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context(
      new WebGraphicsContext3DCommandBufferImpl(
          surface_id,
          url,
          gpu_channel_host.get(),
          attrs,
          lose_context_when_out_of_memory,
          WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
          NULL));
  return context.Pass();
}

void GpuProcessTransportFactory::OnLostMainThreadSharedContextInsideCallback() {
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::Bind(&GpuProcessTransportFactory::OnLostMainThreadSharedContext,
                 callback_factory_.GetWeakPtr()));
}

void GpuProcessTransportFactory::OnLostMainThreadSharedContext() {
  LOG(ERROR) << "Lost UI shared context.";

  // Keep old resources around while we call the observers, but ensure that
  // new resources are created if needed.
  // Kill shared contexts for both threads in tandem so they are always in
  // the same share group.
  scoped_refptr<cc::ContextProvider> lost_shared_main_thread_contexts =
      shared_main_thread_contexts_;
  shared_main_thread_contexts_  = NULL;

  scoped_ptr<GLHelper> lost_gl_helper = gl_helper_.Pass();

  FOR_EACH_OBSERVER(ImageTransportFactoryObserver,
                    observer_list_,
                    OnLostResources());

  // Kill things that use the shared context before killing the shared context.
  lost_gl_helper.reset();
  lost_shared_main_thread_contexts  = NULL;
}

}  // namespace content