1 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "GLContextProvider.h"
7 #include "GLContextCGL.h"
8 #include "GLLibraryLoader.h"
10 #include "nsIWidget.h"
11 #include <OpenGL/gl.h>
12 #include "gfxFailure.h"
13 #include "mozilla/IntegerRange.h"
14 #include "mozilla/StaticPrefs_gfx.h"
15 #include "mozilla/StaticPrefs_gl.h"
16 #include "mozilla/StaticPrefs_layout.h"
19 #include "mozilla/ProfilerLabels.h"
20 #include "MozFramebuffer.h"
21 #include "mozilla/layers/CompositorOptions.h"
22 #include "mozilla/widget/CompositorWidget.h"
23 #include "ScopedGLHelpers.h"
25 #include <OpenGL/OpenGL.h>
30 using namespace mozilla::gfx;
31 using namespace mozilla::widget;
35 bool EnsureInitialized() {
40 mOGLLibrary = PR_LoadLibrary("/System/Library/Frameworks/OpenGL.framework/OpenGL");
42 NS_WARNING("Couldn't load OpenGL Framework.");
51 const auto& Library() const { return mOGLLibrary; }
54 bool mInitialized = false;
55 PRLibrary* mOGLLibrary = nullptr;
58 CGLLibrary sCGLLibrary;
60 GLContextCGL::GLContextCGL(const GLContextDesc& desc, NSOpenGLContext* context)
61 : GLContext(desc), mContext(context) {
62 CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallback, this);
65 GLContextCGL::~GLContextCGL() {
68 CGDisplayRemoveReconfigurationCallback(DisplayReconfigurationCallback, this);
71 if ([NSOpenGLContext currentContext] == mContext) {
72 // Clear the current context before releasing. If we don't do
73 // this, the next time we call [NSOpenGLContext currentContext],
74 // "invalid context" will be printed to the console.
75 [NSOpenGLContext clearCurrentContext];
81 CGLContextObj GLContextCGL::GetCGLContext() const {
82 return static_cast<CGLContextObj>([mContext CGLContextObj]);
85 bool GLContextCGL::MakeCurrentImpl() const {
87 [mContext makeCurrentContext];
88 MOZ_ASSERT(IsCurrentImpl());
89 // Use non-blocking swap in "ASAP mode".
90 // ASAP mode means that rendering is iterated as fast as possible.
91 // ASAP mode is entered when layout.frame_rate=0 (requires restart).
92 // If swapInt is 1, then glSwapBuffers will block and wait for a vblank signal.
93 // When we're iterating as fast as possible, however, we want a non-blocking
94 // glSwapBuffers, which will happen when swapInt==0.
95 GLint swapInt = StaticPrefs::layout_frame_rate() == 0 ? 0 : 1;
96 [mContext setValues:&swapInt forParameter:NSOpenGLCPSwapInterval];
101 bool GLContextCGL::IsCurrentImpl() const { return [NSOpenGLContext currentContext] == mContext; }
103 /* static */ void GLContextCGL::DisplayReconfigurationCallback(CGDirectDisplayID aDisplay,
104 CGDisplayChangeSummaryFlags aFlags,
106 if (aFlags & kCGDisplaySetModeFlag) {
107 static_cast<GLContextCGL*>(aUserInfo)->mActiveGPUSwitchMayHaveOccurred = true;
111 static NSOpenGLContext* CreateWithFormat(const NSOpenGLPixelFormatAttribute* attribs) {
112 NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
114 NS_WARNING("Failed to create NSOpenGLPixelFormat.");
118 NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:format shareContext:nullptr];
125 // Get the "OpenGL display mask" for a fresh context. The return value of this
126 // function depends on the time at which this function is called.
127 // In practice, on a Macbook Pro with an integrated and a discrete GPU, this function returns the
128 // display mask for the GPU that currently drives the internal display.
130 // Quick reference of the concepts involved in the code below:
131 // GPU switch: On Mac devices with an integrated and a discrete GPU, a GPU switch changes which
132 // GPU drives the internal display. Both GPUs are still usable at all times. (When the
133 // integrated GPU is driving the internal display, using the discrete GPU can incur a longer
135 // Virtual screen: A CGL concept. A "virtual screen" corresponds to a GL renderer. There's one
136 // for the integrated GPU, one for each discrete GPU, and one for the Apple software renderer.
137 // The list of virtual screens is per-NSOpenGLPixelFormat; it is filtered down to only the
138 // renderers that support the requirements from the pixel format attributes. Indexes into this
139 // list (such as currentVirtualScreen) cannot be used interchangably across different
140 // NSOpenGLPixelFormat instances.
141 // Display mask: A bitset per GL renderer. Different renderers have disjoint display masks. The
142 // Apple software renderer has all bits zeroed. For each CGDirectDisplayID,
143 // CGDisplayIDToOpenGLDisplayMask(displayID) returns a single bit in the display mask.
144 // CGDirectDisplayID: An ID for each (physical screen, GPU which can drive this screen) pair. The
145 // current CGDirectDisplayID for an NSScreen object can be obtained using [[[screen
146 // deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; it changes depending on
147 // which GPU is currently driving the screen.
148 static CGOpenGLDisplayMask GetFreshContextDisplayMask() {
149 NSOpenGLPixelFormatAttribute attribs[] = {NSOpenGLPFAAllowOfflineRenderers, 0};
150 NSOpenGLPixelFormat* pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
151 MOZ_RELEASE_ASSERT(pixelFormat);
152 NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat
153 shareContext:nullptr];
154 GLint displayMask = 0;
155 [pixelFormat getValues:&displayMask
156 forAttribute:NSOpenGLPFAScreenMask
157 forVirtualScreen:[context currentVirtualScreen]];
158 [pixelFormat release];
160 return static_cast<CGOpenGLDisplayMask>(displayMask);
163 static bool IsSameGPU(CGOpenGLDisplayMask mask1, CGOpenGLDisplayMask mask2) {
164 if ((mask1 & mask2) != 0) {
167 // Both masks can be zero, when using the Apple software renderer.
168 return !mask1 && !mask2;
171 void GLContextCGL::MigrateToActiveGPU() {
172 if (!mActiveGPUSwitchMayHaveOccurred.compareExchange(true, false)) {
176 CGOpenGLDisplayMask newPreferredDisplayMask = GetFreshContextDisplayMask();
177 NSOpenGLPixelFormat* pixelFormat = [mContext pixelFormat];
178 GLint currentVirtualScreen = [mContext currentVirtualScreen];
179 GLint currentDisplayMask = 0;
180 [pixelFormat getValues:¤tDisplayMask
181 forAttribute:NSOpenGLPFAScreenMask
182 forVirtualScreen:currentVirtualScreen];
183 if (IsSameGPU(currentDisplayMask, newPreferredDisplayMask)) {
184 // No "virtual screen" change needed.
188 // Find the "virtual screen" with a display mask that matches newPreferredDisplayMask, if
189 // available, and switch the context over to it.
190 // This code was inspired by equivalent functionality in -[NSOpenGLContext update] which only
191 // kicks in for contexts that present via a CAOpenGLLayer.
192 for (const auto i : IntegerRange([pixelFormat numberOfVirtualScreens])) {
193 GLint displayMask = 0;
194 [pixelFormat getValues:&displayMask forAttribute:NSOpenGLPFAScreenMask forVirtualScreen:i];
195 if (IsSameGPU(displayMask, newPreferredDisplayMask)) {
196 CGLSetVirtualScreen([mContext CGLContextObj], i);
202 GLenum GLContextCGL::GetPreferredARGB32Format() const { return LOCAL_GL_BGRA; }
204 bool GLContextCGL::SwapBuffers() {
205 AUTO_PROFILER_LABEL("GLContextCGL::SwapBuffers", GRAPHICS);
207 // We do not have a default framebuffer. Just do a flush.
208 // Flushing is necessary if we want our IOSurfaces to have the correct
209 // content once they're picked up by the WindowServer from our CALayers.
215 void GLContextCGL::GetWSIInfo(nsCString* const out) const { out->AppendLiteral("CGL"); }
217 Maybe<SymbolLoader> GLContextCGL::GetSymbolLoader() const {
218 const auto& lib = sCGLLibrary.Library();
219 return Some(SymbolLoader(*lib));
222 already_AddRefed<GLContext> GLContextProviderCGL::CreateForCompositorWidget(
223 CompositorWidget* aCompositorWidget, bool aHardwareWebRender, bool aForceAccelerated) {
224 CreateContextFlags flags = CreateContextFlags::ALLOW_OFFLINE_RENDERER;
225 if (aForceAccelerated) {
226 flags |= CreateContextFlags::FORCE_ENABLE_HARDWARE;
228 if (!aHardwareWebRender) {
229 flags |= CreateContextFlags::REQUIRE_COMPAT_PROFILE;
231 nsCString failureUnused;
232 return CreateHeadless({flags}, &failureUnused);
235 static RefPtr<GLContextCGL> CreateOffscreenFBOContext(GLContextCreateDesc desc) {
236 if (!sCGLLibrary.EnsureInitialized()) {
240 NSOpenGLContext* context = nullptr;
242 std::vector<NSOpenGLPixelFormatAttribute> attribs;
243 auto& flags = desc.flags;
245 if (!StaticPrefs::gl_allow_high_power()) {
246 flags &= ~CreateContextFlags::HIGH_POWER;
248 if (flags & CreateContextFlags::ALLOW_OFFLINE_RENDERER ||
249 !(flags & CreateContextFlags::HIGH_POWER)) {
250 // This is really poorly named on Apple's part, but "AllowOfflineRenderers" means
251 // that we want to allow running on the iGPU instead of requiring the dGPU.
252 attribs.push_back(NSOpenGLPFAAllowOfflineRenderers);
255 if (flags & CreateContextFlags::FORCE_ENABLE_HARDWARE) {
256 attribs.push_back(NSOpenGLPFAAccelerated);
259 if (!(flags & CreateContextFlags::REQUIRE_COMPAT_PROFILE)) {
260 auto coreAttribs = attribs;
261 coreAttribs.push_back(NSOpenGLPFAOpenGLProfile);
262 coreAttribs.push_back(NSOpenGLProfileVersion3_2Core);
263 coreAttribs.push_back(0);
264 context = CreateWithFormat(coreAttribs.data());
268 attribs.push_back(0);
269 context = CreateWithFormat(attribs.data());
273 NS_WARNING("Failed to create NSOpenGLContext.");
277 RefPtr<GLContextCGL> glContext = new GLContextCGL({desc, true}, context);
279 if (flags & CreateContextFlags::PREFER_MULTITHREADED) {
280 CGLEnable(glContext->GetCGLContext(), kCGLCEMPEngine);
285 already_AddRefed<GLContext> GLContextProviderCGL::CreateHeadless(const GLContextCreateDesc& desc,
286 nsACString* const out_failureId) {
287 auto gl = CreateOffscreenFBOContext(desc);
289 *out_failureId = "FEATURE_FAILURE_CGL_FBO"_ns;
294 *out_failureId = "FEATURE_FAILURE_CGL_INIT"_ns;
295 NS_WARNING("Failed during Init.");
302 static RefPtr<GLContext> gGlobalContext;
304 GLContext* GLContextProviderCGL::GetGlobalContext() {
305 static bool triedToCreateContext = false;
306 if (!triedToCreateContext) {
307 triedToCreateContext = true;
309 MOZ_RELEASE_ASSERT(!gGlobalContext);
310 nsCString discardFailureId;
311 RefPtr<GLContext> temp = CreateHeadless({}, &discardFailureId);
312 gGlobalContext = temp;
314 if (!gGlobalContext) {
315 NS_WARNING("Couldn't init gGlobalContext.");
319 return gGlobalContext;
322 void GLContextProviderCGL::Shutdown() { gGlobalContext = nullptr; }
325 } /* namespace mozilla */