Commit 8af59efe authored by kbr's avatar kbr Committed by Commit bot

Revert IOSurface CoreAnimation simplifications on ccameron@'s advice.

Contains:

Revert "Workaround to prevent crashes when destroying CGL contexts"
This reverts commit 282049cc.

Revert "Log erros while presenting an IOSurface to about:gpu"
This reverts commit 090e36f0.

Revert "Simplify IOSurface CoreAnimation code: Part 2"
This reverts commit 672e23e9.
Resolved conflicts:
	content/browser/compositor/io_surface_layer_mac.mm

Fixed call ccameron@ pointed out in: https://codereview.chromium.org/490393002/diff/260001/content/browser/compositor/io_surface_layer_mac.mm#oldcode149

Build fixes for recent scoped_refptr changes.

BUG=314190,408986,411782
R=piman@chromium.org
TBR=ccameron@chromium.org,pfeldman@chromium.org

Review URL: https://codereview.chromium.org/596703006

Cr-Commit-Position: refs/heads/master@{#296449}
parent 978d46da
...@@ -208,6 +208,7 @@ void BrowserCompositorViewMacInternal::GotAcceleratedIOSurfaceFrame( ...@@ -208,6 +208,7 @@ void BrowserCompositorViewMacInternal::GotAcceleratedIOSurfaceFrame(
// layer. // layer.
bool needs_new_layer = bool needs_new_layer =
!io_surface_layer_ || !io_surface_layer_ ||
[io_surface_layer_ hasBeenPoisoned] ||
[io_surface_layer_ scaleFactor] != scale_factor; [io_surface_layer_ scaleFactor] != scale_factor;
if (needs_new_layer) { if (needs_new_layer) {
io_surface_layer_.reset( io_surface_layer_.reset(
...@@ -220,12 +221,28 @@ void BrowserCompositorViewMacInternal::GotAcceleratedIOSurfaceFrame( ...@@ -220,12 +221,28 @@ void BrowserCompositorViewMacInternal::GotAcceleratedIOSurfaceFrame(
} }
// Open the provided IOSurface. // Open the provided IOSurface.
[io_surface_layer_ gotFrameWithIOSurface:io_surface_id if (io_surface_layer_) {
withPixelSize:pixel_size bool result = [io_surface_layer_ gotFrameWithIOSurface:io_surface_id
withScaleFactor:scale_factor]; withPixelSize:pixel_size
withScaleFactor:scale_factor];
if (!result) {
DestroyIOSurfaceLayer(io_surface_layer_);
LOG(ERROR) << "Failed open IOSurface in IOSurfaceLayer";
}
}
// Give a final complaint if anything with the layer's creation went wrong.
// This frame will appear blank, the compositor will try to create another,
// and maybe that will go better.
if (!io_surface_layer_) {
LOG(ERROR) << "IOSurfaceLayer is nil, tab will be blank";
IOSurfaceLayerHitError();
}
// Make the CALayer draw and set its size appropriately. // Make the CALayer draw and set its size appropriately.
if (io_surface_layer_) { if (io_surface_layer_) {
[io_surface_layer_ gotNewFrame];
// Set the bounds of the accelerated layer to match the size of the frame. // Set the bounds of the accelerated layer to match the size of the frame.
// If the bounds changed, force the content to be displayed immediately. // If the bounds changed, force the content to be displayed immediately.
CGRect new_layer_bounds = CGRectMake( CGRect new_layer_bounds = CGRectMake(
...@@ -328,8 +345,12 @@ void BrowserCompositorViewMacInternal::IOSurfaceLayerDidDrawFrame() { ...@@ -328,8 +345,12 @@ void BrowserCompositorViewMacInternal::IOSurfaceLayerDidDrawFrame() {
} }
void BrowserCompositorViewMacInternal::IOSurfaceLayerHitError() { void BrowserCompositorViewMacInternal::IOSurfaceLayerHitError() {
// Perform all acks that would have been done if the frame had succeeded, to
// un-block the compositor and renderer.
IOSurfaceLayerDidDrawFrame();
// Poison the context being used and request a mulligan. // Poison the context being used and request a mulligan.
DestroyIOSurfaceLayer(io_surface_layer_); [io_surface_layer_ poisonContextAndSharegroup];
compositor_->ScheduleFullRedraw(); compositor_->ScheduleFullRedraw();
} }
......
...@@ -2,22 +2,21 @@ ...@@ -2,22 +2,21 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifndef CONTENT_BROWSER_COMPOSITOR_IO_SURFACE_LAYER_MAC_H_ #ifndef CONTENT_BROWSER_RENDERER_HOST_COMPOSITING_IOSURFACE_LAYER_MAC_H_
#define CONTENT_BROWSER_COMPOSITOR_IO_SURFACE_LAYER_MAC_H_ #define CONTENT_BROWSER_RENDERER_HOST_COMPOSITING_IOSURFACE_LAYER_MAC_H_
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include <IOSurface/IOSurfaceAPI.h>
#include "base/mac/scoped_cftyperef.h" #include "base/mac/scoped_cftyperef.h"
#include "base/memory/ref_counted.h" #include "base/memory/ref_counted.h"
#include "base/timer/timer.h" #include "base/timer/timer.h"
#include "ui/gfx/size.h" #include "ui/gfx/size.h"
#include "ui/gl/scoped_cgl.h"
@class IOSurfaceLayer; @class IOSurfaceLayer;
namespace content { namespace content {
class IOSurfaceLayerHelper; class CompositingIOSurfaceMac;
class CompositingIOSurfaceContext;
// The interface through which the IOSurfaceLayer calls back into // The interface through which the IOSurfaceLayer calls back into
// the structrue that created it (RenderWidgetHostViewMac or // the structrue that created it (RenderWidgetHostViewMac or
...@@ -37,13 +36,58 @@ class IOSurfaceLayerClient { ...@@ -37,13 +36,58 @@ class IOSurfaceLayerClient {
virtual void IOSurfaceLayerHitError() = 0; virtual void IOSurfaceLayerHitError() = 0;
}; };
} // namespace content // IOSurfaceLayerHelper provides C++ functionality needed for the
// IOSurfaceLayer class, and does most of the heavy lifting for the
// class.
// TODO(ccameron): This class should own IOSurfaceLayer, rather than
// vice versa.
class IOSurfaceLayerHelper {
public:
IOSurfaceLayerHelper(IOSurfaceLayerClient* client,
IOSurfaceLayer* layer);
~IOSurfaceLayerHelper();
// The CoreAnimation layer for drawing accelerated content. // Called when the IOSurfaceLayer gets a new frame.
@interface IOSurfaceLayer : CAOpenGLLayer { void GotNewFrame();
@private
content::IOSurfaceLayerClient* client_; // Called whenever -[IOSurfaceLayer setNeedsDisplay] is called.
scoped_ptr<content::IOSurfaceLayerHelper> helper_; void SetNeedsDisplay();
// Called whenever -[IOSurfaceLayer canDrawInCGLContext] is called,
// to determine if a new frame should be drawn.
bool CanDraw();
// Called whenever -[IOSurfaceLayer drawInCGLContext] draws a
// frame.
void DidDraw(bool success);
// Immediately re-draw the layer, even if the content has not changed, and
// ensure that the frame be acked.
void SetNeedsDisplayAndDisplayAndAck();
// Immediately draw the layer, only if one is pending, and ensure that the
// frame be acked.
void DisplayIfNeededAndAck();
// Mark a bracket in which new frames are being pumped in a restricted nested
// run loop. During this time frames are acked immediately and draws are
// deferred until the bracket ends.
void BeginPumpingFrames();
void EndPumpingFrames();
private:
// Called whenever the frame provided in GotNewFrame should be acknowledged
// (this may be because it was drawn, or it may be to unblock the
// compositor).
void AckPendingFrame(bool success);
void TimerFired();
// The client that the owning layer was created with.
content::IOSurfaceLayerClient* const client_;
// The layer that owns this helper.
IOSurfaceLayer* const layer_;
// Used to track when canDrawInCGLContext should return YES. This can be // Used to track when canDrawInCGLContext should return YES. This can be
// in response to receiving a new compositor frame, or from any of the events // in response to receiving a new compositor frame, or from any of the events
...@@ -60,32 +104,35 @@ class IOSurfaceLayerClient { ...@@ -60,32 +104,35 @@ class IOSurfaceLayerClient {
// Set when inside a BeginPumpingFrames/EndPumpingFrames block. // Set when inside a BeginPumpingFrames/EndPumpingFrames block.
bool is_pumping_frames_; bool is_pumping_frames_;
// The IOSurface being drawn by this layer. // The browser places back-pressure on the GPU by not acknowledging swap
base::ScopedCFTypeRef<IOSurfaceRef> io_surface_; // calls until they appear on the screen. This can lead to hangs if the
// view is moved offscreen (among other things). Prevent hangs by always
// acknowledging the frame after timeout of 1/6th of a second has passed.
base::DelayTimer<IOSurfaceLayerHelper> timer_;
};
// The size of the frame in pixels. This will be less or equal than the pixel } // namespace content
// size of |io_surface_|.
gfx::Size frame_pixel_size_;
// The GL texture that was bound to |io_surface_| during the last draw call, // The CoreAnimation layer for drawing accelerated content.
// along with the context that was done in, and the value of |io_surface_| at @interface IOSurfaceLayer : CAOpenGLLayer {
// the time of the bind. @private
GLuint io_surface_texture_; scoped_refptr<content::CompositingIOSurfaceMac> iosurface_;
base::ScopedTypeRef<CGLContextObj> io_surface_texture_context_; scoped_refptr<content::CompositingIOSurfaceContext> context_;
base::ScopedCFTypeRef<IOSurfaceRef> io_surface_texture_io_surface_;
// The CGL renderer ID, captured at draw time. scoped_ptr<content::IOSurfaceLayerHelper> helper_;
GLint cgl_renderer_id_;
} }
- (id)initWithClient:(content::IOSurfaceLayerClient*)client - (id)initWithClient:(content::IOSurfaceLayerClient*)client
withScaleFactor:(float)scale_factor; withScaleFactor:(float)scale_factor;
// Called when a new frame is received. - (bool)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id
- (void)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id
withPixelSize:(gfx::Size)pixel_size withPixelSize:(gfx::Size)pixel_size
withScaleFactor:(float)scale_factor; withScaleFactor:(float)scale_factor;
// Context poison accessors.
- (void)poisonContextAndSharegroup;
- (bool)hasBeenPoisoned;
- (float)scaleFactor; - (float)scaleFactor;
// The CGL renderer ID. // The CGL renderer ID.
...@@ -95,14 +142,20 @@ class IOSurfaceLayerClient { ...@@ -95,14 +142,20 @@ class IOSurfaceLayerClient {
// must be called before the layer is destroyed. // must be called before the layer is destroyed.
- (void)resetClient; - (void)resetClient;
// Called when a new frame is received.
- (void)gotNewFrame;
// Force a draw immediately (even if this means re-displaying a previously // Force a draw immediately (even if this means re-displaying a previously
// displayed frame). // displayed frame).
- (void)setNeedsDisplayAndDisplayAndAck; - (void)setNeedsDisplayAndDisplayAndAck;
// Force a draw immediately, but only if one was requested.
- (void)displayIfNeededAndAck;
// Mark a bracket in which new frames are being pumped in a restricted nested // Mark a bracket in which new frames are being pumped in a restricted nested
// run loop. // run loop.
- (void)beginPumpingFrames; - (void)beginPumpingFrames;
- (void)endPumpingFrames; - (void)endPumpingFrames;
@end @end
#endif // CONTENT_BROWSER_COMPOSITOR_IO_SURFACE_LAYER_MAC_H_ #endif // CONTENT_BROWSER_RENDERER_HOST_COMPOSITING_IOSURFACE_LAYER_MAC_H_
...@@ -4,8 +4,6 @@ ...@@ -4,8 +4,6 @@
#include "content/browser/compositor/io_surface_layer_mac.h" #include "content/browser/compositor/io_surface_layer_mac.h"
#include <sstream>
#include <CoreFoundation/CoreFoundation.h> #include <CoreFoundation/CoreFoundation.h>
#include <OpenGL/CGLIOSurface.h> #include <OpenGL/CGLIOSurface.h>
#include <OpenGL/CGLRenderers.h> #include <OpenGL/CGLRenderers.h>
...@@ -14,94 +12,28 @@ ...@@ -14,94 +12,28 @@
#include "base/mac/mac_util.h" #include "base/mac/mac_util.h"
#include "base/mac/sdk_forward_declarations.h" #include "base/mac/sdk_forward_declarations.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_mac.h" #include "content/browser/renderer_host/render_widget_host_view_mac.h"
#include "content/browser/renderer_host/compositing_iosurface_context_mac.h"
#include "content/browser/renderer_host/compositing_iosurface_mac.h"
#include "ui/base/cocoa/animation_utils.h" #include "ui/base/cocoa/animation_utils.h"
#include "ui/gfx/size_conversions.h" #include "ui/gfx/size_conversions.h"
#include "ui/gl/scoped_cgl.h"
#include "ui/gl/gpu_switching_manager.h" #include "ui/gl/gpu_switching_manager.h"
// Convenience macro for checking errors in the below code.
#define CHECK_GL_ERROR() do { \
GLenum gl_error = glGetError(); \
LOG_IF(ERROR, gl_error != GL_NO_ERROR) << "GL Error: " << gl_error; \
} while (0)
namespace {
// Helper function for logging error codes.
template<typename T>
std::string to_string(T value) {
std::ostringstream stream;
stream << value;
return stream.str();
}
// Helper function posted to destroy textures on a clean stack.
void DestroyTexture(
base::ScopedTypeRef<CGLContextObj> context,
base::ScopedCFTypeRef<IOSurfaceRef> io_surface,
GLuint texture) {
// Destroy the texture before tearing down the context, and while the
// IOSurface is still being kept around.
CGLSetCurrentContext(context);
glDeleteTextures(1, &texture);
CGLSetCurrentContext(NULL);
// Release (and likely destroy) the context.
context.reset();
// Finally release the IOSurface.
io_surface.reset();
}
}
////////////////////////////////////////////////////////////////////////////////
// IOSurfaceLayer(Private)
@interface IOSurfaceLayer(Private)
// Reset the texture and post a task to clean it up.
- (void)resetTextureAndPostDestroy;
// Force a draw immediately, but only if one was requested.
- (void)displayIfNeededAndAck;
// Called when it has been a fixed interval of time and a frame has yet to be
// drawn.
- (void)timerFired;
@end
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// IOSurfaceLayerHelper // IOSurfaceLayerHelper
namespace content { namespace content {
// IOSurfaceLayerHelper provides C++ functionality needed for the
// IOSurfaceLayer class (interfacing with base::DelayTimer).
class IOSurfaceLayerHelper {
public:
IOSurfaceLayerHelper(IOSurfaceLayer* layer);
~IOSurfaceLayerHelper();
void ResetTimer();
private:
void TimerFired();
// The layer that owns this helper.
IOSurfaceLayer* const layer_;
// The browser places back-pressure on the GPU by not acknowledging swap
// calls until they appear on the screen. This can lead to hangs if the
// view is moved offscreen (among other things). Prevent hangs by always
// acknowledging the frame after timeout of 1/6th of a second has passed.
base::DelayTimer<IOSurfaceLayerHelper> timer_;
};
IOSurfaceLayerHelper::IOSurfaceLayerHelper( IOSurfaceLayerHelper::IOSurfaceLayerHelper(
IOSurfaceLayerClient* client,
IOSurfaceLayer* layer) IOSurfaceLayer* layer)
: layer_(layer), : client_(client),
layer_(layer),
needs_display_(false),
has_pending_frame_(false),
did_not_draw_counter_(0),
is_pumping_frames_(false),
timer_( timer_(
FROM_HERE, FROM_HERE,
base::TimeDelta::FromSeconds(1) / 6, base::TimeDelta::FromSeconds(1) / 6,
...@@ -109,117 +41,37 @@ IOSurfaceLayerHelper::IOSurfaceLayerHelper( ...@@ -109,117 +41,37 @@ IOSurfaceLayerHelper::IOSurfaceLayerHelper(
&IOSurfaceLayerHelper::TimerFired) {} &IOSurfaceLayerHelper::TimerFired) {}
IOSurfaceLayerHelper::~IOSurfaceLayerHelper() { IOSurfaceLayerHelper::~IOSurfaceLayerHelper() {
}
void IOSurfaceLayerHelper::ResetTimer() {
timer_.Reset();
}
void IOSurfaceLayerHelper::TimerFired() {
[layer_ timerFired];
}
} // namespace content
////////////////////////////////////////////////////////////////////////////////
// IOSurfaceLayer
@implementation IOSurfaceLayer
- (id)initWithClient:(content::IOSurfaceLayerClient*)client
withScaleFactor:(float)scale_factor {
if (self = [super init]) {
client_ = client;
helper_.reset(new content::IOSurfaceLayerHelper(self));
needs_display_ = false;
has_pending_frame_ = false;
did_not_draw_counter_ = 0;
is_pumping_frames_ = false;
io_surface_texture_ = 0;
cgl_renderer_id_ = 0;
[self setBackgroundColor:CGColorGetConstantColor(kCGColorWhite)];
[self setAnchorPoint:CGPointMake(0, 0)];
// Setting contents gravity is necessary to prevent the layer from being
// scaled during dyanmic resizes (especially with devtools open).
[self setContentsGravity:kCAGravityTopLeft];
if ([self respondsToSelector:(@selector(setContentsScale:))])
[self setContentsScale:scale_factor];
}
return self;
}
- (void)dealloc {
DCHECK(!helper_ && !client_);
[super dealloc];
}
- (float)scaleFactor {
if ([self respondsToSelector:(@selector(contentsScale))])
return [self contentsScale];
return 1;
}
- (int)rendererID {
return cgl_renderer_id_;
}
- (void)timerFired {
[self displayIfNeededAndAck];
}
- (void)resetClient {
// Any acks that were waiting on this layer to draw will not occur, so ack // Any acks that were waiting on this layer to draw will not occur, so ack
// them now to prevent blocking the renderer. // them now to prevent blocking the renderer.
[self ackPendingFrame]; AckPendingFrame(true);
helper_.reset();
client_ = NULL;
} }
- (void)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id void IOSurfaceLayerHelper::GotNewFrame() {
withPixelSize:(gfx::Size)pixel_size
withScaleFactor:(float)scale_factor {
// A trace value of 2 indicates that there is a pending swap ack. See // A trace value of 2 indicates that there is a pending swap ack. See
// canDrawInCGLContext for other value meanings. // canDrawInCGLContext for other value meanings.
TRACE_COUNTER_ID1("browser", "PendingSwapAck", self, 2); TRACE_COUNTER_ID1("browser", "PendingSwapAck", this, 2);
has_pending_frame_ = true; has_pending_frame_ = true;
needs_display_ = true; needs_display_ = true;
helper_->ResetTimer(); timer_.Reset();
frame_pixel_size_ = pixel_size;
// If this is a new IOSurface, open the IOSurface and mark that the
// GL texture needs to bind to the new surface.
if (!io_surface_ || io_surface_id != IOSurfaceGetID(io_surface_)) {
io_surface_.reset(IOSurfaceLookup(io_surface_id));
if (!io_surface_) {
[self resetTextureAndPostDestroy];
content::GpuDataManagerImpl::GetInstance()->AddLogMessage(
logging::LOG_ERROR,
"IOSurfaceLayer",
"Failed to open IOSurface in gotFrameWithIOSurface");
if (client_)
client_->IOSurfaceLayerHitError();
}
}
// If reqested, draw immediately and don't bother trying to use the // If reqested, draw immediately and don't bother trying to use the
// isAsynchronous property to ensure smooth animation. If this is while // isAsynchronous property to ensure smooth animation. If this is while
// frames are being pumped then ack and display immediately to get a // frames are being pumped then ack and display immediately to get a
// correct-sized frame displayed as soon as possible. // correct-sized frame displayed as soon as possible.
if (is_pumping_frames_ || if (is_pumping_frames_ || client_->IOSurfaceLayerShouldAckImmediately()) {
(client_ && client_->IOSurfaceLayerShouldAckImmediately())) { SetNeedsDisplayAndDisplayAndAck();
[self setNeedsDisplayAndDisplayAndAck];
} else { } else {
if (![self isAsynchronous]) if (![layer_ isAsynchronous])
[self setAsynchronous:YES]; [layer_ setAsynchronous:YES];
} }
} }
- (BOOL)canDrawInCGLContext:(CGLContextObj)glContext void IOSurfaceLayerHelper::SetNeedsDisplay() {
pixelFormat:(CGLPixelFormatObj)pixelFormat needs_display_ = true;
forLayerTime:(CFTimeInterval)timeInterval }
displayTime:(const CVTimeStamp*)timeStamp {
bool IOSurfaceLayerHelper::CanDraw() {
// If we return NO 30 times in a row, switch to being synchronous to avoid // If we return NO 30 times in a row, switch to being synchronous to avoid
// burning CPU cycles on this callback. // burning CPU cycles on this callback.
if (needs_display_) { if (needs_display_) {
...@@ -227,7 +79,7 @@ void IOSurfaceLayerHelper::TimerFired() { ...@@ -227,7 +79,7 @@ void IOSurfaceLayerHelper::TimerFired() {
} else { } else {
did_not_draw_counter_ += 1; did_not_draw_counter_ += 1;
if (did_not_draw_counter_ == 30) if (did_not_draw_counter_ == 30)
[self setAsynchronous:NO]; [layer_ setAsynchronous:NO];
} }
// Add an instantaneous blip to the PendingSwapAck state to indicate // Add an instantaneous blip to the PendingSwapAck state to indicate
...@@ -237,264 +89,239 @@ void IOSurfaceLayerHelper::TimerFired() { ...@@ -237,264 +89,239 @@ void IOSurfaceLayerHelper::TimerFired() {
// pending swap ack) indicates that we did not request a draw. This would // pending swap ack) indicates that we did not request a draw. This would
// be more natural to do with a tracing pseudo-thread // be more natural to do with a tracing pseudo-thread
// http://crbug.com/366300 // http://crbug.com/366300
TRACE_COUNTER_ID1("browser", "PendingSwapAck", self, needs_display_ ? 3 : 1); TRACE_COUNTER_ID1("browser", "PendingSwapAck", this, needs_display_ ? 3 : 1);
TRACE_COUNTER_ID1("browser", "PendingSwapAck", self, TRACE_COUNTER_ID1("browser", "PendingSwapAck", this,
has_pending_frame_ ? 2 : 0); has_pending_frame_ ? 2 : 0);
return needs_display_; return needs_display_;
} }
- (void)ackPendingFrame { void IOSurfaceLayerHelper::DidDraw(bool success) {
needs_display_ = false;
AckPendingFrame(success);
}
void IOSurfaceLayerHelper::AckPendingFrame(bool success) {
if (!has_pending_frame_) if (!has_pending_frame_)
return; return;
has_pending_frame_ = false; has_pending_frame_ = false;
if (client_) if (success)
client_->IOSurfaceLayerDidDrawFrame(); client_->IOSurfaceLayerDidDrawFrame();
else
client_->IOSurfaceLayerHitError();
// A trace value of 0 indicates that there is no longer a pending swap ack. // A trace value of 0 indicates that there is no longer a pending swap ack.
TRACE_COUNTER_ID1("browser", "PendingSwapAck", self, 0); TRACE_COUNTER_ID1("browser", "PendingSwapAck", this, 0);
} }
- (void)setNeedsDisplayAndDisplayAndAck { void IOSurfaceLayerHelper::SetNeedsDisplayAndDisplayAndAck() {
// Drawing using setNeedsDisplay and displayIfNeeded will result in // Drawing using setNeedsDisplay and displayIfNeeded will result in
// subsequent canDrawInCGLContext callbacks getting dropped, and jerky // subsequent canDrawInCGLContext callbacks getting dropped, and jerky
// animation. Disable asynchronous drawing before issuing these calls as a // animation. Disable asynchronous drawing before issuing these calls as a
// workaround. // workaround.
// http://crbug.com/395827 // http://crbug.com/395827
if ([self isAsynchronous]) if ([layer_ isAsynchronous])
[self setAsynchronous:NO]; [layer_ setAsynchronous:NO];
[self setNeedsDisplay]; [layer_ setNeedsDisplay];
[self displayIfNeededAndAck]; DisplayIfNeededAndAck();
} }
- (void)displayIfNeededAndAck { void IOSurfaceLayerHelper::DisplayIfNeededAndAck() {
if (!needs_display_) if (!needs_display_)
return; return;
// As in SetNeedsDisplayAndDisplayAndAck, disable asynchronous drawing before // As in SetNeedsDisplayAndDisplayAndAck, disable asynchronous drawing before
// issuing displayIfNeeded. // issuing displayIfNeeded.
// http://crbug.com/395827 // http://crbug.com/395827
if ([self isAsynchronous]) if ([layer_ isAsynchronous])
[self setAsynchronous:NO]; [layer_ setAsynchronous:NO];
// Do not bother drawing while pumping new frames -- wait until the waiting // Do not bother drawing while pumping new frames -- wait until the waiting
// block ends to draw any of the new frames. // block ends to draw any of the new frames.
if (!is_pumping_frames_) if (!is_pumping_frames_)
[self displayIfNeeded]; [layer_ displayIfNeeded];
// Calls to setNeedsDisplay can sometimes be ignored, especially if issued // Calls to setNeedsDisplay can sometimes be ignored, especially if issued
// rapidly (e.g, with vsync off). This is unacceptable because the failure // rapidly (e.g, with vsync off). This is unacceptable because the failure
// to ack a single frame will hang the renderer. Ensure that the renderer // to ack a single frame will hang the renderer. Ensure that the renderer
// not be blocked by lying and claiming that we drew the frame. // not be blocked by lying and claiming that we drew the frame.
[self ackPendingFrame]; AckPendingFrame(true);
} }
- (void)beginPumpingFrames { void IOSurfaceLayerHelper::TimerFired() {
DisplayIfNeededAndAck();
}
void IOSurfaceLayerHelper::BeginPumpingFrames() {
is_pumping_frames_ = true; is_pumping_frames_ = true;
} }
- (void)endPumpingFrames { void IOSurfaceLayerHelper::EndPumpingFrames() {
is_pumping_frames_ = false; is_pumping_frames_ = false;
[self displayIfNeededAndAck]; DisplayIfNeededAndAck();
}
} // namespace content
////////////////////////////////////////////////////////////////////////////////
// IOSurfaceLayer
@implementation IOSurfaceLayer
- (content::CompositingIOSurfaceMac*)iosurface {
return iosurface_.get();
}
- (content::CompositingIOSurfaceContext*)context {
return context_.get();
}
- (id)initWithClient:(content::IOSurfaceLayerClient*)client
withScaleFactor:(float)scale_factor {
if (self = [super init]) {
helper_.reset(new content::IOSurfaceLayerHelper(client, self));
iosurface_ = content::CompositingIOSurfaceMac::Create();
context_ = content::CompositingIOSurfaceContext::Get(
content::CompositingIOSurfaceContext::kCALayerContextWindowNumber);
if (!iosurface_.get() || !context_.get()) {
LOG(ERROR) << "Failed create CompositingIOSurface or context";
[self resetClient];
[self release];
return nil;
}
[self setBackgroundColor:CGColorGetConstantColor(kCGColorWhite)];
[self setAnchorPoint:CGPointMake(0, 0)];
// Setting contents gravity is necessary to prevent the layer from being
// scaled during dyanmic resizes (especially with devtools open).
[self setContentsGravity:kCAGravityTopLeft];
if ([self respondsToSelector:(@selector(setContentsScale:))]) {
[self setContentsScale:scale_factor];
}
}
return self;
}
- (void)dealloc {
DCHECK(!helper_);
[super dealloc];
}
- (bool)gotFrameWithIOSurface:(IOSurfaceID)io_surface_id
withPixelSize:(gfx::Size)pixel_size
withScaleFactor:(float)scale_factor {
bool result = true;
gfx::ScopedCGLSetCurrentContext scoped_set_current_context(
context_->cgl_context());
result = iosurface_->SetIOSurfaceWithContextCurrent(
context_, io_surface_id, pixel_size, scale_factor);
return result;
}
- (void)poisonContextAndSharegroup {
context_->PoisonContextAndSharegroup();
}
- (bool)hasBeenPoisoned {
return context_->HasBeenPoisoned();
}
- (float)scaleFactor {
return iosurface_->scale_factor();
}
- (int)rendererID {
return iosurface_->GetRendererID();
}
- (void)resetClient {
helper_.reset();
}
- (void)gotNewFrame {
helper_->GotNewFrame();
}
- (void)setNeedsDisplayAndDisplayAndAck {
helper_->SetNeedsDisplayAndDisplayAndAck();
}
- (void)displayIfNeededAndAck {
helper_->DisplayIfNeededAndAck();
}
- (void)beginPumpingFrames {
helper_->BeginPumpingFrames();
}
- (void)endPumpingFrames {
helper_->EndPumpingFrames();
} }
// The remaining methods implement the CAOpenGLLayer interface. // The remaining methods implement the CAOpenGLLayer interface.
- (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask { - (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
// Create the pixel format object for the context. if (!context_.get())
std::vector<CGLPixelFormatAttribute> attribs; return [super copyCGLPixelFormatForDisplayMask:mask];
attribs.push_back(kCGLPFADepthSize); return CGLRetainPixelFormat(CGLGetPixelFormat(context_->cgl_context()));
attribs.push_back(static_cast<CGLPixelFormatAttribute>(0));
if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus()) {
attribs.push_back(kCGLPFAAllowOfflineRenderers);
attribs.push_back(static_cast<CGLPixelFormatAttribute>(1));
}
attribs.push_back(static_cast<CGLPixelFormatAttribute>(0));
GLint number_virtual_screens = 0;
base::ScopedTypeRef<CGLPixelFormatObj> pixel_format;
CGLError cgl_error = CGLChoosePixelFormat(
&attribs.front(), pixel_format.InitializeInto(), &number_virtual_screens);
if (cgl_error != kCGLNoError) {
content::GpuDataManagerImpl::GetInstance()->AddLogMessage(
logging::LOG_ERROR,
"IOSurfaceLayer",
std::string("Failed to create pixel format object with CGL error ") +
to_string(static_cast<int>(cgl_error)));
return NULL;
}
return CGLRetainPixelFormat(pixel_format);
} }
- (void)releaseCGLContext:(CGLContextObj)glContext { - (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat {
// The GL context is being destroyed, so mark the resources as needing to be if (!context_.get())
// recreated. return [super copyCGLContextForPixelFormat:pixelFormat];
[self resetTextureAndPostDestroy]; return CGLRetainContext(context_->cgl_context());
[super releaseCGLContext:glContext];
} }
- (void)setNeedsDisplay { - (void)setNeedsDisplay {
needs_display_ = true; if (helper_)
helper_->SetNeedsDisplay();
[super setNeedsDisplay]; [super setNeedsDisplay];
} }
- (BOOL)canDrawInCGLContext:(CGLContextObj)glContext
pixelFormat:(CGLPixelFormatObj)pixelFormat
forLayerTime:(CFTimeInterval)timeInterval
displayTime:(const CVTimeStamp*)timeStamp {
if (helper_)
return helper_->CanDraw();
return NO;
}
- (void)drawInCGLContext:(CGLContextObj)glContext - (void)drawInCGLContext:(CGLContextObj)glContext
pixelFormat:(CGLPixelFormatObj)pixelFormat pixelFormat:(CGLPixelFormatObj)pixelFormat
forLayerTime:(CFTimeInterval)timeInterval forLayerTime:(CFTimeInterval)timeInterval
displayTime:(const CVTimeStamp*)timeStamp { displayTime:(const CVTimeStamp*)timeStamp {
TRACE_EVENT0("browser", "IOSurfaceLayer::drawInCGLContext"); TRACE_EVENT0("browser", "IOSurfaceLayer::drawInCGLContext");
// Create the texture if it has not been created in this context yet. if (!iosurface_->HasIOSurface() || context_->cgl_context() != glContext) {
if (!io_surface_texture_) {
DCHECK(!io_surface_texture_io_surface_);
DCHECK(!io_surface_texture_context_);
glGenTextures(1, &io_surface_texture_);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, io_surface_texture_);
glTexParameteri(
GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(
GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
io_surface_texture_context_.reset(glContext, base::scoped_policy::RETAIN);
}
DCHECK(io_surface_texture_context_ == glContext);
// Associate the IOSurface with this texture, if the underlying IOSurface has
// been changed.
if (io_surface_ != io_surface_texture_io_surface_) {
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, io_surface_texture_);
CGLError cgl_error = CGLTexImageIOSurface2D(
glContext,
GL_TEXTURE_RECTANGLE_ARB,
GL_RGBA,
IOSurfaceGetWidth(io_surface_),
IOSurfaceGetHeight(io_surface_),
GL_BGRA,
GL_UNSIGNED_INT_8_8_8_8_REV,
io_surface_.get(),
0 /* plane */);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
if (cgl_error == kCGLNoError) {
io_surface_texture_io_surface_ = io_surface_;
} else {
[self resetTextureAndPostDestroy];
content::GpuDataManagerImpl::GetInstance()->AddLogMessage(
logging::LOG_ERROR,
"IOSurfaceLayer",
std::string("CGLTexImageIOSurface2D failed with CGL error ") +
to_string(cgl_error));
if (client_)
client_->IOSurfaceLayerHitError();
}
} else if (!io_surface_) {
[self resetTextureAndPostDestroy];
}
// Fill the viewport with the texture. The viewport must be smaller or equal
// than the texture, because it is resized as frames arrive.
if (io_surface_texture_) {
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
gfx::Size viewport_pixel_size(viewport[2], viewport[3]);
DCHECK_LE(
viewport_pixel_size.width(),
frame_pixel_size_.width());
DCHECK_LE(
viewport_pixel_size.height(),
frame_pixel_size_.height());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, viewport_pixel_size.width(),
0, viewport_pixel_size.height(), -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor4f(1, 1, 1, 1);
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, io_surface_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(0, 0);
glTexCoord2f(viewport[2], 0);
glVertex2f(frame_pixel_size_.width(), 0);
glTexCoord2f(viewport[2], viewport[3]);
glVertex2f(frame_pixel_size_.width(), frame_pixel_size_.height());
glTexCoord2f(0, viewport[3]);
glVertex2f(0, frame_pixel_size_.height());
glEnd();
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
glDisable(GL_TEXTURE_RECTANGLE_ARB);
// Workaround for issue 158469. Issue a dummy draw call with
// io_surface_texture_ not bound to a texture, in order to shake all
// references to the IOSurface out of the driver.
glBegin(GL_TRIANGLES);
glEnd();
} else {
content::GpuDataManagerImpl::GetInstance()->AddLogMessage(
logging::LOG_ERROR,
"IOSurfaceLayer",
std::string("No texture to draw, clearing to white"));
glClearColor(1, 1, 1, 1); glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT);
return;
} }
// Query the current GL renderer to send back to the GPU process. // The correct viewport to cover the layer will be set up by the caller.
{ // Transform this into a window size for DrawIOSurface, where it will be
CGLError cgl_error = CGLGetParameter( // transformed back into this viewport.
glContext, kCGLCPCurrentRendererID, &cgl_renderer_id_); GLint viewport[4];
if (cgl_error == kCGLNoError) { glGetIntegerv(GL_VIEWPORT, viewport);
cgl_renderer_id_ &= kCGLRendererIDMatchingMask; gfx::Rect window_rect(viewport[0], viewport[1], viewport[2], viewport[3]);
} else { float window_scale_factor = 1.f;
content::GpuDataManagerImpl::GetInstance()->AddLogMessage( if ([self respondsToSelector:(@selector(contentsScale))])
logging::LOG_ERROR, window_scale_factor = [self contentsScale];
"IOSurfaceLayer", window_rect = ToNearestRect(
std::string("CGLGetParameter for kCGLCPCurrentRendererID failed ") + gfx::ScaleRect(window_rect, 1.f/window_scale_factor));
std::string("with CGL error ") + to_string(cgl_error));
cgl_renderer_id_ = 0;
}
}
// If we hit any errors, tell the client. bool draw_succeeded = iosurface_->DrawIOSurface(
while (GLenum gl_error = glGetError()) { context_, window_rect, window_scale_factor);
content::GpuDataManagerImpl::GetInstance()->AddLogMessage(
logging::LOG_ERROR, if (helper_)
"IOSurfaceLayer", helper_->DidDraw(draw_succeeded);
std::string("Hit GL error ") + to_string(gl_error) +
std::string(" in drawInCGLContext"));
if (client_)
client_->IOSurfaceLayerHitError();
}
needs_display_ = false;
[super drawInCGLContext:glContext [super drawInCGLContext:glContext
pixelFormat:pixelFormat pixelFormat:pixelFormat
forLayerTime:timeInterval forLayerTime:timeInterval
displayTime:timeStamp]; displayTime:timeStamp];
[self ackPendingFrame];
}
- (void)resetTextureAndPostDestroy {
if (!io_surface_texture_) {
DCHECK(!io_surface_texture_context_);
DCHECK(!io_surface_texture_io_surface_);
return;
}
// Post a task to clean up the texture on a clean stack.
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&DestroyTexture,
io_surface_texture_context_,
io_surface_texture_io_surface_,
io_surface_texture_));
// Reset the texture state.
io_surface_texture_ = 0;
io_surface_texture_context_.reset();
io_surface_texture_io_surface_.reset();
cgl_renderer_id_ = 0;
} }
@end @end
...@@ -125,9 +125,9 @@ IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest, MAYBE_CaptureScreenshot) { ...@@ -125,9 +125,9 @@ IN_PROC_BROWSER_TEST_F(CaptureScreenshotTest, MAYBE_CaptureScreenshot) {
gfx::PNGCodec::Decode(reinterpret_cast<const unsigned char*>(png.data()), gfx::PNGCodec::Decode(reinterpret_cast<const unsigned char*>(png.data()),
png.size(), &bitmap); png.size(), &bitmap);
SkColor color(bitmap.getColor(0, 0)); SkColor color(bitmap.getColor(0, 0));
EXPECT_LE(std::abs(0x12-(int)SkColorGetR(color)), 1); EXPECT_TRUE(std::abs(0x12-(int)SkColorGetR(color)) <= 1);
EXPECT_LE(std::abs(0x34-(int)SkColorGetG(color)), 1); EXPECT_TRUE(std::abs(0x34-(int)SkColorGetG(color)) <= 1);
EXPECT_LE(std::abs(0x56-(int)SkColorGetB(color)), 1); EXPECT_TRUE(std::abs(0x56-(int)SkColorGetB(color)) <= 1);
} }
} // namespace content } // namespace content
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment