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/. */
5
6#include "GLContextProvider.h"
7#include "GLContextCGL.h"
8#include "GLLibraryLoader.h"
9#include "nsDebug.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"
17#include "prenv.h"
18#include "prlink.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"
24
25#include <OpenGL/OpenGL.h>
26
27namespace mozilla {
28namespace gl {
29
30using namespace mozilla::gfx;
31using namespace mozilla::widget;
32
33class CGLLibrary {
34 public:
35  bool EnsureInitialized() {
36    if (mInitialized) {
37      return true;
38    }
39    if (!mOGLLibrary) {
40      mOGLLibrary = PR_LoadLibrary("/System/Library/Frameworks/OpenGL.framework/OpenGL");
41      if (!mOGLLibrary) {
42        NS_WARNING("Couldn't load OpenGL Framework.");
43        return false;
44      }
45    }
46
47    mInitialized = true;
48    return true;
49  }
50
51  const auto& Library() const { return mOGLLibrary; }
52
53 private:
54  bool mInitialized = false;
55  PRLibrary* mOGLLibrary = nullptr;
56};
57
58CGLLibrary sCGLLibrary;
59
60GLContextCGL::GLContextCGL(const GLContextDesc& desc, NSOpenGLContext* context)
61    : GLContext(desc), mContext(context) {
62  CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallback, this);
63}
64
65GLContextCGL::~GLContextCGL() {
66  MarkDestroyed();
67
68  CGDisplayRemoveReconfigurationCallback(DisplayReconfigurationCallback, this);
69
70  if (mContext) {
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];
76    }
77    [mContext release];
78  }
79}
80
81CGLContextObj GLContextCGL::GetCGLContext() const {
82  return static_cast<CGLContextObj>([mContext CGLContextObj]);
83}
84
85bool GLContextCGL::MakeCurrentImpl() const {
86  if (mContext) {
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];
97  }
98  return true;
99}
100
101bool GLContextCGL::IsCurrentImpl() const { return [NSOpenGLContext currentContext] == mContext; }
102
103/* static */ void GLContextCGL::DisplayReconfigurationCallback(CGDirectDisplayID aDisplay,
104                                                               CGDisplayChangeSummaryFlags aFlags,
105                                                               void* aUserInfo) {
106  if (aFlags & kCGDisplaySetModeFlag) {
107    static_cast<GLContextCGL*>(aUserInfo)->mActiveGPUSwitchMayHaveOccurred = true;
108  }
109}
110
111static NSOpenGLContext* CreateWithFormat(const NSOpenGLPixelFormatAttribute* attribs) {
112  NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
113  if (!format) {
114    NS_WARNING("Failed to create NSOpenGLPixelFormat.");
115    return nullptr;
116  }
117
118  NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:format shareContext:nullptr];
119
120  [format release];
121
122  return context;
123}
124
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.
129//
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
134//     warm-up cost.)
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.
148static 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];
159  [context release];
160  return static_cast<CGOpenGLDisplayMask>(displayMask);
161}
162
163static bool IsSameGPU(CGOpenGLDisplayMask mask1, CGOpenGLDisplayMask mask2) {
164  if ((mask1 & mask2) != 0) {
165    return true;
166  }
167  // Both masks can be zero, when using the Apple software renderer.
168  return !mask1 && !mask2;
169}
170
171void GLContextCGL::MigrateToActiveGPU() {
172  if (!mActiveGPUSwitchMayHaveOccurred.compareExchange(true, false)) {
173    return;
174  }
175
176  CGOpenGLDisplayMask newPreferredDisplayMask = GetFreshContextDisplayMask();
177  NSOpenGLPixelFormat* pixelFormat = [mContext pixelFormat];
178  GLint currentVirtualScreen = [mContext currentVirtualScreen];
179  GLint currentDisplayMask = 0;
180  [pixelFormat getValues:&currentDisplayMask
181            forAttribute:NSOpenGLPFAScreenMask
182        forVirtualScreen:currentVirtualScreen];
183  if (IsSameGPU(currentDisplayMask, newPreferredDisplayMask)) {
184    // No "virtual screen" change needed.
185    return;
186  }
187
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);
197      return;
198    }
199  }
200}
201
202GLenum GLContextCGL::GetPreferredARGB32Format() const { return LOCAL_GL_BGRA; }
203
204bool GLContextCGL::SwapBuffers() {
205  AUTO_PROFILER_LABEL("GLContextCGL::SwapBuffers", GRAPHICS);
206
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.
210  fFlush();
211
212  return true;
213}
214
215void GLContextCGL::GetWSIInfo(nsCString* const out) const { out->AppendLiteral("CGL"); }
216
217Maybe<SymbolLoader> GLContextCGL::GetSymbolLoader() const {
218  const auto& lib = sCGLLibrary.Library();
219  return Some(SymbolLoader(*lib));
220}
221
222already_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;
227  }
228  if (!aHardwareWebRender) {
229    flags |= CreateContextFlags::REQUIRE_COMPAT_PROFILE;
230  }
231  nsCString failureUnused;
232  return CreateHeadless({flags}, &failureUnused);
233}
234
235static RefPtr<GLContextCGL> CreateOffscreenFBOContext(GLContextCreateDesc desc) {
236  if (!sCGLLibrary.EnsureInitialized()) {
237    return nullptr;
238  }
239
240  NSOpenGLContext* context = nullptr;
241
242  std::vector<NSOpenGLPixelFormatAttribute> attribs;
243  auto& flags = desc.flags;
244
245  if (!StaticPrefs::gl_allow_high_power()) {
246    flags &= ~CreateContextFlags::HIGH_POWER;
247  }
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);
253  }
254
255  if (flags & CreateContextFlags::FORCE_ENABLE_HARDWARE) {
256    attribs.push_back(NSOpenGLPFAAccelerated);
257  }
258
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());
265  }
266
267  if (!context) {
268    attribs.push_back(0);
269    context = CreateWithFormat(attribs.data());
270  }
271
272  if (!context) {
273    NS_WARNING("Failed to create NSOpenGLContext.");
274    return nullptr;
275  }
276
277  RefPtr<GLContextCGL> glContext = new GLContextCGL({desc, true}, context);
278
279  if (flags & CreateContextFlags::PREFER_MULTITHREADED) {
280    CGLEnable(glContext->GetCGLContext(), kCGLCEMPEngine);
281  }
282  return glContext;
283}
284
285already_AddRefed<GLContext> GLContextProviderCGL::CreateHeadless(const GLContextCreateDesc& desc,
286                                                                 nsACString* const out_failureId) {
287  auto gl = CreateOffscreenFBOContext(desc);
288  if (!gl) {
289    *out_failureId = "FEATURE_FAILURE_CGL_FBO"_ns;
290    return nullptr;
291  }
292
293  if (!gl->Init()) {
294    *out_failureId = "FEATURE_FAILURE_CGL_INIT"_ns;
295    NS_WARNING("Failed during Init.");
296    return nullptr;
297  }
298
299  return gl.forget();
300}
301
302static RefPtr<GLContext> gGlobalContext;
303
304GLContext* GLContextProviderCGL::GetGlobalContext() {
305  static bool triedToCreateContext = false;
306  if (!triedToCreateContext) {
307    triedToCreateContext = true;
308
309    MOZ_RELEASE_ASSERT(!gGlobalContext);
310    nsCString discardFailureId;
311    RefPtr<GLContext> temp = CreateHeadless({}, &discardFailureId);
312    gGlobalContext = temp;
313
314    if (!gGlobalContext) {
315      NS_WARNING("Couldn't init gGlobalContext.");
316    }
317  }
318
319  return gGlobalContext;
320}
321
322void GLContextProviderCGL::Shutdown() { gGlobalContext = nullptr; }
323
324} /* namespace gl */
325} /* namespace mozilla */
326