8dacd43abe3790835cf504d2f192462bef600bc5
[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/compositor/io_surface_context_mac.h"
17 #include "content/browser/compositor/io_surface_texture_mac.h"
18 #include "content/browser/renderer_host/render_widget_host_impl.h"
19 #include "content/browser/renderer_host/render_widget_host_view_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 - (id)initWithClient:(content::IOSurfaceLayerClient*)client
173      withScaleFactor:(float)scale_factor {
174   if (self = [super init]) {
175     helper_.reset(new content::IOSurfaceLayerHelper(client, self));
176
177     iosurface_ = content::IOSurfaceTexture::Create();
178     context_ = content::IOSurfaceContext::Get(
179         content::IOSurfaceContext::kCALayerContext);
180     if (!iosurface_.get() || !context_.get()) {
181       LOG(ERROR) << "Failed create CompositingIOSurface or context";
182       [self resetClient];
183       [self release];
184       return nil;
185     }
186
187     [self setBackgroundColor:CGColorGetConstantColor(kCGColorWhite)];
188     [self setAnchorPoint:CGPointMake(0, 0)];
189     // Setting contents gravity is necessary to prevent the layer from being
190     // scaled during dyanmic resizes (especially with devtools open).
191     [self setContentsGravity:kCAGravityTopLeft];
192     if ([self respondsToSelector:(@selector(setContentsScale:))]) {
193       [self setContentsScale:scale_factor];
194     }
195   }
196   return self;
197 }
198
199 - (void)dealloc {
200   DCHECK(!helper_);
201   [super dealloc];
202 }
203
204 - (bool)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id
205                 withPixelSize:(gfx::Size)pixel_size
206               withScaleFactor:(float)scale_factor {
207   return iosurface_->SetIOSurface(io_surface_id, pixel_size);
208 }
209
210 - (void)poisonContextAndSharegroup {
211   context_->PoisonContextAndSharegroup();
212 }
213
214 - (bool)hasBeenPoisoned {
215   return context_->HasBeenPoisoned();
216 }
217
218 - (float)scaleFactor {
219   if ([self respondsToSelector:(@selector(contentsScale))])
220     return [self contentsScale];
221   return 1;
222 }
223
224 - (int)rendererID {
225   GLint current_renderer_id = -1;
226   if (CGLGetParameter(context_->cgl_context(),
227                       kCGLCPCurrentRendererID,
228                       &current_renderer_id) == kCGLNoError) {
229     return current_renderer_id & kCGLRendererIDMatchingMask;
230   }
231   return -1;
232 }
233
234 - (void)resetClient {
235   helper_.reset();
236 }
237
238 - (void)gotNewFrame {
239   helper_->GotNewFrame();
240 }
241
242 - (void)setNeedsDisplayAndDisplayAndAck {
243   helper_->SetNeedsDisplayAndDisplayAndAck();
244 }
245
246 - (void)displayIfNeededAndAck {
247   helper_->DisplayIfNeededAndAck();
248 }
249
250 - (void)beginPumpingFrames {
251   helper_->BeginPumpingFrames();
252 }
253
254 - (void)endPumpingFrames {
255   helper_->EndPumpingFrames();
256 }
257
258 // The remaining methods implement the CAOpenGLLayer interface.
259
260 - (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
261   if (!context_.get())
262     return [super copyCGLPixelFormatForDisplayMask:mask];
263   return CGLRetainPixelFormat(CGLGetPixelFormat(context_->cgl_context()));
264 }
265
266 - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat {
267   if (!context_.get())
268     return [super copyCGLContextForPixelFormat:pixelFormat];
269   return CGLRetainContext(context_->cgl_context());
270 }
271
272 - (void)setNeedsDisplay {
273   if (helper_)
274     helper_->SetNeedsDisplay();
275   [super setNeedsDisplay];
276 }
277
278 - (BOOL)canDrawInCGLContext:(CGLContextObj)glContext
279                 pixelFormat:(CGLPixelFormatObj)pixelFormat
280                forLayerTime:(CFTimeInterval)timeInterval
281                 displayTime:(const CVTimeStamp*)timeStamp {
282   if (helper_)
283     return helper_->CanDraw();
284   return NO;
285 }
286
287 - (void)drawInCGLContext:(CGLContextObj)glContext
288              pixelFormat:(CGLPixelFormatObj)pixelFormat
289             forLayerTime:(CFTimeInterval)timeInterval
290              displayTime:(const CVTimeStamp*)timeStamp {
291   TRACE_EVENT0("browser", "IOSurfaceLayer::drawInCGLContext");
292
293   bool draw_succeeded = iosurface_->DrawIOSurface();
294   if (helper_)
295     helper_->DidDraw(draw_succeeded);
296
297   [super drawInCGLContext:glContext
298               pixelFormat:pixelFormat
299              forLayerTime:timeInterval
300               displayTime:timeStamp];
301 }
302
303 @end