Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / content / browser / compositor / io_surface_layer_mac.mm
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.
4
5 #include "content/browser/compositor/io_surface_layer_mac.h"
6
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>
13
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"
23
24 ////////////////////////////////////////////////////////////////////////////////
25 // IOSurfaceLayerHelper
26
27 namespace content {
28
29 IOSurfaceLayerHelper::IOSurfaceLayerHelper(
30     IOSurfaceLayerClient* client,
31     IOSurfaceLayer* layer)
32         : client_(client),
33           layer_(layer),
34           needs_display_(false),
35           has_pending_frame_(false),
36           did_not_draw_counter_(0),
37           is_pumping_frames_(false),
38           timer_(
39               FROM_HERE,
40               base::TimeDelta::FromSeconds(1) / 6,
41               this,
42               &IOSurfaceLayerHelper::TimerFired) {}
43
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);
48 }
49
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);
54
55   has_pending_frame_ = true;
56   needs_display_ = true;
57   timer_.Reset();
58
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();
65   } else {
66     if (![layer_ isAsynchronous])
67       [layer_ setAsynchronous:YES];
68   }
69 }
70
71 void IOSurfaceLayerHelper::SetNeedsDisplay() {
72   needs_display_ = true;
73 }
74
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.
78   if (needs_display_) {
79     did_not_draw_counter_ = 0;
80   } else {
81     did_not_draw_counter_ += 1;
82     if (did_not_draw_counter_ == 30)
83       [layer_ setAsynchronous:NO];
84   }
85
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);
96
97   return needs_display_;
98 }
99
100 void IOSurfaceLayerHelper::DidDraw(bool success) {
101   needs_display_ = false;
102   AckPendingFrame(success);
103 }
104
105 void IOSurfaceLayerHelper::AckPendingFrame(bool success) {
106   if (!has_pending_frame_)
107     return;
108   has_pending_frame_ = false;
109   if (success)
110     client_->IOSurfaceLayerDidDrawFrame();
111   else
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);
115 }
116
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
121   // workaround.
122   // http://crbug.com/395827
123   if ([layer_ isAsynchronous])
124     [layer_ setAsynchronous:NO];
125
126   [layer_ setNeedsDisplay];
127   DisplayIfNeededAndAck();
128 }
129
130 void IOSurfaceLayerHelper::DisplayIfNeededAndAck() {
131   if (!needs_display_)
132     return;
133
134   // As in SetNeedsDisplayAndDisplayAndAck, disable asynchronous drawing before
135   // issuing displayIfNeeded.
136   // http://crbug.com/395827
137   if ([layer_ isAsynchronous])
138     [layer_ setAsynchronous:NO];
139
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];
144
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);
150 }
151
152 void IOSurfaceLayerHelper::TimerFired() {
153   DisplayIfNeededAndAck();
154 }
155
156 void IOSurfaceLayerHelper::BeginPumpingFrames() {
157   is_pumping_frames_ = true;
158 }
159
160 void IOSurfaceLayerHelper::EndPumpingFrames() {
161   is_pumping_frames_ = false;
162   DisplayIfNeededAndAck();
163 }
164
165 }  // namespace content
166
167 ////////////////////////////////////////////////////////////////////////////////
168 // IOSurfaceLayer
169
170 @implementation IOSurfaceLayer
171
172 - (content::CompositingIOSurfaceMac*)iosurface {
173   return iosurface_.get();
174 }
175
176 - (content::CompositingIOSurfaceContext*)context {
177   return context_.get();
178 }
179
180 - (id)initWithClient:(content::IOSurfaceLayerClient*)client
181      withScaleFactor:(float)scale_factor {
182   if (self = [super init]) {
183     helper_.reset(new content::IOSurfaceLayerHelper(client, self));
184
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";
190       [self resetClient];
191       [self release];
192       return nil;
193     }
194
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];
202     }
203   }
204   return self;
205 }
206
207 - (void)dealloc {
208   DCHECK(!helper_);
209   [super dealloc];
210 }
211
212 - (bool)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id
213                 withPixelSize:(gfx::Size)pixel_size
214               withScaleFactor:(float)scale_factor {
215   bool result = true;
216   gfx::ScopedCGLSetCurrentContext scoped_set_current_context(
217       context_->cgl_context());
218   result = iosurface_->SetIOSurfaceWithContextCurrent(
219       context_, io_surface_id, pixel_size, scale_factor);
220   return result;
221 }
222
223 - (void)poisonContextAndSharegroup {
224   context_->PoisonContextAndSharegroup();
225 }
226
227 - (bool)hasBeenPoisoned {
228   return context_->HasBeenPoisoned();
229 }
230
231 - (float)scaleFactor {
232   return iosurface_->scale_factor();
233 }
234
235 - (int)rendererID {
236   return iosurface_->GetRendererID();
237 }
238
239 - (void)resetClient {
240   helper_.reset();
241 }
242
243 - (void)gotNewFrame {
244   helper_->GotNewFrame();
245 }
246
247 - (void)setNeedsDisplayAndDisplayAndAck {
248   helper_->SetNeedsDisplayAndDisplayAndAck();
249 }
250
251 - (void)displayIfNeededAndAck {
252   helper_->DisplayIfNeededAndAck();
253 }
254
255 - (void)beginPumpingFrames {
256   helper_->BeginPumpingFrames();
257 }
258
259 - (void)endPumpingFrames {
260   helper_->EndPumpingFrames();
261 }
262
263 // The remaining methods implement the CAOpenGLLayer interface.
264
265 - (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
266   if (!context_.get())
267     return [super copyCGLPixelFormatForDisplayMask:mask];
268   return CGLRetainPixelFormat(CGLGetPixelFormat(context_->cgl_context()));
269 }
270
271 - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat {
272   if (!context_.get())
273     return [super copyCGLContextForPixelFormat:pixelFormat];
274   return CGLRetainContext(context_->cgl_context());
275 }
276
277 - (void)setNeedsDisplay {
278   if (helper_)
279     helper_->SetNeedsDisplay();
280   [super setNeedsDisplay];
281 }
282
283 - (BOOL)canDrawInCGLContext:(CGLContextObj)glContext
284                 pixelFormat:(CGLPixelFormatObj)pixelFormat
285                forLayerTime:(CFTimeInterval)timeInterval
286                 displayTime:(const CVTimeStamp*)timeStamp {
287   if (helper_)
288     return helper_->CanDraw();
289   return NO;
290 }
291
292 - (void)drawInCGLContext:(CGLContextObj)glContext
293              pixelFormat:(CGLPixelFormatObj)pixelFormat
294             forLayerTime:(CFTimeInterval)timeInterval
295              displayTime:(const CVTimeStamp*)timeStamp {
296   TRACE_EVENT0("browser", "IOSurfaceLayer::drawInCGLContext");
297
298   if (!iosurface_->HasIOSurface() || context_->cgl_context() != glContext) {
299     glClearColor(1, 1, 1, 1);
300     glClear(GL_COLOR_BUFFER_BIT);
301     return;
302   }
303
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.
307   GLint viewport[4];
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));
315
316   bool draw_succeeded = iosurface_->DrawIOSurface(
317       context_, window_rect, window_scale_factor);
318
319   if (helper_)
320     helper_->DidDraw(draw_succeeded);
321
322   [super drawInCGLContext:glContext
323               pixelFormat:pixelFormat
324              forLayerTime:timeInterval
325               displayTime:timeStamp];
326 }
327
328 @end