gl_renderer.cc revision c5cede9ae108bb15f6b7a8aea21c7e1fefa2834c
1// Copyright 2010 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 "cc/output/gl_renderer.h"
6
7#include <algorithm>
8#include <limits>
9#include <set>
10#include <string>
11#include <vector>
12
13#include "base/debug/trace_event.h"
14#include "base/logging.h"
15#include "base/strings/string_split.h"
16#include "base/strings/string_util.h"
17#include "base/strings/stringprintf.h"
18#include "build/build_config.h"
19#include "cc/base/math_util.h"
20#include "cc/layers/video_layer_impl.h"
21#include "cc/output/compositor_frame.h"
22#include "cc/output/compositor_frame_metadata.h"
23#include "cc/output/context_provider.h"
24#include "cc/output/copy_output_request.h"
25#include "cc/output/geometry_binding.h"
26#include "cc/output/gl_frame_data.h"
27#include "cc/output/output_surface.h"
28#include "cc/output/render_surface_filters.h"
29#include "cc/quads/picture_draw_quad.h"
30#include "cc/quads/render_pass.h"
31#include "cc/quads/stream_video_draw_quad.h"
32#include "cc/quads/texture_draw_quad.h"
33#include "cc/resources/layer_quad.h"
34#include "cc/resources/raster_worker_pool.h"
35#include "cc/resources/scoped_resource.h"
36#include "cc/resources/texture_mailbox_deleter.h"
37#include "cc/trees/damage_tracker.h"
38#include "cc/trees/proxy.h"
39#include "cc/trees/single_thread_proxy.h"
40#include "gpu/GLES2/gl2extchromium.h"
41#include "gpu/command_buffer/client/context_support.h"
42#include "gpu/command_buffer/client/gles2_interface.h"
43#include "gpu/command_buffer/common/gpu_memory_allocation.h"
44#include "third_party/khronos/GLES2/gl2.h"
45#include "third_party/khronos/GLES2/gl2ext.h"
46#include "third_party/skia/include/core/SkBitmap.h"
47#include "third_party/skia/include/core/SkColor.h"
48#include "third_party/skia/include/core/SkColorFilter.h"
49#include "third_party/skia/include/core/SkSurface.h"
50#include "third_party/skia/include/gpu/GrContext.h"
51#include "third_party/skia/include/gpu/GrTexture.h"
52#include "third_party/skia/include/gpu/SkGpuDevice.h"
53#include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
54#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
55#include "ui/gfx/quad_f.h"
56#include "ui/gfx/rect_conversions.h"
57
58using gpu::gles2::GLES2Interface;
59
60namespace cc {
61
62namespace {
63
64// TODO(epenner): This should probably be moved to output surface.
65//
66// This implements a simple fence based on client side swaps.
67// This is to isolate the ResourceProvider from 'frames' which
68// it shouldn't need to care about, while still allowing us to
69// enforce good texture recycling behavior strictly throughout
70// the compositor (don't recycle a texture while it's in use).
71class SimpleSwapFence : public ResourceProvider::Fence {
72 public:
73  SimpleSwapFence() : has_passed_(false) {}
74  virtual bool HasPassed() OVERRIDE { return has_passed_; }
75  void SetHasPassed() { has_passed_ = true; }
76
77 private:
78  virtual ~SimpleSwapFence() {}
79  bool has_passed_;
80};
81
82class OnDemandRasterTaskImpl : public internal::Task {
83 public:
84  OnDemandRasterTaskImpl(PicturePileImpl* picture_pile,
85                         SkBitmap* bitmap,
86                         gfx::Rect content_rect,
87                         float contents_scale)
88      : picture_pile_(picture_pile),
89        bitmap_(bitmap),
90        content_rect_(content_rect),
91        contents_scale_(contents_scale) {
92    DCHECK(picture_pile_);
93    DCHECK(bitmap_);
94  }
95
96  // Overridden from internal::Task:
97  virtual void RunOnWorkerThread() OVERRIDE {
98    TRACE_EVENT0("cc", "OnDemandRasterTaskImpl::RunOnWorkerThread");
99    SkCanvas canvas(*bitmap_);
100
101    PicturePileImpl* picture_pile = picture_pile_->GetCloneForDrawingOnThread(
102        RasterWorkerPool::GetPictureCloneIndexForCurrentThread());
103    DCHECK(picture_pile);
104
105    picture_pile->RasterToBitmap(&canvas, content_rect_, contents_scale_, NULL);
106  }
107
108 protected:
109  virtual ~OnDemandRasterTaskImpl() {}
110
111 private:
112  PicturePileImpl* picture_pile_;
113  SkBitmap* bitmap_;
114  const gfx::Rect content_rect_;
115  const float contents_scale_;
116
117  DISALLOW_COPY_AND_ASSIGN(OnDemandRasterTaskImpl);
118};
119
120bool NeedsIOSurfaceReadbackWorkaround() {
121#if defined(OS_MACOSX)
122  // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
123  // but it doesn't seem to hurt.
124  return true;
125#else
126  return false;
127#endif
128}
129
130Float4 UVTransform(const TextureDrawQuad* quad) {
131  gfx::PointF uv0 = quad->uv_top_left;
132  gfx::PointF uv1 = quad->uv_bottom_right;
133  Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
134  if (quad->flipped) {
135    xform.data[1] = 1.0f - xform.data[1];
136    xform.data[3] = -xform.data[3];
137  }
138  return xform;
139}
140
141Float4 PremultipliedColor(SkColor color) {
142  const float factor = 1.0f / 255.0f;
143  const float alpha = SkColorGetA(color) * factor;
144
145  Float4 result = {
146      {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
147       SkColorGetB(color) * factor * alpha, alpha}};
148  return result;
149}
150
151SamplerType SamplerTypeFromTextureTarget(GLenum target) {
152  switch (target) {
153    case GL_TEXTURE_2D:
154      return SamplerType2D;
155    case GL_TEXTURE_RECTANGLE_ARB:
156      return SamplerType2DRect;
157    case GL_TEXTURE_EXTERNAL_OES:
158      return SamplerTypeExternalOES;
159    default:
160      NOTREACHED();
161      return SamplerType2D;
162  }
163}
164
165// Smallest unit that impact anti-aliasing output. We use this to
166// determine when anti-aliasing is unnecessary.
167const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
168
169}  // anonymous namespace
170
171struct GLRenderer::PendingAsyncReadPixels {
172  PendingAsyncReadPixels() : buffer(0) {}
173
174  scoped_ptr<CopyOutputRequest> copy_request;
175  base::CancelableClosure finished_read_pixels_callback;
176  unsigned buffer;
177
178 private:
179  DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
180};
181
182scoped_ptr<GLRenderer> GLRenderer::Create(
183    RendererClient* client,
184    const LayerTreeSettings* settings,
185    OutputSurface* output_surface,
186    ResourceProvider* resource_provider,
187    TextureMailboxDeleter* texture_mailbox_deleter,
188    int highp_threshold_min) {
189  return make_scoped_ptr(new GLRenderer(client,
190                                        settings,
191                                        output_surface,
192                                        resource_provider,
193                                        texture_mailbox_deleter,
194                                        highp_threshold_min));
195}
196
197GLRenderer::GLRenderer(RendererClient* client,
198                       const LayerTreeSettings* settings,
199                       OutputSurface* output_surface,
200                       ResourceProvider* resource_provider,
201                       TextureMailboxDeleter* texture_mailbox_deleter,
202                       int highp_threshold_min)
203    : DirectRenderer(client, settings, output_surface, resource_provider),
204      offscreen_framebuffer_id_(0),
205      shared_geometry_quad_(gfx::RectF(-0.5f, -0.5f, 1.0f, 1.0f)),
206      gl_(output_surface->context_provider()->ContextGL()),
207      context_support_(output_surface->context_provider()->ContextSupport()),
208      texture_mailbox_deleter_(texture_mailbox_deleter),
209      is_backbuffer_discarded_(false),
210      visible_(true),
211      is_scissor_enabled_(false),
212      scissor_rect_needs_reset_(true),
213      stencil_shadow_(false),
214      blend_shadow_(false),
215      highp_threshold_min_(highp_threshold_min),
216      highp_threshold_cache_(0),
217      on_demand_tile_raster_resource_id_(0) {
218  DCHECK(gl_);
219  DCHECK(context_support_);
220
221  ContextProvider::Capabilities context_caps =
222      output_surface_->context_provider()->ContextCapabilities();
223
224  capabilities_.using_partial_swap =
225      settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
226
227  DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
228
229  capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
230
231  capabilities_.max_texture_size = resource_provider_->max_texture_size();
232  capabilities_.best_texture_format = resource_provider_->best_texture_format();
233
234  // The updater can access textures while the GLRenderer is using them.
235  capabilities_.allow_partial_texture_updates = true;
236
237  // Check for texture fast paths. Currently we always use MO8 textures,
238  // so we only need to avoid POT textures if we have an NPOT fast-path.
239  capabilities_.avoid_pow2_textures = context_caps.gpu.fast_npot_mo8_textures;
240
241  capabilities_.using_offscreen_context3d = true;
242
243  capabilities_.using_map_image =
244      settings_->use_map_image && context_caps.gpu.map_image;
245
246  capabilities_.using_discard_framebuffer =
247      context_caps.gpu.discard_framebuffer;
248
249  capabilities_.allow_rasterize_on_demand = true;
250
251  InitializeSharedObjects();
252}
253
254GLRenderer::~GLRenderer() {
255  while (!pending_async_read_pixels_.empty()) {
256    PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
257    pending_read->finished_read_pixels_callback.Cancel();
258    pending_async_read_pixels_.pop_back();
259  }
260
261  in_use_overlay_resources_.clear();
262
263  CleanupSharedObjects();
264}
265
266const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
267  return capabilities_;
268}
269
270void GLRenderer::DebugGLCall(GLES2Interface* gl,
271                             const char* command,
272                             const char* file,
273                             int line) {
274  GLuint error = gl->GetError();
275  if (error != GL_NO_ERROR)
276    LOG(ERROR) << "GL command failed: File: " << file << "\n\tLine " << line
277               << "\n\tcommand: " << command << ", error "
278               << static_cast<int>(error) << "\n";
279}
280
281void GLRenderer::SetVisible(bool visible) {
282  if (visible_ == visible)
283    return;
284  visible_ = visible;
285
286  EnforceMemoryPolicy();
287
288  context_support_->SetSurfaceVisible(visible);
289}
290
291void GLRenderer::SendManagedMemoryStats(size_t bytes_visible,
292                                        size_t bytes_visible_and_nearby,
293                                        size_t bytes_allocated) {
294  gpu::ManagedMemoryStats stats;
295  stats.bytes_required = bytes_visible;
296  stats.bytes_nice_to_have = bytes_visible_and_nearby;
297  stats.bytes_allocated = bytes_allocated;
298  stats.backbuffer_requested = !is_backbuffer_discarded_;
299  context_support_->SendManagedMemoryStats(stats);
300}
301
302void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
303
304void GLRenderer::DiscardPixels(bool has_external_stencil_test,
305                               bool draw_rect_covers_full_surface) {
306  if (has_external_stencil_test || !draw_rect_covers_full_surface ||
307      !capabilities_.using_discard_framebuffer)
308    return;
309  bool using_default_framebuffer =
310      !current_framebuffer_lock_ &&
311      output_surface_->capabilities().uses_default_gl_framebuffer;
312  GLenum attachments[] = {static_cast<GLenum>(
313      using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
314  gl_->DiscardFramebufferEXT(
315      GL_FRAMEBUFFER, arraysize(attachments), attachments);
316}
317
318void GLRenderer::ClearFramebuffer(DrawingFrame* frame,
319                                  bool has_external_stencil_test) {
320  // It's unsafe to clear when we have a stencil test because glClear ignores
321  // stencil.
322  if (has_external_stencil_test) {
323    DCHECK(!frame->current_render_pass->has_transparent_background);
324    return;
325  }
326
327  // On DEBUG builds, opaque render passes are cleared to blue to easily see
328  // regions that were not drawn on the screen.
329  if (frame->current_render_pass->has_transparent_background)
330    GLC(gl_, gl_->ClearColor(0, 0, 0, 0));
331  else
332    GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
333
334  bool always_clear = false;
335#ifndef NDEBUG
336  always_clear = true;
337#endif
338  if (always_clear || frame->current_render_pass->has_transparent_background) {
339    GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
340    if (always_clear)
341      clear_bits |= GL_STENCIL_BUFFER_BIT;
342    gl_->Clear(clear_bits);
343  }
344}
345
346void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
347  if (frame->device_viewport_rect.IsEmpty())
348    return;
349
350  TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
351
352  // TODO(enne): Do we need to reinitialize all of this state per frame?
353  ReinitializeGLState();
354}
355
356void GLRenderer::DoNoOp() {
357  GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
358  GLC(gl_, gl_->Flush());
359}
360
361void GLRenderer::DoDrawQuad(DrawingFrame* frame, const DrawQuad* quad) {
362  DCHECK(quad->rect.Contains(quad->visible_rect));
363  if (quad->material != DrawQuad::TEXTURE_CONTENT) {
364    FlushTextureQuadCache();
365  }
366
367  switch (quad->material) {
368    case DrawQuad::INVALID:
369      NOTREACHED();
370      break;
371    case DrawQuad::CHECKERBOARD:
372      DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad));
373      break;
374    case DrawQuad::DEBUG_BORDER:
375      DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
376      break;
377    case DrawQuad::IO_SURFACE_CONTENT:
378      DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad));
379      break;
380    case DrawQuad::PICTURE_CONTENT:
381      DrawPictureQuad(frame, PictureDrawQuad::MaterialCast(quad));
382      break;
383    case DrawQuad::RENDER_PASS:
384      DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad));
385      break;
386    case DrawQuad::SOLID_COLOR:
387      DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad));
388      break;
389    case DrawQuad::STREAM_VIDEO_CONTENT:
390      DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad));
391      break;
392    case DrawQuad::SURFACE_CONTENT:
393      // Surface content should be fully resolved to other quad types before
394      // reaching a direct renderer.
395      NOTREACHED();
396      break;
397    case DrawQuad::TEXTURE_CONTENT:
398      EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad));
399      break;
400    case DrawQuad::TILED_CONTENT:
401      DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad));
402      break;
403    case DrawQuad::YUV_VIDEO_CONTENT:
404      DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad));
405      break;
406  }
407}
408
409void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
410                                      const CheckerboardDrawQuad* quad) {
411  SetBlendEnabled(quad->ShouldDrawWithBlending());
412
413  const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
414  DCHECK(program && (program->initialized() || IsContextLost()));
415  SetUseProgram(program->program());
416
417  SkColor color = quad->color;
418  GLC(gl_,
419      gl_->Uniform4f(program->fragment_shader().color_location(),
420                     SkColorGetR(color) * (1.0f / 255.0f),
421                     SkColorGetG(color) * (1.0f / 255.0f),
422                     SkColorGetB(color) * (1.0f / 255.0f),
423                     1));
424
425  const int checkerboard_width = 16;
426  float frequency = 1.0f / checkerboard_width;
427
428  gfx::Rect tile_rect = quad->rect;
429  float tex_offset_x = tile_rect.x() % checkerboard_width;
430  float tex_offset_y = tile_rect.y() % checkerboard_width;
431  float tex_scale_x = tile_rect.width();
432  float tex_scale_y = tile_rect.height();
433  GLC(gl_,
434      gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
435                     tex_offset_x,
436                     tex_offset_y,
437                     tex_scale_x,
438                     tex_scale_y));
439
440  GLC(gl_,
441      gl_->Uniform1f(program->fragment_shader().frequency_location(),
442                     frequency));
443
444  SetShaderOpacity(quad->opacity(),
445                   program->fragment_shader().alpha_location());
446  DrawQuadGeometry(frame,
447                   quad->quadTransform(),
448                   quad->rect,
449                   program->vertex_shader().matrix_location());
450}
451
452void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
453                                     const DebugBorderDrawQuad* quad) {
454  SetBlendEnabled(quad->ShouldDrawWithBlending());
455
456  static float gl_matrix[16];
457  const DebugBorderProgram* program = GetDebugBorderProgram();
458  DCHECK(program && (program->initialized() || IsContextLost()));
459  SetUseProgram(program->program());
460
461  // Use the full quad_rect for debug quads to not move the edges based on
462  // partial swaps.
463  gfx::Rect layer_rect = quad->rect;
464  gfx::Transform render_matrix = quad->quadTransform();
465  render_matrix.Translate(0.5f * layer_rect.width() + layer_rect.x(),
466                          0.5f * layer_rect.height() + layer_rect.y());
467  render_matrix.Scale(layer_rect.width(), layer_rect.height());
468  GLRenderer::ToGLMatrix(&gl_matrix[0],
469                         frame->projection_matrix * render_matrix);
470  GLC(gl_,
471      gl_->UniformMatrix4fv(
472          program->vertex_shader().matrix_location(), 1, false, &gl_matrix[0]));
473
474  SkColor color = quad->color;
475  float alpha = SkColorGetA(color) * (1.0f / 255.0f);
476
477  GLC(gl_,
478      gl_->Uniform4f(program->fragment_shader().color_location(),
479                     (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
480                     (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
481                     (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
482                     alpha));
483
484  GLC(gl_, gl_->LineWidth(quad->width));
485
486  // The indices for the line are stored in the same array as the triangle
487  // indices.
488  GLC(gl_, gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0));
489}
490
491static SkBitmap ApplyImageFilter(GLRenderer* renderer,
492                                 ContextProvider* offscreen_contexts,
493                                 const gfx::Point& origin,
494                                 SkImageFilter* filter,
495                                 ScopedResource* source_texture_resource) {
496  if (!filter)
497    return SkBitmap();
498
499  if (!offscreen_contexts || !offscreen_contexts->GrContext())
500    return SkBitmap();
501
502  ResourceProvider::ScopedReadLockGL lock(renderer->resource_provider(),
503                                          source_texture_resource->id());
504
505  // Flush the compositor context to ensure that textures there are available
506  // in the shared context.  Do this after locking/creating the compositor
507  // texture.
508  renderer->resource_provider()->Flush();
509
510  // Wrap the source texture in a Ganesh platform texture.
511  GrBackendTextureDesc backend_texture_description;
512  backend_texture_description.fWidth = source_texture_resource->size().width();
513  backend_texture_description.fHeight =
514      source_texture_resource->size().height();
515  backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
516  backend_texture_description.fTextureHandle = lock.texture_id();
517  backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
518  skia::RefPtr<GrTexture> texture =
519      skia::AdoptRef(offscreen_contexts->GrContext()->wrapBackendTexture(
520          backend_texture_description));
521
522  SkImageInfo info = {
523    source_texture_resource->size().width(),
524    source_texture_resource->size().height(),
525    kPMColor_SkColorType,
526    kPremul_SkAlphaType
527  };
528  // Place the platform texture inside an SkBitmap.
529  SkBitmap source;
530  source.setConfig(info);
531  skia::RefPtr<SkGrPixelRef> pixel_ref =
532      skia::AdoptRef(new SkGrPixelRef(info, texture.get()));
533  source.setPixelRef(pixel_ref.get());
534
535  // Create a scratch texture for backing store.
536  GrTextureDesc desc;
537  desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
538  desc.fSampleCnt = 0;
539  desc.fWidth = source.width();
540  desc.fHeight = source.height();
541  desc.fConfig = kSkia8888_GrPixelConfig;
542  desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
543  GrAutoScratchTexture scratch_texture(
544      offscreen_contexts->GrContext(), desc, GrContext::kExact_ScratchTexMatch);
545  skia::RefPtr<GrTexture> backing_store =
546      skia::AdoptRef(scratch_texture.detach());
547
548  // Create a device and canvas using that backing store.
549  SkGpuDevice device(offscreen_contexts->GrContext(), backing_store.get());
550  SkCanvas canvas(&device);
551
552  // Draw the source bitmap through the filter to the canvas.
553  SkPaint paint;
554  paint.setImageFilter(filter);
555  canvas.clear(SK_ColorTRANSPARENT);
556
557  // TODO(senorblanco): in addition to the origin translation here, the canvas
558  // should also be scaled to accomodate device pixel ratio and pinch zoom. See
559  // crbug.com/281516 and crbug.com/281518.
560  canvas.translate(SkIntToScalar(-origin.x()), SkIntToScalar(-origin.y()));
561  canvas.drawSprite(source, 0, 0, &paint);
562
563  // Flush skia context so that all the rendered stuff appears on the
564  // texture.
565  offscreen_contexts->GrContext()->flush();
566
567  // Flush the GL context so rendering results from this context are
568  // visible in the compositor's context.
569  offscreen_contexts->ContextGL()->Flush();
570
571  return device.accessBitmap(false);
572}
573
574static SkBitmap ApplyBlendModeWithBackdrop(
575    GLRenderer* renderer,
576    ContextProvider* offscreen_contexts,
577    SkBitmap source_bitmap_with_filters,
578    ScopedResource* source_texture_resource,
579    ScopedResource* background_texture_resource,
580    SkXfermode::Mode blend_mode) {
581  if (!offscreen_contexts || !offscreen_contexts->GrContext())
582    return source_bitmap_with_filters;
583
584  DCHECK(background_texture_resource);
585  DCHECK(source_texture_resource);
586
587  gfx::Size source_size = source_texture_resource->size();
588  gfx::Size background_size = background_texture_resource->size();
589
590  DCHECK_LE(background_size.width(), source_size.width());
591  DCHECK_LE(background_size.height(), source_size.height());
592
593  int source_texture_with_filters_id;
594  scoped_ptr<ResourceProvider::ScopedReadLockGL> lock;
595  if (source_bitmap_with_filters.getTexture()) {
596    DCHECK_EQ(source_size.width(), source_bitmap_with_filters.width());
597    DCHECK_EQ(source_size.height(), source_bitmap_with_filters.height());
598    GrTexture* texture =
599        reinterpret_cast<GrTexture*>(source_bitmap_with_filters.getTexture());
600    source_texture_with_filters_id = texture->getTextureHandle();
601  } else {
602    lock.reset(new ResourceProvider::ScopedReadLockGL(
603        renderer->resource_provider(), source_texture_resource->id()));
604    source_texture_with_filters_id = lock->texture_id();
605  }
606
607  ResourceProvider::ScopedReadLockGL lock_background(
608      renderer->resource_provider(), background_texture_resource->id());
609
610  // Flush the compositor context to ensure that textures there are available
611  // in the shared context.  Do this after locking/creating the compositor
612  // texture.
613  renderer->resource_provider()->Flush();
614
615  // Wrap the source texture in a Ganesh platform texture.
616  GrBackendTextureDesc backend_texture_description;
617  backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
618  backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
619
620  backend_texture_description.fWidth = source_size.width();
621  backend_texture_description.fHeight = source_size.height();
622  backend_texture_description.fTextureHandle = source_texture_with_filters_id;
623  skia::RefPtr<GrTexture> source_texture =
624      skia::AdoptRef(offscreen_contexts->GrContext()->wrapBackendTexture(
625          backend_texture_description));
626
627  backend_texture_description.fWidth = background_size.width();
628  backend_texture_description.fHeight = background_size.height();
629  backend_texture_description.fTextureHandle = lock_background.texture_id();
630  skia::RefPtr<GrTexture> background_texture =
631      skia::AdoptRef(offscreen_contexts->GrContext()->wrapBackendTexture(
632          backend_texture_description));
633
634  SkImageInfo source_info = {
635    source_size.width(),
636    source_size.height(),
637    kPMColor_SkColorType,
638    kPremul_SkAlphaType
639  };
640  // Place the platform texture inside an SkBitmap.
641  SkBitmap source;
642  source.setConfig(source_info);
643  skia::RefPtr<SkGrPixelRef> source_pixel_ref =
644      skia::AdoptRef(new SkGrPixelRef(source_info, source_texture.get()));
645  source.setPixelRef(source_pixel_ref.get());
646
647  SkImageInfo background_info = {
648    background_size.width(),
649    background_size.height(),
650    kPMColor_SkColorType,
651    kPremul_SkAlphaType
652  };
653
654  SkBitmap background;
655  background.setConfig(background_info);
656  skia::RefPtr<SkGrPixelRef> background_pixel_ref =
657      skia::AdoptRef(new SkGrPixelRef(
658          background_info, background_texture.get()));
659  background.setPixelRef(background_pixel_ref.get());
660
661  // Create a scratch texture for backing store.
662  GrTextureDesc desc;
663  desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
664  desc.fSampleCnt = 0;
665  desc.fWidth = source.width();
666  desc.fHeight = source.height();
667  desc.fConfig = kSkia8888_GrPixelConfig;
668  desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
669  GrAutoScratchTexture scratch_texture(
670      offscreen_contexts->GrContext(), desc, GrContext::kExact_ScratchTexMatch);
671  skia::RefPtr<GrTexture> backing_store =
672      skia::AdoptRef(scratch_texture.detach());
673
674  // Create a device and canvas using that backing store.
675  SkGpuDevice device(offscreen_contexts->GrContext(), backing_store.get());
676  SkCanvas canvas(&device);
677
678  // Draw the source bitmap through the filter to the canvas.
679  canvas.clear(SK_ColorTRANSPARENT);
680  canvas.drawSprite(background, 0, 0);
681  SkPaint paint;
682  paint.setXfermodeMode(blend_mode);
683  canvas.drawSprite(source, 0, 0, &paint);
684
685  // Flush skia context so that all the rendered stuff appears on the
686  // texture.
687  offscreen_contexts->GrContext()->flush();
688
689  // Flush the GL context so rendering results from this context are
690  // visible in the compositor's context.
691  offscreen_contexts->ContextGL()->Flush();
692
693  return device.accessBitmap(false);
694}
695
696scoped_ptr<ScopedResource> GLRenderer::GetBackgroundWithFilters(
697    DrawingFrame* frame,
698    const RenderPassDrawQuad* quad,
699    const gfx::Transform& contents_device_transform,
700    const gfx::Transform& contents_device_transform_inverse,
701    bool* background_changed) {
702  // This method draws a background filter, which applies a filter to any pixels
703  // behind the quad and seen through its background.  The algorithm works as
704  // follows:
705  // 1. Compute a bounding box around the pixels that will be visible through
706  // the quad.
707  // 2. Read the pixels in the bounding box into a buffer R.
708  // 3. Apply the background filter to R, so that it is applied in the pixels'
709  // coordinate space.
710  // 4. Apply the quad's inverse transform to map the pixels in R into the
711  // quad's content space. This implicitly clips R by the content bounds of the
712  // quad since the destination texture has bounds matching the quad's content.
713  // 5. Draw the background texture for the contents using the same transform as
714  // used to draw the contents itself. This is done without blending to replace
715  // the current background pixels with the new filtered background.
716  // 6. Draw the contents of the quad over drop of the new background with
717  // blending, as per usual. The filtered background pixels will show through
718  // any non-opaque pixels in this draws.
719  //
720  // Pixel copies in this algorithm occur at steps 2, 3, 4, and 5.
721
722  // TODO(danakj): When this algorithm changes, update
723  // LayerTreeHost::PrioritizeTextures() accordingly.
724
725  // TODO(danakj): We only allow background filters on an opaque render surface
726  // because other surfaces may contain translucent pixels, and the contents
727  // behind those translucent pixels wouldn't have the filter applied.
728  bool apply_background_filters =
729      !frame->current_render_pass->has_transparent_background;
730  DCHECK(!frame->current_texture);
731
732  // TODO(ajuma): Add support for reference filters once
733  // FilterOperations::GetOutsets supports reference filters.
734  if (apply_background_filters && quad->background_filters.HasReferenceFilter())
735    apply_background_filters = false;
736
737  // TODO(danakj): Do a single readback for both the surface and replica and
738  // cache the filtered results (once filter textures are not reused).
739  gfx::Rect window_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
740      contents_device_transform, SharedGeometryQuad().BoundingBox()));
741
742  int top, right, bottom, left;
743  quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
744  window_rect.Inset(-left, -top, -right, -bottom);
745
746  window_rect.Intersect(
747      MoveFromDrawToWindowSpace(frame->current_render_pass->output_rect));
748
749  scoped_ptr<ScopedResource> device_background_texture =
750      ScopedResource::Create(resource_provider_);
751  // The TextureUsageFramebuffer hint makes ResourceProvider avoid immutable
752  // storage allocation (texStorage2DEXT) for this texture. copyTexImage2D fails
753  // when called on a texture having immutable storage.
754  device_background_texture->Allocate(
755      window_rect.size(), ResourceProvider::TextureUsageFramebuffer, RGBA_8888);
756  {
757    ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
758                                             device_background_texture->id());
759    GetFramebufferTexture(
760        lock.texture_id(), device_background_texture->format(), window_rect);
761  }
762
763  skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
764      quad->background_filters, device_background_texture->size());
765
766  SkBitmap filtered_device_background;
767  if (apply_background_filters) {
768    filtered_device_background =
769        ApplyImageFilter(this,
770                         frame->offscreen_context_provider,
771                         quad->rect.origin(),
772                         filter.get(),
773                         device_background_texture.get());
774  }
775  *background_changed = (filtered_device_background.getTexture() != NULL);
776
777  int filtered_device_background_texture_id = 0;
778  scoped_ptr<ResourceProvider::ScopedReadLockGL> lock;
779  if (filtered_device_background.getTexture()) {
780    GrTexture* texture =
781        reinterpret_cast<GrTexture*>(filtered_device_background.getTexture());
782    filtered_device_background_texture_id = texture->getTextureHandle();
783  } else {
784    lock.reset(new ResourceProvider::ScopedReadLockGL(
785        resource_provider_, device_background_texture->id()));
786    filtered_device_background_texture_id = lock->texture_id();
787  }
788
789  scoped_ptr<ScopedResource> background_texture =
790      ScopedResource::Create(resource_provider_);
791  background_texture->Allocate(
792      quad->rect.size(), ResourceProvider::TextureUsageFramebuffer, RGBA_8888);
793
794  const RenderPass* target_render_pass = frame->current_render_pass;
795  bool using_background_texture =
796      UseScopedTexture(frame, background_texture.get(), quad->rect);
797
798  if (using_background_texture) {
799    // Copy the readback pixels from device to the background texture for the
800    // surface.
801    gfx::Transform device_to_framebuffer_transform;
802    device_to_framebuffer_transform.Translate(
803        quad->rect.width() * 0.5f + quad->rect.x(),
804        quad->rect.height() * 0.5f + quad->rect.y());
805    device_to_framebuffer_transform.Scale(quad->rect.width(),
806                                          quad->rect.height());
807    device_to_framebuffer_transform.PreconcatTransform(
808        contents_device_transform_inverse);
809
810#ifndef NDEBUG
811    GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
812    gl_->Clear(GL_COLOR_BUFFER_BIT);
813#endif
814
815    // The filtered_deveice_background_texture is oriented the same as the frame
816    // buffer. The transform we are copying with has a vertical flip, as well as
817    // the |device_to_framebuffer_transform|, which cancel each other out. So do
818    // not flip the contents in the shader to maintain orientation.
819    bool flip_vertically = false;
820
821    CopyTextureToFramebuffer(frame,
822                             filtered_device_background_texture_id,
823                             window_rect,
824                             device_to_framebuffer_transform,
825                             flip_vertically);
826  }
827
828  UseRenderPass(frame, target_render_pass);
829
830  if (!using_background_texture)
831    return scoped_ptr<ScopedResource>();
832  return background_texture.Pass();
833}
834
835void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
836                                    const RenderPassDrawQuad* quad) {
837  SetBlendEnabled(quad->ShouldDrawWithBlending());
838
839  ScopedResource* contents_texture =
840      render_pass_textures_.get(quad->render_pass_id);
841  if (!contents_texture || !contents_texture->id())
842    return;
843
844  gfx::Transform quad_rect_matrix;
845  QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
846  gfx::Transform contents_device_transform =
847      frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
848  contents_device_transform.FlattenTo2d();
849
850  // Can only draw surface if device matrix is invertible.
851  gfx::Transform contents_device_transform_inverse(
852      gfx::Transform::kSkipInitialization);
853  if (!contents_device_transform.GetInverse(&contents_device_transform_inverse))
854    return;
855
856  bool need_background_texture =
857      quad->shared_quad_state->blend_mode != SkXfermode::kSrcOver_Mode ||
858      !quad->background_filters.IsEmpty();
859  bool background_changed = false;
860  scoped_ptr<ScopedResource> background_texture;
861  if (need_background_texture) {
862    // The pixels from the filtered background should completely replace the
863    // current pixel values.
864    bool disable_blending = blend_enabled();
865    if (disable_blending)
866      SetBlendEnabled(false);
867
868    background_texture =
869        GetBackgroundWithFilters(frame,
870                                 quad,
871                                 contents_device_transform,
872                                 contents_device_transform_inverse,
873                                 &background_changed);
874
875    if (disable_blending)
876      SetBlendEnabled(true);
877  }
878
879  // TODO(senorblanco): Cache this value so that we don't have to do it for both
880  // the surface and its replica.  Apply filters to the contents texture.
881  SkBitmap filter_bitmap;
882  SkScalar color_matrix[20];
883  bool use_color_matrix = false;
884  // TODO(ajuma): Always use RenderSurfaceFilters::BuildImageFilter, not just
885  // when we have a reference filter.
886  if (!quad->filters.IsEmpty()) {
887    skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
888        quad->filters, contents_texture->size());
889    if (filter) {
890      skia::RefPtr<SkColorFilter> cf;
891
892      {
893        SkColorFilter* colorfilter_rawptr = NULL;
894        filter->asColorFilter(&colorfilter_rawptr);
895        cf = skia::AdoptRef(colorfilter_rawptr);
896      }
897
898      if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
899        // We have a single color matrix as a filter; apply it locally
900        // in the compositor.
901        use_color_matrix = true;
902      } else {
903        filter_bitmap = ApplyImageFilter(this,
904                                         frame->offscreen_context_provider,
905                                         quad->rect.origin(),
906                                         filter.get(),
907                                         contents_texture);
908      }
909    }
910  }
911
912  if (quad->shared_quad_state->blend_mode != SkXfermode::kSrcOver_Mode &&
913      background_texture) {
914    filter_bitmap =
915        ApplyBlendModeWithBackdrop(this,
916                                   frame->offscreen_context_provider,
917                                   filter_bitmap,
918                                   contents_texture,
919                                   background_texture.get(),
920                                   quad->shared_quad_state->blend_mode);
921  }
922
923  // Draw the background texture if it has some filters applied.
924  if (background_texture && background_changed) {
925    DCHECK(background_texture->size() == quad->rect.size());
926    ResourceProvider::ScopedReadLockGL lock(resource_provider_,
927                                            background_texture->id());
928
929    // The background_texture is oriented the same as the frame buffer. The
930    // transform we are copying with has a vertical flip, so flip the contents
931    // in the shader to maintain orientation
932    bool flip_vertically = true;
933
934    CopyTextureToFramebuffer(frame,
935                             lock.texture_id(),
936                             quad->rect,
937                             quad->quadTransform(),
938                             flip_vertically);
939  }
940
941  bool clipped = false;
942  gfx::QuadF device_quad = MathUtil::MapQuad(
943      contents_device_transform, SharedGeometryQuad(), &clipped);
944  LayerQuad device_layer_bounds(gfx::QuadF(device_quad.BoundingBox()));
945  LayerQuad device_layer_edges(device_quad);
946
947  // Use anti-aliasing programs only when necessary.
948  bool use_aa =
949      !clipped && (!device_quad.IsRectilinear() ||
950                   !gfx::IsNearestRectWithinDistance(device_quad.BoundingBox(),
951                                                     kAntiAliasingEpsilon));
952  if (use_aa) {
953    device_layer_bounds.InflateAntiAliasingDistance();
954    device_layer_edges.InflateAntiAliasingDistance();
955  }
956
957  scoped_ptr<ResourceProvider::ScopedReadLockGL> mask_resource_lock;
958  unsigned mask_texture_id = 0;
959  if (quad->mask_resource_id) {
960    mask_resource_lock.reset(new ResourceProvider::ScopedReadLockGL(
961        resource_provider_, quad->mask_resource_id));
962    mask_texture_id = mask_resource_lock->texture_id();
963  }
964
965  // TODO(danakj): use the background_texture and blend the background in with
966  // this draw instead of having a separate copy of the background texture.
967
968  scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
969  if (filter_bitmap.getTexture()) {
970    GrTexture* texture =
971        reinterpret_cast<GrTexture*>(filter_bitmap.getTexture());
972    DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
973    gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
974  } else {
975    contents_resource_lock =
976        make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
977            resource_provider_, contents_texture->id(), GL_LINEAR));
978    DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
979              contents_resource_lock->target());
980  }
981
982  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
983      gl_,
984      &highp_threshold_cache_,
985      highp_threshold_min_,
986      quad->shared_quad_state->visible_content_rect.bottom_right());
987
988  int shader_quad_location = -1;
989  int shader_edge_location = -1;
990  int shader_viewport_location = -1;
991  int shader_mask_sampler_location = -1;
992  int shader_mask_tex_coord_scale_location = -1;
993  int shader_mask_tex_coord_offset_location = -1;
994  int shader_matrix_location = -1;
995  int shader_alpha_location = -1;
996  int shader_color_matrix_location = -1;
997  int shader_color_offset_location = -1;
998  int shader_tex_transform_location = -1;
999
1000  if (use_aa && mask_texture_id && !use_color_matrix) {
1001    const RenderPassMaskProgramAA* program =
1002        GetRenderPassMaskProgramAA(tex_coord_precision);
1003    SetUseProgram(program->program());
1004    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1005
1006    shader_quad_location = program->vertex_shader().quad_location();
1007    shader_edge_location = program->vertex_shader().edge_location();
1008    shader_viewport_location = program->vertex_shader().viewport_location();
1009    shader_mask_sampler_location =
1010        program->fragment_shader().mask_sampler_location();
1011    shader_mask_tex_coord_scale_location =
1012        program->fragment_shader().mask_tex_coord_scale_location();
1013    shader_mask_tex_coord_offset_location =
1014        program->fragment_shader().mask_tex_coord_offset_location();
1015    shader_matrix_location = program->vertex_shader().matrix_location();
1016    shader_alpha_location = program->fragment_shader().alpha_location();
1017    shader_tex_transform_location =
1018        program->vertex_shader().tex_transform_location();
1019  } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1020    const RenderPassMaskProgram* program =
1021        GetRenderPassMaskProgram(tex_coord_precision);
1022    SetUseProgram(program->program());
1023    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1024
1025    shader_mask_sampler_location =
1026        program->fragment_shader().mask_sampler_location();
1027    shader_mask_tex_coord_scale_location =
1028        program->fragment_shader().mask_tex_coord_scale_location();
1029    shader_mask_tex_coord_offset_location =
1030        program->fragment_shader().mask_tex_coord_offset_location();
1031    shader_matrix_location = program->vertex_shader().matrix_location();
1032    shader_alpha_location = program->fragment_shader().alpha_location();
1033    shader_tex_transform_location =
1034        program->vertex_shader().tex_transform_location();
1035  } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1036    const RenderPassProgramAA* program =
1037        GetRenderPassProgramAA(tex_coord_precision);
1038    SetUseProgram(program->program());
1039    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1040
1041    shader_quad_location = program->vertex_shader().quad_location();
1042    shader_edge_location = program->vertex_shader().edge_location();
1043    shader_viewport_location = program->vertex_shader().viewport_location();
1044    shader_matrix_location = program->vertex_shader().matrix_location();
1045    shader_alpha_location = program->fragment_shader().alpha_location();
1046    shader_tex_transform_location =
1047        program->vertex_shader().tex_transform_location();
1048  } else if (use_aa && mask_texture_id && use_color_matrix) {
1049    const RenderPassMaskColorMatrixProgramAA* program =
1050        GetRenderPassMaskColorMatrixProgramAA(tex_coord_precision);
1051    SetUseProgram(program->program());
1052    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1053
1054    shader_matrix_location = program->vertex_shader().matrix_location();
1055    shader_quad_location = program->vertex_shader().quad_location();
1056    shader_tex_transform_location =
1057        program->vertex_shader().tex_transform_location();
1058    shader_edge_location = program->vertex_shader().edge_location();
1059    shader_viewport_location = program->vertex_shader().viewport_location();
1060    shader_alpha_location = program->fragment_shader().alpha_location();
1061    shader_mask_sampler_location =
1062        program->fragment_shader().mask_sampler_location();
1063    shader_mask_tex_coord_scale_location =
1064        program->fragment_shader().mask_tex_coord_scale_location();
1065    shader_mask_tex_coord_offset_location =
1066        program->fragment_shader().mask_tex_coord_offset_location();
1067    shader_color_matrix_location =
1068        program->fragment_shader().color_matrix_location();
1069    shader_color_offset_location =
1070        program->fragment_shader().color_offset_location();
1071  } else if (use_aa && !mask_texture_id && use_color_matrix) {
1072    const RenderPassColorMatrixProgramAA* program =
1073        GetRenderPassColorMatrixProgramAA(tex_coord_precision);
1074    SetUseProgram(program->program());
1075    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1076
1077    shader_matrix_location = program->vertex_shader().matrix_location();
1078    shader_quad_location = program->vertex_shader().quad_location();
1079    shader_tex_transform_location =
1080        program->vertex_shader().tex_transform_location();
1081    shader_edge_location = program->vertex_shader().edge_location();
1082    shader_viewport_location = program->vertex_shader().viewport_location();
1083    shader_alpha_location = program->fragment_shader().alpha_location();
1084    shader_color_matrix_location =
1085        program->fragment_shader().color_matrix_location();
1086    shader_color_offset_location =
1087        program->fragment_shader().color_offset_location();
1088  } else if (!use_aa && mask_texture_id && use_color_matrix) {
1089    const RenderPassMaskColorMatrixProgram* program =
1090        GetRenderPassMaskColorMatrixProgram(tex_coord_precision);
1091    SetUseProgram(program->program());
1092    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1093
1094    shader_matrix_location = program->vertex_shader().matrix_location();
1095    shader_tex_transform_location =
1096        program->vertex_shader().tex_transform_location();
1097    shader_mask_sampler_location =
1098        program->fragment_shader().mask_sampler_location();
1099    shader_mask_tex_coord_scale_location =
1100        program->fragment_shader().mask_tex_coord_scale_location();
1101    shader_mask_tex_coord_offset_location =
1102        program->fragment_shader().mask_tex_coord_offset_location();
1103    shader_alpha_location = program->fragment_shader().alpha_location();
1104    shader_color_matrix_location =
1105        program->fragment_shader().color_matrix_location();
1106    shader_color_offset_location =
1107        program->fragment_shader().color_offset_location();
1108  } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1109    const RenderPassColorMatrixProgram* program =
1110        GetRenderPassColorMatrixProgram(tex_coord_precision);
1111    SetUseProgram(program->program());
1112    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1113
1114    shader_matrix_location = program->vertex_shader().matrix_location();
1115    shader_tex_transform_location =
1116        program->vertex_shader().tex_transform_location();
1117    shader_alpha_location = program->fragment_shader().alpha_location();
1118    shader_color_matrix_location =
1119        program->fragment_shader().color_matrix_location();
1120    shader_color_offset_location =
1121        program->fragment_shader().color_offset_location();
1122  } else {
1123    const RenderPassProgram* program =
1124        GetRenderPassProgram(tex_coord_precision);
1125    SetUseProgram(program->program());
1126    GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1127
1128    shader_matrix_location = program->vertex_shader().matrix_location();
1129    shader_alpha_location = program->fragment_shader().alpha_location();
1130    shader_tex_transform_location =
1131        program->vertex_shader().tex_transform_location();
1132  }
1133  float tex_scale_x =
1134      quad->rect.width() / static_cast<float>(contents_texture->size().width());
1135  float tex_scale_y = quad->rect.height() /
1136                      static_cast<float>(contents_texture->size().height());
1137  DCHECK_LE(tex_scale_x, 1.0f);
1138  DCHECK_LE(tex_scale_y, 1.0f);
1139
1140  DCHECK(shader_tex_transform_location != -1 || IsContextLost());
1141  // Flip the content vertically in the shader, as the RenderPass input
1142  // texture is already oriented the same way as the framebuffer, but the
1143  // projection transform does a flip.
1144  GLC(gl_,
1145      gl_->Uniform4f(shader_tex_transform_location,
1146                     0.0f,
1147                     tex_scale_y,
1148                     tex_scale_x,
1149                     -tex_scale_y));
1150
1151  scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_mask_sampler_lock;
1152  if (shader_mask_sampler_location != -1) {
1153    DCHECK_NE(shader_mask_tex_coord_scale_location, 1);
1154    DCHECK_NE(shader_mask_tex_coord_offset_location, 1);
1155    GLC(gl_, gl_->Uniform1i(shader_mask_sampler_location, 1));
1156
1157    float mask_tex_scale_x = quad->mask_uv_rect.width() / tex_scale_x;
1158    float mask_tex_scale_y = quad->mask_uv_rect.height() / tex_scale_y;
1159
1160    // Mask textures are oriented vertically flipped relative to the framebuffer
1161    // and the RenderPass contents texture, so we flip the tex coords from the
1162    // RenderPass texture to find the mask texture coords.
1163    GLC(gl_,
1164        gl_->Uniform2f(shader_mask_tex_coord_offset_location,
1165                       quad->mask_uv_rect.x(),
1166                       quad->mask_uv_rect.y() + quad->mask_uv_rect.height()));
1167    GLC(gl_,
1168        gl_->Uniform2f(shader_mask_tex_coord_scale_location,
1169                       mask_tex_scale_x,
1170                       -mask_tex_scale_y));
1171    shader_mask_sampler_lock = make_scoped_ptr(
1172        new ResourceProvider::ScopedSamplerGL(resource_provider_,
1173                                              quad->mask_resource_id,
1174                                              GL_TEXTURE1,
1175                                              GL_LINEAR));
1176    DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1177              shader_mask_sampler_lock->target());
1178  }
1179
1180  if (shader_edge_location != -1) {
1181    float edge[24];
1182    device_layer_edges.ToFloatArray(edge);
1183    device_layer_bounds.ToFloatArray(&edge[12]);
1184    GLC(gl_, gl_->Uniform3fv(shader_edge_location, 8, edge));
1185  }
1186
1187  if (shader_viewport_location != -1) {
1188    float viewport[4] = {static_cast<float>(viewport_.x()),
1189                         static_cast<float>(viewport_.y()),
1190                         static_cast<float>(viewport_.width()),
1191                         static_cast<float>(viewport_.height()), };
1192    GLC(gl_, gl_->Uniform4fv(shader_viewport_location, 1, viewport));
1193  }
1194
1195  if (shader_color_matrix_location != -1) {
1196    float matrix[16];
1197    for (int i = 0; i < 4; ++i) {
1198      for (int j = 0; j < 4; ++j)
1199        matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1200    }
1201    GLC(gl_,
1202        gl_->UniformMatrix4fv(shader_color_matrix_location, 1, false, matrix));
1203  }
1204  static const float kScale = 1.0f / 255.0f;
1205  if (shader_color_offset_location != -1) {
1206    float offset[4];
1207    for (int i = 0; i < 4; ++i)
1208      offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1209
1210    GLC(gl_, gl_->Uniform4fv(shader_color_offset_location, 1, offset));
1211  }
1212
1213  // Map device space quad to surface space. contents_device_transform has no 3d
1214  // component since it was flattened, so we don't need to project.
1215  gfx::QuadF surface_quad = MathUtil::MapQuad(contents_device_transform_inverse,
1216                                              device_layer_edges.ToQuadF(),
1217                                              &clipped);
1218
1219  SetShaderOpacity(quad->opacity(), shader_alpha_location);
1220  SetShaderQuadF(surface_quad, shader_quad_location);
1221  DrawQuadGeometry(
1222      frame, quad->quadTransform(), quad->rect, shader_matrix_location);
1223
1224  // Flush the compositor context before the filter bitmap goes out of
1225  // scope, so the draw gets processed before the filter texture gets deleted.
1226  if (filter_bitmap.getTexture())
1227    GLC(gl_, gl_->Flush());
1228}
1229
1230struct SolidColorProgramUniforms {
1231  unsigned program;
1232  unsigned matrix_location;
1233  unsigned viewport_location;
1234  unsigned quad_location;
1235  unsigned edge_location;
1236  unsigned color_location;
1237};
1238
1239template <class T>
1240static void SolidColorUniformLocation(T program,
1241                                      SolidColorProgramUniforms* uniforms) {
1242  uniforms->program = program->program();
1243  uniforms->matrix_location = program->vertex_shader().matrix_location();
1244  uniforms->viewport_location = program->vertex_shader().viewport_location();
1245  uniforms->quad_location = program->vertex_shader().quad_location();
1246  uniforms->edge_location = program->vertex_shader().edge_location();
1247  uniforms->color_location = program->fragment_shader().color_location();
1248}
1249
1250// static
1251bool GLRenderer::SetupQuadForAntialiasing(
1252    const gfx::Transform& device_transform,
1253    const DrawQuad* quad,
1254    gfx::QuadF* local_quad,
1255    float edge[24]) {
1256  gfx::Rect tile_rect = quad->visible_rect;
1257
1258  bool clipped = false;
1259  gfx::QuadF device_layer_quad = MathUtil::MapQuad(
1260      device_transform, gfx::QuadF(quad->visibleContentRect()), &clipped);
1261
1262  bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1263  bool is_nearest_rect_within_epsilon =
1264      is_axis_aligned_in_target &&
1265      gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1266                                       kAntiAliasingEpsilon);
1267  // AAing clipped quads is not supported by the code yet.
1268  bool use_aa = !clipped && !is_nearest_rect_within_epsilon && quad->IsEdge();
1269  if (!use_aa)
1270    return false;
1271
1272  LayerQuad device_layer_bounds(gfx::QuadF(device_layer_quad.BoundingBox()));
1273  device_layer_bounds.InflateAntiAliasingDistance();
1274
1275  LayerQuad device_layer_edges(device_layer_quad);
1276  device_layer_edges.InflateAntiAliasingDistance();
1277
1278  device_layer_edges.ToFloatArray(edge);
1279  device_layer_bounds.ToFloatArray(&edge[12]);
1280
1281  gfx::PointF bottom_right = tile_rect.bottom_right();
1282  gfx::PointF bottom_left = tile_rect.bottom_left();
1283  gfx::PointF top_left = tile_rect.origin();
1284  gfx::PointF top_right = tile_rect.top_right();
1285
1286  // Map points to device space.
1287  bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1288  DCHECK(!clipped);
1289  bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1290  DCHECK(!clipped);
1291  top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1292  DCHECK(!clipped);
1293  top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1294  DCHECK(!clipped);
1295
1296  LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1297  LayerQuad::Edge left_edge(bottom_left, top_left);
1298  LayerQuad::Edge top_edge(top_left, top_right);
1299  LayerQuad::Edge right_edge(top_right, bottom_right);
1300
1301  // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1302  if (quad->IsTopEdge() && tile_rect.y() == quad->rect.y())
1303    top_edge = device_layer_edges.top();
1304  if (quad->IsLeftEdge() && tile_rect.x() == quad->rect.x())
1305    left_edge = device_layer_edges.left();
1306  if (quad->IsRightEdge() && tile_rect.right() == quad->rect.right())
1307    right_edge = device_layer_edges.right();
1308  if (quad->IsBottomEdge() && tile_rect.bottom() == quad->rect.bottom())
1309    bottom_edge = device_layer_edges.bottom();
1310
1311  float sign = gfx::QuadF(tile_rect).IsCounterClockwise() ? -1 : 1;
1312  bottom_edge.scale(sign);
1313  left_edge.scale(sign);
1314  top_edge.scale(sign);
1315  right_edge.scale(sign);
1316
1317  // Create device space quad.
1318  LayerQuad device_quad(left_edge, top_edge, right_edge, bottom_edge);
1319
1320  // Map device space quad to local space. device_transform has no 3d
1321  // component since it was flattened, so we don't need to project.  We should
1322  // have already checked that the transform was uninvertible above.
1323  gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1324  bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1325  DCHECK(did_invert);
1326  *local_quad = MathUtil::MapQuad(
1327      inverse_device_transform, device_quad.ToQuadF(), &clipped);
1328  // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1329  // cause device_quad to become clipped. To our knowledge this scenario does
1330  // not need to be handled differently than the unclipped case.
1331
1332  return true;
1333}
1334
1335void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1336                                    const SolidColorDrawQuad* quad) {
1337  gfx::Rect tile_rect = quad->visible_rect;
1338
1339  SkColor color = quad->color;
1340  float opacity = quad->opacity();
1341  float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1342
1343  // Early out if alpha is small enough that quad doesn't contribute to output.
1344  if (alpha < std::numeric_limits<float>::epsilon() &&
1345      quad->ShouldDrawWithBlending())
1346    return;
1347
1348  gfx::Transform device_transform =
1349      frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1350  device_transform.FlattenTo2d();
1351  if (!device_transform.IsInvertible())
1352    return;
1353
1354  gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1355  float edge[24];
1356  bool use_aa =
1357      settings_->allow_antialiasing && !quad->force_anti_aliasing_off &&
1358      SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1359
1360  SolidColorProgramUniforms uniforms;
1361  if (use_aa)
1362    SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1363  else
1364    SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1365  SetUseProgram(uniforms.program);
1366
1367  GLC(gl_,
1368      gl_->Uniform4f(uniforms.color_location,
1369                     (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1370                     (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1371                     (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
1372                     alpha));
1373  if (use_aa) {
1374    float viewport[4] = {static_cast<float>(viewport_.x()),
1375                         static_cast<float>(viewport_.y()),
1376                         static_cast<float>(viewport_.width()),
1377                         static_cast<float>(viewport_.height()), };
1378    GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1379    GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1380  }
1381
1382  // Enable blending when the quad properties require it or if we decided
1383  // to use antialiasing.
1384  SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1385
1386  // Normalize to tile_rect.
1387  local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1388
1389  SetShaderQuadF(local_quad, uniforms.quad_location);
1390
1391  // The transform and vertex data are used to figure out the extents that the
1392  // un-antialiased quad should have and which vertex this is and the float
1393  // quad passed in via uniform is the actual geometry that gets used to draw
1394  // it. This is why this centered rect is used and not the original quad_rect.
1395  gfx::RectF centered_rect(
1396      gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1397      tile_rect.size());
1398  DrawQuadGeometry(
1399      frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1400}
1401
1402struct TileProgramUniforms {
1403  unsigned program;
1404  unsigned matrix_location;
1405  unsigned viewport_location;
1406  unsigned quad_location;
1407  unsigned edge_location;
1408  unsigned vertex_tex_transform_location;
1409  unsigned sampler_location;
1410  unsigned fragment_tex_transform_location;
1411  unsigned alpha_location;
1412};
1413
1414template <class T>
1415static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1416  uniforms->program = program->program();
1417  uniforms->matrix_location = program->vertex_shader().matrix_location();
1418  uniforms->viewport_location = program->vertex_shader().viewport_location();
1419  uniforms->quad_location = program->vertex_shader().quad_location();
1420  uniforms->edge_location = program->vertex_shader().edge_location();
1421  uniforms->vertex_tex_transform_location =
1422      program->vertex_shader().vertex_tex_transform_location();
1423
1424  uniforms->sampler_location = program->fragment_shader().sampler_location();
1425  uniforms->alpha_location = program->fragment_shader().alpha_location();
1426  uniforms->fragment_tex_transform_location =
1427      program->fragment_shader().fragment_tex_transform_location();
1428}
1429
1430void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1431                              const TileDrawQuad* quad) {
1432  DrawContentQuad(frame, quad, quad->resource_id);
1433}
1434
1435void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1436                                 const ContentDrawQuadBase* quad,
1437                                 ResourceProvider::ResourceId resource_id) {
1438  gfx::Rect tile_rect = quad->visible_rect;
1439
1440  gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1441      quad->tex_coord_rect, quad->rect, tile_rect);
1442  float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1443  float tex_to_geom_scale_y =
1444      quad->rect.height() / quad->tex_coord_rect.height();
1445
1446  gfx::RectF clamp_geom_rect(tile_rect);
1447  gfx::RectF clamp_tex_rect(tex_coord_rect);
1448  // Clamp texture coordinates to avoid sampling outside the layer
1449  // by deflating the tile region half a texel or half a texel
1450  // minus epsilon for one pixel layers. The resulting clamp region
1451  // is mapped to the unit square by the vertex shader and mapped
1452  // back to normalized texture coordinates by the fragment shader
1453  // after being clamped to 0-1 range.
1454  float tex_clamp_x =
1455      std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1456  float tex_clamp_y =
1457      std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1458  float geom_clamp_x =
1459      std::min(tex_clamp_x * tex_to_geom_scale_x,
1460               0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1461  float geom_clamp_y =
1462      std::min(tex_clamp_y * tex_to_geom_scale_y,
1463               0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1464  clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1465  clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1466
1467  // Map clamping rectangle to unit square.
1468  float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1469  float vertex_tex_translate_y =
1470      -clamp_geom_rect.y() / clamp_geom_rect.height();
1471  float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1472  float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1473
1474  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1475      gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1476
1477  gfx::Transform device_transform =
1478      frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1479  device_transform.FlattenTo2d();
1480  if (!device_transform.IsInvertible())
1481    return;
1482
1483  gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1484  float edge[24];
1485  bool use_aa =
1486      settings_->allow_antialiasing &&
1487      SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1488
1489  bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1490  GLenum filter = (use_aa || scaled ||
1491                   !quad->quadTransform().IsIdentityOrIntegerTranslation())
1492                      ? GL_LINEAR
1493                      : GL_NEAREST;
1494  ResourceProvider::ScopedSamplerGL quad_resource_lock(
1495      resource_provider_, resource_id, filter);
1496  SamplerType sampler =
1497      SamplerTypeFromTextureTarget(quad_resource_lock.target());
1498
1499  float fragment_tex_translate_x = clamp_tex_rect.x();
1500  float fragment_tex_translate_y = clamp_tex_rect.y();
1501  float fragment_tex_scale_x = clamp_tex_rect.width();
1502  float fragment_tex_scale_y = clamp_tex_rect.height();
1503
1504  // Map to normalized texture coordinates.
1505  if (sampler != SamplerType2DRect) {
1506    gfx::Size texture_size = quad->texture_size;
1507    DCHECK(!texture_size.IsEmpty());
1508    fragment_tex_translate_x /= texture_size.width();
1509    fragment_tex_translate_y /= texture_size.height();
1510    fragment_tex_scale_x /= texture_size.width();
1511    fragment_tex_scale_y /= texture_size.height();
1512  }
1513
1514  TileProgramUniforms uniforms;
1515  if (use_aa) {
1516    if (quad->swizzle_contents) {
1517      TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1518                          &uniforms);
1519    } else {
1520      TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1521                          &uniforms);
1522    }
1523  } else {
1524    if (quad->ShouldDrawWithBlending()) {
1525      if (quad->swizzle_contents) {
1526        TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1527                            &uniforms);
1528      } else {
1529        TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1530                            &uniforms);
1531      }
1532    } else {
1533      if (quad->swizzle_contents) {
1534        TileUniformLocation(
1535            GetTileProgramSwizzleOpaque(tex_coord_precision, sampler),
1536            &uniforms);
1537      } else {
1538        TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1539                            &uniforms);
1540      }
1541    }
1542  }
1543
1544  SetUseProgram(uniforms.program);
1545  GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1546
1547  if (use_aa) {
1548    float viewport[4] = {static_cast<float>(viewport_.x()),
1549                         static_cast<float>(viewport_.y()),
1550                         static_cast<float>(viewport_.width()),
1551                         static_cast<float>(viewport_.height()), };
1552    GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1553    GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1554
1555    GLC(gl_,
1556        gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1557                       vertex_tex_translate_x,
1558                       vertex_tex_translate_y,
1559                       vertex_tex_scale_x,
1560                       vertex_tex_scale_y));
1561    GLC(gl_,
1562        gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1563                       fragment_tex_translate_x,
1564                       fragment_tex_translate_y,
1565                       fragment_tex_scale_x,
1566                       fragment_tex_scale_y));
1567  } else {
1568    // Move fragment shader transform to vertex shader. We can do this while
1569    // still producing correct results as fragment_tex_transform_location
1570    // should always be non-negative when tiles are transformed in a way
1571    // that could result in sampling outside the layer.
1572    vertex_tex_scale_x *= fragment_tex_scale_x;
1573    vertex_tex_scale_y *= fragment_tex_scale_y;
1574    vertex_tex_translate_x *= fragment_tex_scale_x;
1575    vertex_tex_translate_y *= fragment_tex_scale_y;
1576    vertex_tex_translate_x += fragment_tex_translate_x;
1577    vertex_tex_translate_y += fragment_tex_translate_y;
1578
1579    GLC(gl_,
1580        gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1581                       vertex_tex_translate_x,
1582                       vertex_tex_translate_y,
1583                       vertex_tex_scale_x,
1584                       vertex_tex_scale_y));
1585  }
1586
1587  // Enable blending when the quad properties require it or if we decided
1588  // to use antialiasing.
1589  SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1590
1591  // Normalize to tile_rect.
1592  local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1593
1594  SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1595  SetShaderQuadF(local_quad, uniforms.quad_location);
1596
1597  // The transform and vertex data are used to figure out the extents that the
1598  // un-antialiased quad should have and which vertex this is and the float
1599  // quad passed in via uniform is the actual geometry that gets used to draw
1600  // it. This is why this centered rect is used and not the original quad_rect.
1601  gfx::RectF centered_rect(
1602      gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1603      tile_rect.size());
1604  DrawQuadGeometry(
1605      frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1606}
1607
1608void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1609                                  const YUVVideoDrawQuad* quad) {
1610  SetBlendEnabled(quad->ShouldDrawWithBlending());
1611
1612  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1613      gl_,
1614      &highp_threshold_cache_,
1615      highp_threshold_min_,
1616      quad->shared_quad_state->visible_content_rect.bottom_right());
1617
1618  bool use_alpha_plane = quad->a_plane_resource_id != 0;
1619
1620  ResourceProvider::ScopedSamplerGL y_plane_lock(
1621      resource_provider_, quad->y_plane_resource_id, GL_TEXTURE1, GL_LINEAR);
1622  DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), y_plane_lock.target());
1623  ResourceProvider::ScopedSamplerGL u_plane_lock(
1624      resource_provider_, quad->u_plane_resource_id, GL_TEXTURE2, GL_LINEAR);
1625  DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), u_plane_lock.target());
1626  ResourceProvider::ScopedSamplerGL v_plane_lock(
1627      resource_provider_, quad->v_plane_resource_id, GL_TEXTURE3, GL_LINEAR);
1628  DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), v_plane_lock.target());
1629  scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1630  if (use_alpha_plane) {
1631    a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1632        resource_provider_, quad->a_plane_resource_id, GL_TEXTURE4, GL_LINEAR));
1633    DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), a_plane_lock->target());
1634  }
1635
1636  int matrix_location = -1;
1637  int tex_scale_location = -1;
1638  int tex_offset_location = -1;
1639  int y_texture_location = -1;
1640  int u_texture_location = -1;
1641  int v_texture_location = -1;
1642  int a_texture_location = -1;
1643  int yuv_matrix_location = -1;
1644  int yuv_adj_location = -1;
1645  int alpha_location = -1;
1646  if (use_alpha_plane) {
1647    const VideoYUVAProgram* program = GetVideoYUVAProgram(tex_coord_precision);
1648    DCHECK(program && (program->initialized() || IsContextLost()));
1649    SetUseProgram(program->program());
1650    matrix_location = program->vertex_shader().matrix_location();
1651    tex_scale_location = program->vertex_shader().tex_scale_location();
1652    tex_offset_location = program->vertex_shader().tex_offset_location();
1653    y_texture_location = program->fragment_shader().y_texture_location();
1654    u_texture_location = program->fragment_shader().u_texture_location();
1655    v_texture_location = program->fragment_shader().v_texture_location();
1656    a_texture_location = program->fragment_shader().a_texture_location();
1657    yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1658    yuv_adj_location = program->fragment_shader().yuv_adj_location();
1659    alpha_location = program->fragment_shader().alpha_location();
1660  } else {
1661    const VideoYUVProgram* program = GetVideoYUVProgram(tex_coord_precision);
1662    DCHECK(program && (program->initialized() || IsContextLost()));
1663    SetUseProgram(program->program());
1664    matrix_location = program->vertex_shader().matrix_location();
1665    tex_scale_location = program->vertex_shader().tex_scale_location();
1666    tex_offset_location = program->vertex_shader().tex_offset_location();
1667    y_texture_location = program->fragment_shader().y_texture_location();
1668    u_texture_location = program->fragment_shader().u_texture_location();
1669    v_texture_location = program->fragment_shader().v_texture_location();
1670    yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1671    yuv_adj_location = program->fragment_shader().yuv_adj_location();
1672    alpha_location = program->fragment_shader().alpha_location();
1673  }
1674
1675  GLC(gl_,
1676      gl_->Uniform2f(tex_scale_location,
1677                     quad->tex_coord_rect.width(),
1678                     quad->tex_coord_rect.height()));
1679  GLC(gl_,
1680      gl_->Uniform2f(tex_offset_location,
1681                     quad->tex_coord_rect.x(),
1682                     quad->tex_coord_rect.y()));
1683  GLC(gl_, gl_->Uniform1i(y_texture_location, 1));
1684  GLC(gl_, gl_->Uniform1i(u_texture_location, 2));
1685  GLC(gl_, gl_->Uniform1i(v_texture_location, 3));
1686  if (use_alpha_plane)
1687    GLC(gl_, gl_->Uniform1i(a_texture_location, 4));
1688
1689  // These values are magic numbers that are used in the transformation from YUV
1690  // to RGB color values.  They are taken from the following webpage:
1691  // http://www.fourcc.org/fccyvrgb.php
1692  float yuv_to_rgb[9] = {1.164f, 1.164f, 1.164f, 0.0f, -.391f,
1693                         2.018f, 1.596f, -.813f, 0.0f, };
1694  GLC(gl_, gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb));
1695
1696  // These values map to 16, 128, and 128 respectively, and are computed
1697  // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
1698  // They are used in the YUV to RGBA conversion formula:
1699  //   Y - 16   : Gives 16 values of head and footroom for overshooting
1700  //   U - 128  : Turns unsigned U into signed U [-128,127]
1701  //   V - 128  : Turns unsigned V into signed V [-128,127]
1702  float yuv_adjust[3] = {-0.0625f, -0.5f, -0.5f, };
1703  GLC(gl_, gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust));
1704
1705  SetShaderOpacity(quad->opacity(), alpha_location);
1706  DrawQuadGeometry(frame, quad->quadTransform(), quad->rect, matrix_location);
1707}
1708
1709void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
1710                                     const StreamVideoDrawQuad* quad) {
1711  SetBlendEnabled(quad->ShouldDrawWithBlending());
1712
1713  static float gl_matrix[16];
1714
1715  DCHECK(capabilities_.using_egl_image);
1716
1717  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1718      gl_,
1719      &highp_threshold_cache_,
1720      highp_threshold_min_,
1721      quad->shared_quad_state->visible_content_rect.bottom_right());
1722
1723  const VideoStreamTextureProgram* program =
1724      GetVideoStreamTextureProgram(tex_coord_precision);
1725  SetUseProgram(program->program());
1726
1727  ToGLMatrix(&gl_matrix[0], quad->matrix);
1728  GLC(gl_,
1729      gl_->UniformMatrix4fv(
1730          program->vertex_shader().tex_matrix_location(), 1, false, gl_matrix));
1731
1732  ResourceProvider::ScopedReadLockGL lock(resource_provider_,
1733                                          quad->resource_id);
1734  DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
1735  GLC(gl_, gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id()));
1736
1737  GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1738
1739  SetShaderOpacity(quad->opacity(),
1740                   program->fragment_shader().alpha_location());
1741  DrawQuadGeometry(frame,
1742                   quad->quadTransform(),
1743                   quad->rect,
1744                   program->vertex_shader().matrix_location());
1745}
1746
1747void GLRenderer::DrawPictureQuad(const DrawingFrame* frame,
1748                                 const PictureDrawQuad* quad) {
1749  if (on_demand_tile_raster_bitmap_.width() != quad->texture_size.width() ||
1750      on_demand_tile_raster_bitmap_.height() != quad->texture_size.height()) {
1751    on_demand_tile_raster_bitmap_.allocN32Pixels(quad->texture_size.width(),
1752                                                 quad->texture_size.height());
1753
1754    if (on_demand_tile_raster_resource_id_)
1755      resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
1756
1757    on_demand_tile_raster_resource_id_ =
1758        resource_provider_->CreateGLTexture(quad->texture_size,
1759                                            GL_TEXTURE_2D,
1760                                            GL_TEXTURE_POOL_UNMANAGED_CHROMIUM,
1761                                            GL_CLAMP_TO_EDGE,
1762                                            ResourceProvider::TextureUsageAny,
1763                                            quad->texture_format);
1764  }
1765
1766  // Create and run on-demand raster task for tile.
1767  scoped_refptr<internal::Task> on_demand_raster_task(
1768      new OnDemandRasterTaskImpl(quad->picture_pile,
1769                                 &on_demand_tile_raster_bitmap_,
1770                                 quad->content_rect,
1771                                 quad->contents_scale));
1772  RunOnDemandRasterTask(on_demand_raster_task.get());
1773
1774  uint8_t* bitmap_pixels = NULL;
1775  SkBitmap on_demand_tile_raster_bitmap_dest;
1776  SkColorType colorType = ResourceFormatToSkColorType(quad->texture_format);
1777  if (on_demand_tile_raster_bitmap_.colorType() != colorType) {
1778    on_demand_tile_raster_bitmap_.copyTo(&on_demand_tile_raster_bitmap_dest,
1779                                         colorType);
1780    // TODO(kaanb): The GL pipeline assumes a 4-byte alignment for the
1781    // bitmap data. This check will be removed once crbug.com/293728 is fixed.
1782    CHECK_EQ(0u, on_demand_tile_raster_bitmap_dest.rowBytes() % 4);
1783    bitmap_pixels = reinterpret_cast<uint8_t*>(
1784        on_demand_tile_raster_bitmap_dest.getPixels());
1785  } else {
1786    bitmap_pixels =
1787        reinterpret_cast<uint8_t*>(on_demand_tile_raster_bitmap_.getPixels());
1788  }
1789
1790  resource_provider_->SetPixels(on_demand_tile_raster_resource_id_,
1791                                bitmap_pixels,
1792                                gfx::Rect(quad->texture_size),
1793                                gfx::Rect(quad->texture_size),
1794                                gfx::Vector2d());
1795
1796  DrawContentQuad(frame, quad, on_demand_tile_raster_resource_id_);
1797}
1798
1799struct TextureProgramBinding {
1800  template <class Program>
1801  void Set(Program* program) {
1802    DCHECK(program);
1803    program_id = program->program();
1804    sampler_location = program->fragment_shader().sampler_location();
1805    matrix_location = program->vertex_shader().matrix_location();
1806    background_color_location =
1807        program->fragment_shader().background_color_location();
1808  }
1809  int program_id;
1810  int sampler_location;
1811  int matrix_location;
1812  int background_color_location;
1813};
1814
1815struct TexTransformTextureProgramBinding : TextureProgramBinding {
1816  template <class Program>
1817  void Set(Program* program) {
1818    TextureProgramBinding::Set(program);
1819    tex_transform_location = program->vertex_shader().tex_transform_location();
1820    vertex_opacity_location =
1821        program->vertex_shader().vertex_opacity_location();
1822  }
1823  int tex_transform_location;
1824  int vertex_opacity_location;
1825};
1826
1827void GLRenderer::FlushTextureQuadCache() {
1828  // Check to see if we have anything to draw.
1829  if (draw_cache_.program_id == 0)
1830    return;
1831
1832  // Set the correct blending mode.
1833  SetBlendEnabled(draw_cache_.needs_blending);
1834
1835  // Bind the program to the GL state.
1836  SetUseProgram(draw_cache_.program_id);
1837
1838  // Bind the correct texture sampler location.
1839  GLC(gl_, gl_->Uniform1i(draw_cache_.sampler_location, 0));
1840
1841  // Assume the current active textures is 0.
1842  ResourceProvider::ScopedReadLockGL locked_quad(resource_provider_,
1843                                                 draw_cache_.resource_id);
1844  DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
1845  GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, locked_quad.texture_id()));
1846
1847  COMPILE_ASSERT(sizeof(Float4) == 4 * sizeof(float),  // NOLINT(runtime/sizeof)
1848                 struct_is_densely_packed);
1849  COMPILE_ASSERT(
1850      sizeof(Float16) == 16 * sizeof(float),  // NOLINT(runtime/sizeof)
1851      struct_is_densely_packed);
1852
1853  // Upload the tranforms for both points and uvs.
1854  GLC(gl_,
1855      gl_->UniformMatrix4fv(
1856          static_cast<int>(draw_cache_.matrix_location),
1857          static_cast<int>(draw_cache_.matrix_data.size()),
1858          false,
1859          reinterpret_cast<float*>(&draw_cache_.matrix_data.front())));
1860  GLC(gl_,
1861      gl_->Uniform4fv(
1862          static_cast<int>(draw_cache_.uv_xform_location),
1863          static_cast<int>(draw_cache_.uv_xform_data.size()),
1864          reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front())));
1865
1866  if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
1867    Float4 background_color = PremultipliedColor(draw_cache_.background_color);
1868    GLC(gl_,
1869        gl_->Uniform4fv(
1870            draw_cache_.background_color_location, 1, background_color.data));
1871  }
1872
1873  GLC(gl_,
1874      gl_->Uniform1fv(
1875          static_cast<int>(draw_cache_.vertex_opacity_location),
1876          static_cast<int>(draw_cache_.vertex_opacity_data.size()),
1877          static_cast<float*>(&draw_cache_.vertex_opacity_data.front())));
1878
1879  // Draw the quads!
1880  GLC(gl_,
1881      gl_->DrawElements(GL_TRIANGLES,
1882                        6 * draw_cache_.matrix_data.size(),
1883                        GL_UNSIGNED_SHORT,
1884                        0));
1885
1886  // Clear the cache.
1887  draw_cache_.program_id = 0;
1888  draw_cache_.uv_xform_data.resize(0);
1889  draw_cache_.vertex_opacity_data.resize(0);
1890  draw_cache_.matrix_data.resize(0);
1891}
1892
1893void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
1894                                    const TextureDrawQuad* quad) {
1895  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1896      gl_,
1897      &highp_threshold_cache_,
1898      highp_threshold_min_,
1899      quad->shared_quad_state->visible_content_rect.bottom_right());
1900
1901  // Choose the correct texture program binding
1902  TexTransformTextureProgramBinding binding;
1903  if (quad->premultiplied_alpha) {
1904    if (quad->background_color == SK_ColorTRANSPARENT) {
1905      binding.Set(GetTextureProgram(tex_coord_precision));
1906    } else {
1907      binding.Set(GetTextureBackgroundProgram(tex_coord_precision));
1908    }
1909  } else {
1910    if (quad->background_color == SK_ColorTRANSPARENT) {
1911      binding.Set(GetNonPremultipliedTextureProgram(tex_coord_precision));
1912    } else {
1913      binding.Set(
1914          GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision));
1915    }
1916  }
1917
1918  int resource_id = quad->resource_id;
1919
1920  if (draw_cache_.program_id != binding.program_id ||
1921      draw_cache_.resource_id != resource_id ||
1922      draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
1923      draw_cache_.background_color != quad->background_color ||
1924      draw_cache_.matrix_data.size() >= 8) {
1925    FlushTextureQuadCache();
1926    draw_cache_.program_id = binding.program_id;
1927    draw_cache_.resource_id = resource_id;
1928    draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
1929    draw_cache_.background_color = quad->background_color;
1930
1931    draw_cache_.uv_xform_location = binding.tex_transform_location;
1932    draw_cache_.background_color_location = binding.background_color_location;
1933    draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
1934    draw_cache_.matrix_location = binding.matrix_location;
1935    draw_cache_.sampler_location = binding.sampler_location;
1936  }
1937
1938  // Generate the uv-transform
1939  draw_cache_.uv_xform_data.push_back(UVTransform(quad));
1940
1941  // Generate the vertex opacity
1942  const float opacity = quad->opacity();
1943  draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
1944  draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
1945  draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
1946  draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
1947
1948  // Generate the transform matrix
1949  gfx::Transform quad_rect_matrix;
1950  QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
1951  quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
1952
1953  Float16 m;
1954  quad_rect_matrix.matrix().asColMajorf(m.data);
1955  draw_cache_.matrix_data.push_back(m);
1956}
1957
1958void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
1959                                   const IOSurfaceDrawQuad* quad) {
1960  SetBlendEnabled(quad->ShouldDrawWithBlending());
1961
1962  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1963      gl_,
1964      &highp_threshold_cache_,
1965      highp_threshold_min_,
1966      quad->shared_quad_state->visible_content_rect.bottom_right());
1967
1968  TexTransformTextureProgramBinding binding;
1969  binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
1970
1971  SetUseProgram(binding.program_id);
1972  GLC(gl_, gl_->Uniform1i(binding.sampler_location, 0));
1973  if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
1974    GLC(gl_,
1975        gl_->Uniform4f(binding.tex_transform_location,
1976                       0,
1977                       quad->io_surface_size.height(),
1978                       quad->io_surface_size.width(),
1979                       quad->io_surface_size.height() * -1.0f));
1980  } else {
1981    GLC(gl_,
1982        gl_->Uniform4f(binding.tex_transform_location,
1983                       0,
1984                       0,
1985                       quad->io_surface_size.width(),
1986                       quad->io_surface_size.height()));
1987  }
1988
1989  const float vertex_opacity[] = {quad->opacity(), quad->opacity(),
1990                                  quad->opacity(), quad->opacity()};
1991  GLC(gl_, gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity));
1992
1993  ResourceProvider::ScopedReadLockGL lock(resource_provider_,
1994                                          quad->io_surface_resource_id);
1995  DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
1996  GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id()));
1997
1998  DrawQuadGeometry(
1999      frame, quad->quadTransform(), quad->rect, binding.matrix_location);
2000
2001  GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0));
2002}
2003
2004void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2005  current_framebuffer_lock_.reset();
2006  swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2007
2008  GLC(gl_, gl_->Disable(GL_BLEND));
2009  blend_shadow_ = false;
2010
2011  ScheduleOverlays(frame);
2012}
2013
2014void GLRenderer::FinishDrawingQuadList() { FlushTextureQuadCache(); }
2015
2016bool GLRenderer::FlippedFramebuffer() const { return true; }
2017
2018void GLRenderer::EnsureScissorTestEnabled() {
2019  if (is_scissor_enabled_)
2020    return;
2021
2022  FlushTextureQuadCache();
2023  GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
2024  is_scissor_enabled_ = true;
2025}
2026
2027void GLRenderer::EnsureScissorTestDisabled() {
2028  if (!is_scissor_enabled_)
2029    return;
2030
2031  FlushTextureQuadCache();
2032  GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
2033  is_scissor_enabled_ = false;
2034}
2035
2036void GLRenderer::CopyCurrentRenderPassToBitmap(
2037    DrawingFrame* frame,
2038    scoped_ptr<CopyOutputRequest> request) {
2039  gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2040  if (request->has_area())
2041    copy_rect.Intersect(request->area());
2042  GetFramebufferPixelsAsync(copy_rect, request.Pass());
2043}
2044
2045void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2046  transform.matrix().asColMajorf(gl_matrix);
2047}
2048
2049void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2050  if (quad_location == -1)
2051    return;
2052
2053  float gl_quad[8];
2054  gl_quad[0] = quad.p1().x();
2055  gl_quad[1] = quad.p1().y();
2056  gl_quad[2] = quad.p2().x();
2057  gl_quad[3] = quad.p2().y();
2058  gl_quad[4] = quad.p3().x();
2059  gl_quad[5] = quad.p3().y();
2060  gl_quad[6] = quad.p4().x();
2061  gl_quad[7] = quad.p4().y();
2062  GLC(gl_, gl_->Uniform2fv(quad_location, 4, gl_quad));
2063}
2064
2065void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2066  if (alpha_location != -1)
2067    GLC(gl_, gl_->Uniform1f(alpha_location, opacity));
2068}
2069
2070void GLRenderer::SetStencilEnabled(bool enabled) {
2071  if (enabled == stencil_shadow_)
2072    return;
2073
2074  if (enabled)
2075    GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
2076  else
2077    GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
2078  stencil_shadow_ = enabled;
2079}
2080
2081void GLRenderer::SetBlendEnabled(bool enabled) {
2082  if (enabled == blend_shadow_)
2083    return;
2084
2085  if (enabled)
2086    GLC(gl_, gl_->Enable(GL_BLEND));
2087  else
2088    GLC(gl_, gl_->Disable(GL_BLEND));
2089  blend_shadow_ = enabled;
2090}
2091
2092void GLRenderer::SetUseProgram(unsigned program) {
2093  if (program == program_shadow_)
2094    return;
2095  gl_->UseProgram(program);
2096  program_shadow_ = program;
2097}
2098
2099void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2100                                  const gfx::Transform& draw_transform,
2101                                  const gfx::RectF& quad_rect,
2102                                  int matrix_location) {
2103  gfx::Transform quad_rect_matrix;
2104  QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2105  static float gl_matrix[16];
2106  ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2107  GLC(gl_, gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]));
2108
2109  GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
2110}
2111
2112void GLRenderer::CopyTextureToFramebuffer(const DrawingFrame* frame,
2113                                          int texture_id,
2114                                          const gfx::Rect& rect,
2115                                          const gfx::Transform& draw_matrix,
2116                                          bool flip_vertically) {
2117  TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2118      gl_, &highp_threshold_cache_, highp_threshold_min_, rect.bottom_right());
2119
2120  const RenderPassProgram* program = GetRenderPassProgram(tex_coord_precision);
2121  SetUseProgram(program->program());
2122
2123  GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
2124
2125  if (flip_vertically) {
2126    GLC(gl_,
2127        gl_->Uniform4f(program->vertex_shader().tex_transform_location(),
2128                       0.f,
2129                       1.f,
2130                       1.f,
2131                       -1.f));
2132  } else {
2133    GLC(gl_,
2134        gl_->Uniform4f(program->vertex_shader().tex_transform_location(),
2135                       0.f,
2136                       0.f,
2137                       1.f,
2138                       1.f));
2139  }
2140
2141  SetShaderOpacity(1.f, program->fragment_shader().alpha_location());
2142  DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
2143  GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2144  DrawQuadGeometry(
2145      frame, draw_matrix, rect, program->vertex_shader().matrix_location());
2146}
2147
2148void GLRenderer::Finish() {
2149  TRACE_EVENT0("cc", "GLRenderer::Finish");
2150  GLC(gl_, gl_->Finish());
2151}
2152
2153void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2154  DCHECK(!is_backbuffer_discarded_);
2155
2156  TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2157  // We're done! Time to swapbuffers!
2158
2159  gfx::Size surface_size = output_surface_->SurfaceSize();
2160
2161  CompositorFrame compositor_frame;
2162  compositor_frame.metadata = metadata;
2163  compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2164  compositor_frame.gl_frame_data->size = surface_size;
2165  if (capabilities_.using_partial_swap) {
2166    // If supported, we can save significant bandwidth by only swapping the
2167    // damaged/scissored region (clamped to the viewport).
2168    swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2169    int flipped_y_pos_of_rect_bottom = surface_size.height() -
2170                                       swap_buffer_rect_.y() -
2171                                       swap_buffer_rect_.height();
2172    compositor_frame.gl_frame_data->sub_buffer_rect =
2173        gfx::Rect(swap_buffer_rect_.x(),
2174                  flipped_y_pos_of_rect_bottom,
2175                  swap_buffer_rect_.width(),
2176                  swap_buffer_rect_.height());
2177  } else {
2178    compositor_frame.gl_frame_data->sub_buffer_rect =
2179        gfx::Rect(output_surface_->SurfaceSize());
2180  }
2181  output_surface_->SwapBuffers(&compositor_frame);
2182
2183  // Release previously used overlay resources and hold onto the pending ones
2184  // until the next swap buffers.
2185  in_use_overlay_resources_.clear();
2186  in_use_overlay_resources_.swap(pending_overlay_resources_);
2187
2188  swap_buffer_rect_ = gfx::Rect();
2189
2190  // We don't have real fences, so we mark read fences as passed
2191  // assuming a double-buffered GPU pipeline. A texture can be
2192  // written to after one full frame has past since it was last read.
2193  if (last_swap_fence_.get())
2194    static_cast<SimpleSwapFence*>(last_swap_fence_.get())->SetHasPassed();
2195  last_swap_fence_ = resource_provider_->GetReadLockFence();
2196  resource_provider_->SetReadLockFence(new SimpleSwapFence());
2197}
2198
2199void GLRenderer::EnforceMemoryPolicy() {
2200  if (!visible_) {
2201    TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2202    ReleaseRenderPassTextures();
2203    DiscardBackbuffer();
2204    resource_provider_->ReleaseCachedData();
2205    GLC(gl_, gl_->Flush());
2206  }
2207}
2208
2209void GLRenderer::DiscardBackbuffer() {
2210  if (is_backbuffer_discarded_)
2211    return;
2212
2213  output_surface_->DiscardBackbuffer();
2214
2215  is_backbuffer_discarded_ = true;
2216
2217  // Damage tracker needs a full reset every time framebuffer is discarded.
2218  client_->SetFullRootLayerDamage();
2219}
2220
2221void GLRenderer::EnsureBackbuffer() {
2222  if (!is_backbuffer_discarded_)
2223    return;
2224
2225  output_surface_->EnsureBackbuffer();
2226  is_backbuffer_discarded_ = false;
2227}
2228
2229void GLRenderer::GetFramebufferPixels(void* pixels, const gfx::Rect& rect) {
2230  if (!pixels || rect.IsEmpty())
2231    return;
2232
2233  // This function assumes that it is reading the root frame buffer.
2234  DCHECK(!current_framebuffer_lock_);
2235
2236  scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2237  pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2238                                    pending_read.Pass());
2239
2240  // This is a syncronous call since the callback is null.
2241  gfx::Rect window_rect = MoveFromDrawToWindowSpace(rect);
2242  DoGetFramebufferPixels(static_cast<uint8*>(pixels),
2243                         window_rect,
2244                         AsyncGetFramebufferPixelsCleanupCallback());
2245}
2246
2247void GLRenderer::GetFramebufferPixelsAsync(
2248    const gfx::Rect& rect,
2249    scoped_ptr<CopyOutputRequest> request) {
2250  DCHECK(!request->IsEmpty());
2251  if (request->IsEmpty())
2252    return;
2253  if (rect.IsEmpty())
2254    return;
2255
2256  gfx::Rect window_rect = MoveFromDrawToWindowSpace(rect);
2257
2258  if (!request->force_bitmap_result()) {
2259    bool own_mailbox = !request->has_texture_mailbox();
2260
2261    GLuint texture_id = 0;
2262    gl_->GenTextures(1, &texture_id);
2263
2264    gpu::Mailbox mailbox;
2265    if (own_mailbox) {
2266      GLC(gl_, gl_->GenMailboxCHROMIUM(mailbox.name));
2267    } else {
2268      mailbox = request->texture_mailbox().mailbox();
2269      DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2270                request->texture_mailbox().target());
2271      DCHECK(!mailbox.IsZero());
2272      unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2273      if (incoming_sync_point)
2274        GLC(gl_, gl_->WaitSyncPointCHROMIUM(incoming_sync_point));
2275    }
2276
2277    GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2278    if (own_mailbox) {
2279      GLC(gl_,
2280          gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2281      GLC(gl_,
2282          gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2283      GLC(gl_,
2284          gl_->TexParameteri(
2285              GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2286      GLC(gl_,
2287          gl_->TexParameteri(
2288              GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2289      GLC(gl_, gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2290    } else {
2291      GLC(gl_, gl_->ConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2292    }
2293    GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2294    GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2295
2296    unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2297    TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2298
2299    scoped_ptr<SingleReleaseCallback> release_callback;
2300    if (own_mailbox) {
2301      release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2302          output_surface_->context_provider(), texture_id);
2303    } else {
2304      gl_->DeleteTextures(1, &texture_id);
2305    }
2306
2307    request->SendTextureResult(
2308        window_rect.size(), texture_mailbox, release_callback.Pass());
2309    return;
2310  }
2311
2312  DCHECK(request->force_bitmap_result());
2313
2314  scoped_ptr<SkBitmap> bitmap(new SkBitmap);
2315  bitmap->allocN32Pixels(window_rect.width(), window_rect.height());
2316
2317  scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2318
2319  // Save a pointer to the pixels, the bitmap is owned by the cleanup_callback.
2320  uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
2321
2322  AsyncGetFramebufferPixelsCleanupCallback cleanup_callback =
2323      base::Bind(&GLRenderer::PassOnSkBitmap,
2324                 base::Unretained(this),
2325                 base::Passed(&bitmap),
2326                 base::Passed(&lock));
2327
2328  scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2329  pending_read->copy_request = request.Pass();
2330  pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2331                                    pending_read.Pass());
2332
2333  // This is an asyncronous call since the callback is not null.
2334  DoGetFramebufferPixels(pixels, window_rect, cleanup_callback);
2335}
2336
2337void GLRenderer::DoGetFramebufferPixels(
2338    uint8* dest_pixels,
2339    const gfx::Rect& window_rect,
2340    const AsyncGetFramebufferPixelsCleanupCallback& cleanup_callback) {
2341  DCHECK_GE(window_rect.x(), 0);
2342  DCHECK_GE(window_rect.y(), 0);
2343  DCHECK_LE(window_rect.right(), current_surface_size_.width());
2344  DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2345
2346  bool is_async = !cleanup_callback.is_null();
2347
2348  bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2349
2350  unsigned temporary_texture = 0;
2351  unsigned temporary_fbo = 0;
2352
2353  if (do_workaround) {
2354    // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2355    // is an IOSurface-backed texture causes corruption of future glReadPixels()
2356    // calls, even those on different OpenGL contexts. It is believed that this
2357    // is the root cause of top crasher
2358    // http://crbug.com/99393. <rdar://problem/10949687>
2359
2360    gl_->GenTextures(1, &temporary_texture);
2361    GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, temporary_texture));
2362    GLC(gl_,
2363        gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2364    GLC(gl_,
2365        gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2366    GLC(gl_,
2367        gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2368    GLC(gl_,
2369        gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2370    // Copy the contents of the current (IOSurface-backed) framebuffer into a
2371    // temporary texture.
2372    GetFramebufferTexture(
2373        temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2374    gl_->GenFramebuffers(1, &temporary_fbo);
2375    // Attach this texture to an FBO, and perform the readback from that FBO.
2376    GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo));
2377    GLC(gl_,
2378        gl_->FramebufferTexture2D(GL_FRAMEBUFFER,
2379                                  GL_COLOR_ATTACHMENT0,
2380                                  GL_TEXTURE_2D,
2381                                  temporary_texture,
2382                                  0));
2383
2384    DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2385              gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2386  }
2387
2388  GLuint buffer = 0;
2389  gl_->GenBuffers(1, &buffer);
2390  GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer));
2391  GLC(gl_,
2392      gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2393                      4 * window_rect.size().GetArea(),
2394                      NULL,
2395                      GL_STREAM_READ));
2396
2397  GLuint query = 0;
2398  if (is_async) {
2399    gl_->GenQueriesEXT(1, &query);
2400    GLC(gl_, gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query));
2401  }
2402
2403  GLC(gl_,
2404      gl_->ReadPixels(window_rect.x(),
2405                      window_rect.y(),
2406                      window_rect.width(),
2407                      window_rect.height(),
2408                      GL_RGBA,
2409                      GL_UNSIGNED_BYTE,
2410                      NULL));
2411
2412  GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2413
2414  if (do_workaround) {
2415    // Clean up.
2416    GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
2417    GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2418    GLC(gl_, gl_->DeleteFramebuffers(1, &temporary_fbo));
2419    GLC(gl_, gl_->DeleteTextures(1, &temporary_texture));
2420  }
2421
2422  base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2423                                               base::Unretained(this),
2424                                               cleanup_callback,
2425                                               buffer,
2426                                               query,
2427                                               dest_pixels,
2428                                               window_rect.size());
2429  // Save the finished_callback so it can be cancelled.
2430  pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2431      finished_callback);
2432  base::Closure cancelable_callback =
2433      pending_async_read_pixels_.front()->
2434          finished_read_pixels_callback.callback();
2435
2436  // Save the buffer to verify the callbacks happen in the expected order.
2437  pending_async_read_pixels_.front()->buffer = buffer;
2438
2439  if (is_async) {
2440    GLC(gl_, gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM));
2441    context_support_->SignalQuery(query, cancelable_callback);
2442  } else {
2443    resource_provider_->Finish();
2444    finished_callback.Run();
2445  }
2446
2447  EnforceMemoryPolicy();
2448}
2449
2450void GLRenderer::FinishedReadback(
2451    const AsyncGetFramebufferPixelsCleanupCallback& cleanup_callback,
2452    unsigned source_buffer,
2453    unsigned query,
2454    uint8* dest_pixels,
2455    const gfx::Size& size) {
2456  DCHECK(!pending_async_read_pixels_.empty());
2457
2458  if (query != 0) {
2459    GLC(gl_, gl_->DeleteQueriesEXT(1, &query));
2460  }
2461
2462  PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2463  // Make sure we service the readbacks in order.
2464  DCHECK_EQ(source_buffer, current_read->buffer);
2465
2466  uint8* src_pixels = NULL;
2467
2468  if (source_buffer != 0) {
2469    GLC(gl_,
2470        gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer));
2471    src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2472        GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2473
2474    if (src_pixels) {
2475      size_t row_bytes = size.width() * 4;
2476      int num_rows = size.height();
2477      size_t total_bytes = num_rows * row_bytes;
2478      for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2479        // Flip Y axis.
2480        size_t src_y = total_bytes - dest_y - row_bytes;
2481        // Swizzle OpenGL -> Skia byte order.
2482        for (size_t x = 0; x < row_bytes; x += 4) {
2483          dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2484              src_pixels[src_y + x + 0];
2485          dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2486              src_pixels[src_y + x + 1];
2487          dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2488              src_pixels[src_y + x + 2];
2489          dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2490              src_pixels[src_y + x + 3];
2491        }
2492      }
2493
2494      GLC(gl_,
2495          gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM));
2496    }
2497    GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2498    GLC(gl_, gl_->DeleteBuffers(1, &source_buffer));
2499  }
2500
2501  // TODO(danakj): This can go away when synchronous readback is no more and its
2502  // contents can just move here.
2503  if (!cleanup_callback.is_null())
2504    cleanup_callback.Run(current_read->copy_request.Pass(), src_pixels != NULL);
2505
2506  pending_async_read_pixels_.pop_back();
2507}
2508
2509void GLRenderer::PassOnSkBitmap(scoped_ptr<SkBitmap> bitmap,
2510                                scoped_ptr<SkAutoLockPixels> lock,
2511                                scoped_ptr<CopyOutputRequest> request,
2512                                bool success) {
2513  DCHECK(request->force_bitmap_result());
2514
2515  lock.reset();
2516  if (success)
2517    request->SendBitmapResult(bitmap.Pass());
2518}
2519
2520void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2521                                       ResourceFormat texture_format,
2522                                       const gfx::Rect& window_rect) {
2523  DCHECK(texture_id);
2524  DCHECK_GE(window_rect.x(), 0);
2525  DCHECK_GE(window_rect.y(), 0);
2526  DCHECK_LE(window_rect.right(), current_surface_size_.width());
2527  DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2528
2529  GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2530  GLC(gl_,
2531      gl_->CopyTexImage2D(GL_TEXTURE_2D,
2532                          0,
2533                          GLDataFormat(texture_format),
2534                          window_rect.x(),
2535                          window_rect.y(),
2536                          window_rect.width(),
2537                          window_rect.height(),
2538                          0));
2539  GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2540}
2541
2542bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2543                                  const ScopedResource* texture,
2544                                  const gfx::Rect& viewport_rect) {
2545  DCHECK(texture->id());
2546  frame->current_render_pass = NULL;
2547  frame->current_texture = texture;
2548
2549  return BindFramebufferToTexture(frame, texture, viewport_rect);
2550}
2551
2552void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2553  current_framebuffer_lock_.reset();
2554  output_surface_->BindFramebuffer();
2555
2556  if (output_surface_->HasExternalStencilTest()) {
2557    SetStencilEnabled(true);
2558    GLC(gl_, gl_->StencilFunc(GL_EQUAL, 1, 1));
2559  } else {
2560    SetStencilEnabled(false);
2561  }
2562}
2563
2564bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2565                                          const ScopedResource* texture,
2566                                          const gfx::Rect& target_rect) {
2567  DCHECK(texture->id());
2568
2569  current_framebuffer_lock_.reset();
2570
2571  SetStencilEnabled(false);
2572  GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_));
2573  current_framebuffer_lock_ =
2574      make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2575          resource_provider_, texture->id()));
2576  unsigned texture_id = current_framebuffer_lock_->texture_id();
2577  GLC(gl_,
2578      gl_->FramebufferTexture2D(
2579          GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_id, 0));
2580
2581  DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2582             GL_FRAMEBUFFER_COMPLETE ||
2583         IsContextLost());
2584
2585  InitializeViewport(
2586      frame, target_rect, gfx::Rect(target_rect.size()), target_rect.size());
2587  return true;
2588}
2589
2590void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2591  EnsureScissorTestEnabled();
2592
2593  // Don't unnecessarily ask the context to change the scissor, because it
2594  // may cause undesired GPU pipeline flushes.
2595  if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2596    return;
2597
2598  scissor_rect_ = scissor_rect;
2599  FlushTextureQuadCache();
2600  GLC(gl_,
2601      gl_->Scissor(scissor_rect.x(),
2602                   scissor_rect.y(),
2603                   scissor_rect.width(),
2604                   scissor_rect.height()));
2605
2606  scissor_rect_needs_reset_ = false;
2607}
2608
2609void GLRenderer::SetDrawViewport(const gfx::Rect& window_space_viewport) {
2610  viewport_ = window_space_viewport;
2611  GLC(gl_,
2612      gl_->Viewport(window_space_viewport.x(),
2613                    window_space_viewport.y(),
2614                    window_space_viewport.width(),
2615                    window_space_viewport.height()));
2616}
2617
2618void GLRenderer::InitializeSharedObjects() {
2619  TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2620
2621  // Create an FBO for doing offscreen rendering.
2622  GLC(gl_, gl_->GenFramebuffers(1, &offscreen_framebuffer_id_));
2623
2624  shared_geometry_ = make_scoped_ptr(
2625      new GeometryBinding(gl_, QuadVertexRect()));
2626}
2627
2628const GLRenderer::TileCheckerboardProgram*
2629GLRenderer::GetTileCheckerboardProgram() {
2630  if (!tile_checkerboard_program_.initialized()) {
2631    TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2632    tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
2633                                          TexCoordPrecisionNA,
2634                                          SamplerTypeNA);
2635  }
2636  return &tile_checkerboard_program_;
2637}
2638
2639const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2640  if (!debug_border_program_.initialized()) {
2641    TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2642    debug_border_program_.Initialize(output_surface_->context_provider(),
2643                                     TexCoordPrecisionNA,
2644                                     SamplerTypeNA);
2645  }
2646  return &debug_border_program_;
2647}
2648
2649const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2650  if (!solid_color_program_.initialized()) {
2651    TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2652    solid_color_program_.Initialize(output_surface_->context_provider(),
2653                                    TexCoordPrecisionNA,
2654                                    SamplerTypeNA);
2655  }
2656  return &solid_color_program_;
2657}
2658
2659const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
2660  if (!solid_color_program_aa_.initialized()) {
2661    TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2662    solid_color_program_aa_.Initialize(output_surface_->context_provider(),
2663                                       TexCoordPrecisionNA,
2664                                       SamplerTypeNA);
2665  }
2666  return &solid_color_program_aa_;
2667}
2668
2669const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
2670    TexCoordPrecision precision) {
2671  DCHECK_GE(precision, 0);
2672  DCHECK_LT(precision, NumTexCoordPrecisions);
2673  RenderPassProgram* program = &render_pass_program_[precision];
2674  if (!program->initialized()) {
2675    TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2676    program->Initialize(
2677        output_surface_->context_provider(), precision, SamplerType2D);
2678  }
2679  return program;
2680}
2681
2682const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
2683    TexCoordPrecision precision) {
2684  DCHECK_GE(precision, 0);
2685  DCHECK_LT(precision, NumTexCoordPrecisions);
2686  RenderPassProgramAA* program = &render_pass_program_aa_[precision];
2687  if (!program->initialized()) {
2688    TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2689    program->Initialize(
2690        output_surface_->context_provider(), precision, SamplerType2D);
2691  }
2692  return program;
2693}
2694
2695const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
2696    TexCoordPrecision precision) {
2697  DCHECK_GE(precision, 0);
2698  DCHECK_LT(precision, NumTexCoordPrecisions);
2699  RenderPassMaskProgram* program = &render_pass_mask_program_[precision];
2700  if (!program->initialized()) {
2701    TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2702    program->Initialize(
2703        output_surface_->context_provider(), precision, SamplerType2D);
2704  }
2705  return program;
2706}
2707
2708const GLRenderer::RenderPassMaskProgramAA*
2709GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision) {
2710  DCHECK_GE(precision, 0);
2711  DCHECK_LT(precision, NumTexCoordPrecisions);
2712  RenderPassMaskProgramAA* program = &render_pass_mask_program_aa_[precision];
2713  if (!program->initialized()) {
2714    TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
2715    program->Initialize(
2716        output_surface_->context_provider(), precision, SamplerType2D);
2717  }
2718  return program;
2719}
2720
2721const GLRenderer::RenderPassColorMatrixProgram*
2722GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision) {
2723  DCHECK_GE(precision, 0);
2724  DCHECK_LT(precision, NumTexCoordPrecisions);
2725  RenderPassColorMatrixProgram* program =
2726      &render_pass_color_matrix_program_[precision];
2727  if (!program->initialized()) {
2728    TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
2729    program->Initialize(
2730        output_surface_->context_provider(), precision, SamplerType2D);
2731  }
2732  return program;
2733}
2734
2735const GLRenderer::RenderPassColorMatrixProgramAA*
2736GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision) {
2737  DCHECK_GE(precision, 0);
2738  DCHECK_LT(precision, NumTexCoordPrecisions);
2739  RenderPassColorMatrixProgramAA* program =
2740      &render_pass_color_matrix_program_aa_[precision];
2741  if (!program->initialized()) {
2742    TRACE_EVENT0("cc",
2743                 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
2744    program->Initialize(
2745        output_surface_->context_provider(), precision, SamplerType2D);
2746  }
2747  return program;
2748}
2749
2750const GLRenderer::RenderPassMaskColorMatrixProgram*
2751GLRenderer::GetRenderPassMaskColorMatrixProgram(TexCoordPrecision precision) {
2752  DCHECK_GE(precision, 0);
2753  DCHECK_LT(precision, NumTexCoordPrecisions);
2754  RenderPassMaskColorMatrixProgram* program =
2755      &render_pass_mask_color_matrix_program_[precision];
2756  if (!program->initialized()) {
2757    TRACE_EVENT0("cc",
2758                 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
2759    program->Initialize(
2760        output_surface_->context_provider(), precision, SamplerType2D);
2761  }
2762  return program;
2763}
2764
2765const GLRenderer::RenderPassMaskColorMatrixProgramAA*
2766GLRenderer::GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision) {
2767  DCHECK_GE(precision, 0);
2768  DCHECK_LT(precision, NumTexCoordPrecisions);
2769  RenderPassMaskColorMatrixProgramAA* program =
2770      &render_pass_mask_color_matrix_program_aa_[precision];
2771  if (!program->initialized()) {
2772    TRACE_EVENT0("cc",
2773                 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
2774    program->Initialize(
2775        output_surface_->context_provider(), precision, SamplerType2D);
2776  }
2777  return program;
2778}
2779
2780const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
2781    TexCoordPrecision precision,
2782    SamplerType sampler) {
2783  DCHECK_GE(precision, 0);
2784  DCHECK_LT(precision, NumTexCoordPrecisions);
2785  DCHECK_GE(sampler, 0);
2786  DCHECK_LT(sampler, NumSamplerTypes);
2787  TileProgram* program = &tile_program_[precision][sampler];
2788  if (!program->initialized()) {
2789    TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
2790    program->Initialize(
2791        output_surface_->context_provider(), precision, sampler);
2792  }
2793  return program;
2794}
2795
2796const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
2797    TexCoordPrecision precision,
2798    SamplerType sampler) {
2799  DCHECK_GE(precision, 0);
2800  DCHECK_LT(precision, NumTexCoordPrecisions);
2801  DCHECK_GE(sampler, 0);
2802  DCHECK_LT(sampler, NumSamplerTypes);
2803  TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
2804  if (!program->initialized()) {
2805    TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
2806    program->Initialize(
2807        output_surface_->context_provider(), precision, sampler);
2808  }
2809  return program;
2810}
2811
2812const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
2813    TexCoordPrecision precision,
2814    SamplerType sampler) {
2815  DCHECK_GE(precision, 0);
2816  DCHECK_LT(precision, NumTexCoordPrecisions);
2817  DCHECK_GE(sampler, 0);
2818  DCHECK_LT(sampler, NumSamplerTypes);
2819  TileProgramAA* program = &tile_program_aa_[precision][sampler];
2820  if (!program->initialized()) {
2821    TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
2822    program->Initialize(
2823        output_surface_->context_provider(), precision, sampler);
2824  }
2825  return program;
2826}
2827
2828const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
2829    TexCoordPrecision precision,
2830    SamplerType sampler) {
2831  DCHECK_GE(precision, 0);
2832  DCHECK_LT(precision, NumTexCoordPrecisions);
2833  DCHECK_GE(sampler, 0);
2834  DCHECK_LT(sampler, NumSamplerTypes);
2835  TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
2836  if (!program->initialized()) {
2837    TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
2838    program->Initialize(
2839        output_surface_->context_provider(), precision, sampler);
2840  }
2841  return program;
2842}
2843
2844const GLRenderer::TileProgramSwizzleOpaque*
2845GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
2846                                        SamplerType sampler) {
2847  DCHECK_GE(precision, 0);
2848  DCHECK_LT(precision, NumTexCoordPrecisions);
2849  DCHECK_GE(sampler, 0);
2850  DCHECK_LT(sampler, NumSamplerTypes);
2851  TileProgramSwizzleOpaque* program =
2852      &tile_program_swizzle_opaque_[precision][sampler];
2853  if (!program->initialized()) {
2854    TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
2855    program->Initialize(
2856        output_surface_->context_provider(), precision, sampler);
2857  }
2858  return program;
2859}
2860
2861const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
2862    TexCoordPrecision precision,
2863    SamplerType sampler) {
2864  DCHECK_GE(precision, 0);
2865  DCHECK_LT(precision, NumTexCoordPrecisions);
2866  DCHECK_GE(sampler, 0);
2867  DCHECK_LT(sampler, NumSamplerTypes);
2868  TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
2869  if (!program->initialized()) {
2870    TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
2871    program->Initialize(
2872        output_surface_->context_provider(), precision, sampler);
2873  }
2874  return program;
2875}
2876
2877const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
2878    TexCoordPrecision precision) {
2879  DCHECK_GE(precision, 0);
2880  DCHECK_LT(precision, NumTexCoordPrecisions);
2881  TextureProgram* program = &texture_program_[precision];
2882  if (!program->initialized()) {
2883    TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
2884    program->Initialize(
2885        output_surface_->context_provider(), precision, SamplerType2D);
2886  }
2887  return program;
2888}
2889
2890const GLRenderer::NonPremultipliedTextureProgram*
2891GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision) {
2892  DCHECK_GE(precision, 0);
2893  DCHECK_LT(precision, NumTexCoordPrecisions);
2894  NonPremultipliedTextureProgram* program =
2895      &nonpremultiplied_texture_program_[precision];
2896  if (!program->initialized()) {
2897    TRACE_EVENT0("cc",
2898                 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
2899    program->Initialize(
2900        output_surface_->context_provider(), precision, SamplerType2D);
2901  }
2902  return program;
2903}
2904
2905const GLRenderer::TextureBackgroundProgram*
2906GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision) {
2907  DCHECK_GE(precision, 0);
2908  DCHECK_LT(precision, NumTexCoordPrecisions);
2909  TextureBackgroundProgram* program = &texture_background_program_[precision];
2910  if (!program->initialized()) {
2911    TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
2912    program->Initialize(
2913        output_surface_->context_provider(), precision, SamplerType2D);
2914  }
2915  return program;
2916}
2917
2918const GLRenderer::NonPremultipliedTextureBackgroundProgram*
2919GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
2920    TexCoordPrecision precision) {
2921  DCHECK_GE(precision, 0);
2922  DCHECK_LT(precision, NumTexCoordPrecisions);
2923  NonPremultipliedTextureBackgroundProgram* program =
2924      &nonpremultiplied_texture_background_program_[precision];
2925  if (!program->initialized()) {
2926    TRACE_EVENT0("cc",
2927                 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
2928    program->Initialize(
2929        output_surface_->context_provider(), precision, SamplerType2D);
2930  }
2931  return program;
2932}
2933
2934const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
2935    TexCoordPrecision precision) {
2936  DCHECK_GE(precision, 0);
2937  DCHECK_LT(precision, NumTexCoordPrecisions);
2938  TextureProgram* program = &texture_io_surface_program_[precision];
2939  if (!program->initialized()) {
2940    TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
2941    program->Initialize(
2942        output_surface_->context_provider(), precision, SamplerType2DRect);
2943  }
2944  return program;
2945}
2946
2947const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
2948    TexCoordPrecision precision) {
2949  DCHECK_GE(precision, 0);
2950  DCHECK_LT(precision, NumTexCoordPrecisions);
2951  VideoYUVProgram* program = &video_yuv_program_[precision];
2952  if (!program->initialized()) {
2953    TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
2954    program->Initialize(
2955        output_surface_->context_provider(), precision, SamplerType2D);
2956  }
2957  return program;
2958}
2959
2960const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
2961    TexCoordPrecision precision) {
2962  DCHECK_GE(precision, 0);
2963  DCHECK_LT(precision, NumTexCoordPrecisions);
2964  VideoYUVAProgram* program = &video_yuva_program_[precision];
2965  if (!program->initialized()) {
2966    TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
2967    program->Initialize(
2968        output_surface_->context_provider(), precision, SamplerType2D);
2969  }
2970  return program;
2971}
2972
2973const GLRenderer::VideoStreamTextureProgram*
2974GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
2975  if (!Capabilities().using_egl_image)
2976    return NULL;
2977  DCHECK_GE(precision, 0);
2978  DCHECK_LT(precision, NumTexCoordPrecisions);
2979  VideoStreamTextureProgram* program =
2980      &video_stream_texture_program_[precision];
2981  if (!program->initialized()) {
2982    TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
2983    program->Initialize(
2984        output_surface_->context_provider(), precision, SamplerTypeExternalOES);
2985  }
2986  return program;
2987}
2988
2989void GLRenderer::CleanupSharedObjects() {
2990  shared_geometry_.reset();
2991
2992  for (int i = 0; i < NumTexCoordPrecisions; ++i) {
2993    for (int j = 0; j < NumSamplerTypes; ++j) {
2994      tile_program_[i][j].Cleanup(gl_);
2995      tile_program_opaque_[i][j].Cleanup(gl_);
2996      tile_program_swizzle_[i][j].Cleanup(gl_);
2997      tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
2998      tile_program_aa_[i][j].Cleanup(gl_);
2999      tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3000    }
3001
3002    render_pass_mask_program_[i].Cleanup(gl_);
3003    render_pass_program_[i].Cleanup(gl_);
3004    render_pass_mask_program_aa_[i].Cleanup(gl_);
3005    render_pass_program_aa_[i].Cleanup(gl_);
3006    render_pass_color_matrix_program_[i].Cleanup(gl_);
3007    render_pass_mask_color_matrix_program_aa_[i].Cleanup(gl_);
3008    render_pass_color_matrix_program_aa_[i].Cleanup(gl_);
3009    render_pass_mask_color_matrix_program_[i].Cleanup(gl_);
3010
3011    texture_program_[i].Cleanup(gl_);
3012    nonpremultiplied_texture_program_[i].Cleanup(gl_);
3013    texture_background_program_[i].Cleanup(gl_);
3014    nonpremultiplied_texture_background_program_[i].Cleanup(gl_);
3015    texture_io_surface_program_[i].Cleanup(gl_);
3016
3017    video_yuv_program_[i].Cleanup(gl_);
3018    video_yuva_program_[i].Cleanup(gl_);
3019    video_stream_texture_program_[i].Cleanup(gl_);
3020  }
3021
3022  tile_checkerboard_program_.Cleanup(gl_);
3023
3024  debug_border_program_.Cleanup(gl_);
3025  solid_color_program_.Cleanup(gl_);
3026  solid_color_program_aa_.Cleanup(gl_);
3027
3028  if (offscreen_framebuffer_id_)
3029    GLC(gl_, gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_));
3030
3031  if (on_demand_tile_raster_resource_id_)
3032    resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3033
3034  ReleaseRenderPassTextures();
3035}
3036
3037void GLRenderer::ReinitializeGLState() {
3038  // Bind the common vertex attributes used for drawing all the layers.
3039  shared_geometry_->PrepareForDraw();
3040
3041  GLC(gl_, gl_->Disable(GL_DEPTH_TEST));
3042  GLC(gl_, gl_->Disable(GL_CULL_FACE));
3043  GLC(gl_, gl_->ColorMask(true, true, true, true));
3044  GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
3045  stencil_shadow_ = false;
3046  GLC(gl_, gl_->Enable(GL_BLEND));
3047  blend_shadow_ = true;
3048  GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
3049  GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
3050  program_shadow_ = 0;
3051
3052  // Make sure scissoring starts as disabled.
3053  is_scissor_enabled_ = false;
3054  GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
3055  scissor_rect_needs_reset_ = true;
3056}
3057
3058bool GLRenderer::IsContextLost() {
3059  return output_surface_->context_provider()->IsContextLost();
3060}
3061
3062void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3063  if (!frame->overlay_list.size())
3064    return;
3065
3066  ResourceProvider::ResourceIdArray resources;
3067  OverlayCandidateList& overlays = frame->overlay_list;
3068  OverlayCandidateList::iterator it;
3069  for (it = overlays.begin(); it != overlays.end(); ++it) {
3070    const OverlayCandidate& overlay = *it;
3071    // Skip primary plane.
3072    if (overlay.plane_z_order == 0)
3073      continue;
3074
3075    pending_overlay_resources_.push_back(
3076        make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3077            resource_provider(), overlay.resource_id)));
3078
3079    context_support_->ScheduleOverlayPlane(
3080        overlay.plane_z_order,
3081        overlay.transform,
3082        pending_overlay_resources_.back()->texture_id(),
3083        overlay.display_rect,
3084        overlay.uv_rect);
3085  }
3086}
3087
3088}  // namespace cc
3089