1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/compositor/io_surface_layer_mac.h"
7 #include <CoreFoundation/CoreFoundation.h>
8 #include <OpenGL/CGLIOSurface.h>
9 #include <OpenGL/CGLRenderers.h>
10 #include <OpenGL/gl.h>
11 #include <OpenGL/OpenGL.h>
12 #include <OpenGL/gl.h>
14 #include "base/mac/mac_util.h"
15 #include "base/mac/sdk_forward_declarations.h"
16 #include "content/browser/renderer_host/render_widget_host_impl.h"
17 #include "content/browser/renderer_host/render_widget_host_view_mac.h"
18 #include "content/browser/renderer_host/compositing_iosurface_context_mac.h"
19 #include "content/browser/renderer_host/compositing_iosurface_mac.h"
20 #include "ui/base/cocoa/animation_utils.h"
21 #include "ui/gfx/size_conversions.h"
22 #include "ui/gl/gpu_switching_manager.h"
24 ////////////////////////////////////////////////////////////////////////////////
25 // IOSurfaceLayerHelper
29 IOSurfaceLayerHelper::IOSurfaceLayerHelper(
30 IOSurfaceLayerClient* client,
31 IOSurfaceLayer* layer)
34 needs_display_(false),
35 has_pending_frame_(false),
36 did_not_draw_counter_(0),
37 is_pumping_frames_(false),
40 base::TimeDelta::FromSeconds(1) / 6,
42 &IOSurfaceLayerHelper::TimerFired) {}
44 IOSurfaceLayerHelper::~IOSurfaceLayerHelper() {
45 // Any acks that were waiting on this layer to draw will not occur, so ack
46 // them now to prevent blocking the renderer.
47 AckPendingFrame(true);
50 void IOSurfaceLayerHelper::GotNewFrame() {
51 // A trace value of 2 indicates that there is a pending swap ack. See
52 // canDrawInCGLContext for other value meanings.
53 TRACE_COUNTER_ID1("browser", "PendingSwapAck", this, 2);
55 has_pending_frame_ = true;
56 needs_display_ = true;
59 // If reqested, draw immediately and don't bother trying to use the
60 // isAsynchronous property to ensure smooth animation. If this is while
61 // frames are being pumped then ack and display immediately to get a
62 // correct-sized frame displayed as soon as possible.
63 if (is_pumping_frames_ || client_->IOSurfaceLayerShouldAckImmediately()) {
64 SetNeedsDisplayAndDisplayAndAck();
66 if (![layer_ isAsynchronous])
67 [layer_ setAsynchronous:YES];
71 void IOSurfaceLayerHelper::SetNeedsDisplay() {
72 needs_display_ = true;
75 bool IOSurfaceLayerHelper::CanDraw() {
76 // If we return NO 30 times in a row, switch to being synchronous to avoid
77 // burning CPU cycles on this callback.
79 did_not_draw_counter_ = 0;
81 did_not_draw_counter_ += 1;
82 if (did_not_draw_counter_ == 30)
83 [layer_ setAsynchronous:NO];
86 // Add an instantaneous blip to the PendingSwapAck state to indicate
87 // that CoreAnimation asked if a frame is ready. A blip up to to 3 (usually
88 // from 2, indicating that a swap ack is pending) indicates that we
89 // requested a draw. A blip up to 1 (usually from 0, indicating there is no
90 // pending swap ack) indicates that we did not request a draw. This would
91 // be more natural to do with a tracing pseudo-thread
92 // http://crbug.com/366300
93 TRACE_COUNTER_ID1("browser", "PendingSwapAck", this, needs_display_ ? 3 : 1);
94 TRACE_COUNTER_ID1("browser", "PendingSwapAck", this,
95 has_pending_frame_ ? 2 : 0);
97 return needs_display_;
100 void IOSurfaceLayerHelper::DidDraw(bool success) {
101 needs_display_ = false;
102 AckPendingFrame(success);
105 void IOSurfaceLayerHelper::AckPendingFrame(bool success) {
106 if (!has_pending_frame_)
108 has_pending_frame_ = false;
110 client_->IOSurfaceLayerDidDrawFrame();
112 client_->IOSurfaceLayerHitError();
113 // A trace value of 0 indicates that there is no longer a pending swap ack.
114 TRACE_COUNTER_ID1("browser", "PendingSwapAck", this, 0);
117 void IOSurfaceLayerHelper::SetNeedsDisplayAndDisplayAndAck() {
118 // Drawing using setNeedsDisplay and displayIfNeeded will result in
119 // subsequent canDrawInCGLContext callbacks getting dropped, and jerky
120 // animation. Disable asynchronous drawing before issuing these calls as a
122 // http://crbug.com/395827
123 if ([layer_ isAsynchronous])
124 [layer_ setAsynchronous:NO];
126 [layer_ setNeedsDisplay];
127 DisplayIfNeededAndAck();
130 void IOSurfaceLayerHelper::DisplayIfNeededAndAck() {
134 // As in SetNeedsDisplayAndDisplayAndAck, disable asynchronous drawing before
135 // issuing displayIfNeeded.
136 // http://crbug.com/395827
137 if ([layer_ isAsynchronous])
138 [layer_ setAsynchronous:NO];
140 // Do not bother drawing while pumping new frames -- wait until the waiting
141 // block ends to draw any of the new frames.
142 if (!is_pumping_frames_)
143 [layer_ displayIfNeeded];
145 // Calls to setNeedsDisplay can sometimes be ignored, especially if issued
146 // rapidly (e.g, with vsync off). This is unacceptable because the failure
147 // to ack a single frame will hang the renderer. Ensure that the renderer
148 // not be blocked by lying and claiming that we drew the frame.
149 AckPendingFrame(true);
152 void IOSurfaceLayerHelper::TimerFired() {
153 DisplayIfNeededAndAck();
156 void IOSurfaceLayerHelper::BeginPumpingFrames() {
157 is_pumping_frames_ = true;
160 void IOSurfaceLayerHelper::EndPumpingFrames() {
161 is_pumping_frames_ = false;
162 DisplayIfNeededAndAck();
165 } // namespace content
167 ////////////////////////////////////////////////////////////////////////////////
170 @implementation IOSurfaceLayer
172 - (content::CompositingIOSurfaceMac*)iosurface {
173 return iosurface_.get();
176 - (content::CompositingIOSurfaceContext*)context {
177 return context_.get();
180 - (id)initWithClient:(content::IOSurfaceLayerClient*)client
181 withScaleFactor:(float)scale_factor {
182 if (self = [super init]) {
183 helper_.reset(new content::IOSurfaceLayerHelper(client, self));
185 iosurface_ = content::CompositingIOSurfaceMac::Create();
186 context_ = content::CompositingIOSurfaceContext::Get(
187 content::CompositingIOSurfaceContext::kCALayerContextWindowNumber);
188 if (!iosurface_.get() || !context_.get()) {
189 LOG(ERROR) << "Failed create CompositingIOSurface or context";
195 [self setBackgroundColor:CGColorGetConstantColor(kCGColorWhite)];
196 [self setAnchorPoint:CGPointMake(0, 0)];
197 // Setting contents gravity is necessary to prevent the layer from being
198 // scaled during dyanmic resizes (especially with devtools open).
199 [self setContentsGravity:kCAGravityTopLeft];
200 if ([self respondsToSelector:(@selector(setContentsScale:))]) {
201 [self setContentsScale:scale_factor];
212 - (bool)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id
213 withPixelSize:(gfx::Size)pixel_size
214 withScaleFactor:(float)scale_factor {
216 gfx::ScopedCGLSetCurrentContext scoped_set_current_context(
217 context_->cgl_context());
218 result = iosurface_->SetIOSurfaceWithContextCurrent(
219 context_, io_surface_id, pixel_size, scale_factor);
223 - (void)poisonContextAndSharegroup {
224 context_->PoisonContextAndSharegroup();
227 - (bool)hasBeenPoisoned {
228 return context_->HasBeenPoisoned();
231 - (float)scaleFactor {
232 return iosurface_->scale_factor();
236 return iosurface_->GetRendererID();
239 - (void)resetClient {
243 - (void)gotNewFrame {
244 helper_->GotNewFrame();
247 - (void)setNeedsDisplayAndDisplayAndAck {
248 helper_->SetNeedsDisplayAndDisplayAndAck();
251 - (void)displayIfNeededAndAck {
252 helper_->DisplayIfNeededAndAck();
255 - (void)beginPumpingFrames {
256 helper_->BeginPumpingFrames();
259 - (void)endPumpingFrames {
260 helper_->EndPumpingFrames();
263 // The remaining methods implement the CAOpenGLLayer interface.
265 - (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
267 return [super copyCGLPixelFormatForDisplayMask:mask];
268 return CGLRetainPixelFormat(CGLGetPixelFormat(context_->cgl_context()));
271 - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat {
273 return [super copyCGLContextForPixelFormat:pixelFormat];
274 return CGLRetainContext(context_->cgl_context());
277 - (void)setNeedsDisplay {
279 helper_->SetNeedsDisplay();
280 [super setNeedsDisplay];
283 - (BOOL)canDrawInCGLContext:(CGLContextObj)glContext
284 pixelFormat:(CGLPixelFormatObj)pixelFormat
285 forLayerTime:(CFTimeInterval)timeInterval
286 displayTime:(const CVTimeStamp*)timeStamp {
288 return helper_->CanDraw();
292 - (void)drawInCGLContext:(CGLContextObj)glContext
293 pixelFormat:(CGLPixelFormatObj)pixelFormat
294 forLayerTime:(CFTimeInterval)timeInterval
295 displayTime:(const CVTimeStamp*)timeStamp {
296 TRACE_EVENT0("browser", "IOSurfaceLayer::drawInCGLContext");
298 if (!iosurface_->HasIOSurface() || context_->cgl_context() != glContext) {
299 glClearColor(1, 1, 1, 1);
300 glClear(GL_COLOR_BUFFER_BIT);
304 // The correct viewport to cover the layer will be set up by the caller.
305 // Transform this into a window size for DrawIOSurface, where it will be
306 // transformed back into this viewport.
308 glGetIntegerv(GL_VIEWPORT, viewport);
309 gfx::Rect window_rect(viewport[0], viewport[1], viewport[2], viewport[3]);
310 float window_scale_factor = 1.f;
311 if ([self respondsToSelector:(@selector(contentsScale))])
312 window_scale_factor = [self contentsScale];
313 window_rect = ToNearestRect(
314 gfx::ScaleRect(window_rect, 1.f/window_scale_factor));
316 bool draw_succeeded = iosurface_->DrawIOSurface(
317 context_, window_rect, window_scale_factor);
320 helper_->DidDraw(draw_succeeded);
322 [super drawInCGLContext:glContext
323 pixelFormat:pixelFormat
324 forLayerTime:timeInterval
325 displayTime:timeStamp];