Fix OpenGL crashes on macOS (#1899).
[dcpomatic.git] / src / wx / gl_video_view.cc
1 /*
2     Copyright (C) 2018-2019 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "gl_video_view.h"
22 #include "film_viewer.h"
23 #include "wx_util.h"
24 #include "lib/image.h"
25 #include "lib/dcpomatic_assert.h"
26 #include "lib/exceptions.h"
27 #include "lib/cross.h"
28 #include "lib/player_video.h"
29 #include "lib/butler.h"
30 #include <boost/bind/bind.hpp>
31 #include <iostream>
32
33 #ifdef DCPOMATIC_OSX
34 #include <OpenGL/glu.h>
35 #include <OpenGL/glext.h>
36 #include <OpenGL/CGLTypes.h>
37 #include <OpenGL/OpenGL.h>
38 #endif
39
40 #ifdef DCPOMATIC_LINUX
41 #include <GL/glu.h>
42 #include <GL/glext.h>
43 #endif
44
45 #ifdef DCPOMATIC_WINDOWS
46 #include <GL/glu.h>
47 #include <GL/glext.h>
48 #include <GL/wglext.h>
49 #endif
50
51 using std::cout;
52 using std::shared_ptr;
53 using boost::optional;
54 #if BOOST_VERSION >= 106100
55 using namespace boost::placeholders;
56 #endif
57
58
59 static void
60 check_gl_error (char const * last)
61 {
62         GLenum const e = glGetError ();
63         if (e != GL_NO_ERROR) {
64                 throw GLError (last, e);
65         }
66 }
67
68
69 GLVideoView::GLVideoView (FilmViewer* viewer, wxWindow *parent)
70         : VideoView (viewer)
71         , _context (nullptr)
72         , _have_storage (false)
73         , _vsync_enabled (false)
74         , _playing (false)
75         , _one_shot (false)
76 {
77         _canvas = new wxGLCanvas (parent, wxID_ANY, 0, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE);
78         _canvas->Bind (wxEVT_PAINT, boost::bind(&GLVideoView::update, this));
79         _canvas->Bind (wxEVT_SIZE, boost::bind(boost::ref(Sized)));
80
81         _canvas->Bind (wxEVT_TIMER, boost::bind(&GLVideoView::check_for_butler_errors, this));
82         _timer.reset (new wxTimer(_canvas));
83         _timer->Start (2000);
84 }
85
86 GLVideoView::~GLVideoView ()
87 {
88         boost::this_thread::disable_interruption dis;
89
90         try {
91                 _thread.interrupt ();
92                 _thread.join ();
93         } catch (...) {}
94
95         glDeleteTextures (1, &_id);
96 }
97
98 void
99 GLVideoView::check_for_butler_errors ()
100 {
101         if (!_viewer->butler()) {
102                 return;
103         }
104
105         try {
106                 _viewer->butler()->rethrow ();
107         } catch (DecodeError& e) {
108                 error_dialog (get(), e.what());
109         }
110 }
111
112
113 void
114 GLVideoView::update ()
115 {
116         {
117                 boost::mutex::scoped_lock lm (_canvas_mutex);
118                 if (!_canvas->IsShownOnScreen()) {
119                         return;
120                 }
121
122 #ifdef DCPOMATIC_OSX
123                 /* macOS gives errors if we don't do this (and therefore [NSOpenGLContext setView:]) from the main thread */
124                 ensure_context ();
125 #endif
126         }
127
128         if (!_thread.joinable()) {
129                 _thread = boost::thread (boost::bind(&GLVideoView::thread, this));
130         }
131
132         request_one_shot ();
133 }
134
135
136 void
137 GLVideoView::ensure_context ()
138 {
139         if (!_context) {
140                 _context = new wxGLContext (_canvas);
141                 _canvas->SetCurrent (*_context);
142         }
143 }
144
145 void
146 GLVideoView::draw (Position<int> inter_position, dcp::Size inter_size)
147 {
148         glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
149         check_gl_error ("glClear");
150
151         glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
152         check_gl_error ("glClearColor");
153         glEnable (GL_TEXTURE_2D);
154         check_gl_error ("glEnable GL_TEXTURE_2D");
155         glEnable (GL_BLEND);
156         check_gl_error ("glEnable GL_BLEND");
157         glDisable (GL_DEPTH_TEST);
158         check_gl_error ("glDisable GL_DEPTH_TEST");
159         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
160
161         wxSize canvas_size;
162         {
163                 boost::mutex::scoped_lock lm (_canvas_mutex);
164                 canvas_size = _canvas->GetSize ();
165         }
166
167         if (canvas_size.GetWidth() < 64 || canvas_size.GetHeight() < 0) {
168                 return;
169         }
170
171         glViewport (0, 0, canvas_size.GetWidth(), canvas_size.GetHeight());
172         check_gl_error ("glViewport");
173         glMatrixMode (GL_PROJECTION);
174         glLoadIdentity ();
175
176 DCPOMATIC_DISABLE_WARNINGS
177         gluOrtho2D (0, canvas_size.GetWidth(), canvas_size.GetHeight(), 0);
178 DCPOMATIC_ENABLE_WARNINGS
179         check_gl_error ("gluOrtho2d");
180         glMatrixMode (GL_MODELVIEW);
181         glLoadIdentity ();
182
183         glTranslatef (0, 0, 0);
184
185         dcp::Size const out_size = _viewer->out_size ();
186
187         if (_size) {
188                 /* Render our image (texture) */
189                 glBegin (GL_QUADS);
190                 glTexCoord2f (0, 1);
191                 glVertex2f (0, _size->height);
192                 glTexCoord2f (1, 1);
193                 glVertex2f (_size->width, _size->height);
194                 glTexCoord2f (1, 0);
195                 glVertex2f (_size->width, 0);
196                 glTexCoord2f (0, 0);
197                 glVertex2f (0, 0);
198                 glEnd ();
199         } else {
200                 /* No image, so just fill with black */
201                 glBegin (GL_QUADS);
202                 glColor3ub (0, 0, 0);
203                 glVertex2f (0, 0);
204                 glVertex2f (out_size.width, 0);
205                 glVertex2f (out_size.width, out_size.height);
206                 glVertex2f (0, out_size.height);
207                 glVertex2f (0, 0);
208                 glEnd ();
209         }
210
211         if (!_viewer->pad_black() && out_size.width < canvas_size.GetWidth()) {
212                 glBegin (GL_QUADS);
213                 /* XXX: these colours are right for GNOME; may need adjusting for other OS */
214                 glColor3ub (240, 240, 240);
215                 glVertex2f (out_size.width, 0);
216                 glVertex2f (canvas_size.GetWidth(), 0);
217                 glVertex2f (canvas_size.GetWidth(), canvas_size.GetHeight());
218                 glVertex2f (out_size.width, canvas_size.GetHeight());
219                 glEnd ();
220                 glColor3ub (255, 255, 255);
221         }
222
223         if (!_viewer->pad_black() && out_size.height < canvas_size.GetHeight()) {
224                 glColor3ub (240, 240, 240);
225                 int const gap = (canvas_size.GetHeight() - out_size.height) / 2;
226                 glBegin (GL_QUADS);
227                 glVertex2f (0, 0);
228                 glVertex2f (canvas_size.GetWidth(), 0);
229                 glVertex2f (canvas_size.GetWidth(), gap);
230                 glVertex2f (0, gap);
231                 glEnd ();
232                 glBegin (GL_QUADS);
233                 glVertex2f (0, gap + out_size.height + 1);
234                 glVertex2f (canvas_size.GetWidth(), gap + out_size.height + 1);
235                 glVertex2f (canvas_size.GetWidth(), 2 * gap + out_size.height + 2);
236                 glVertex2f (0, 2 * gap + out_size.height + 2);
237                 glEnd ();
238                 glColor3ub (255, 255, 255);
239         }
240
241         if (_viewer->outline_content()) {
242                 glColor3ub (255, 0, 0);
243                 glBegin (GL_LINE_LOOP);
244                 glVertex2f (inter_position.x, inter_position.y + (canvas_size.GetHeight() - out_size.height) / 2);
245                 glVertex2f (inter_position.x + inter_size.width, inter_position.y + (canvas_size.GetHeight() - out_size.height) / 2);
246                 glVertex2f (inter_position.x + inter_size.width, inter_position.y + (canvas_size.GetHeight() - out_size.height) / 2 + inter_size.height);
247                 glVertex2f (inter_position.x, inter_position.y + (canvas_size.GetHeight() - out_size.height) / 2 + inter_size.height);
248                 glEnd ();
249                 glColor3ub (255, 255, 255);
250         }
251
252         glFlush();
253         check_gl_error ("glFlush");
254
255         boost::mutex::scoped_lock lm (_canvas_mutex);
256         _canvas->SwapBuffers();
257 }
258
259 void
260 GLVideoView::set_image (shared_ptr<const Image> image)
261 {
262         if (!image) {
263                 _size = optional<dcp::Size>();
264                 return;
265         }
266
267         DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_RGB24);
268         DCPOMATIC_ASSERT (!image->aligned());
269
270         if (image->size() != _size) {
271                 _have_storage = false;
272         }
273
274         _size = image->size ();
275         glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
276         check_gl_error ("glPixelStorei");
277         if (_have_storage) {
278                 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _size->width, _size->height, GL_RGB, GL_UNSIGNED_BYTE, image->data()[0]);
279                 check_gl_error ("glTexSubImage2D");
280         } else {
281                 glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB8, _size->width, _size->height, 0, GL_RGB, GL_UNSIGNED_BYTE, image->data()[0]);
282                 _have_storage = true;
283                 check_gl_error ("glTexImage2D");
284         }
285
286         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
287         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
288         check_gl_error ("glTexParameteri");
289
290         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
291         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
292         check_gl_error ("glTexParameterf");
293 }
294
295 void
296 GLVideoView::start ()
297 {
298         VideoView::start ();
299
300         boost::mutex::scoped_lock lm (_playing_mutex);
301         _playing = true;
302         _thread_work_condition.notify_all ();
303 }
304
305 void
306 GLVideoView::stop ()
307 {
308         boost::mutex::scoped_lock lm (_playing_mutex);
309         _playing = false;
310 }
311
312
313 void
314 GLVideoView::thread_playing ()
315 {
316         if (length() != dcpomatic::DCPTime()) {
317                 dcpomatic::DCPTime const next = position() + one_video_frame();
318
319                 if (next >= length()) {
320                         _viewer->finished ();
321                         return;
322                 }
323
324                 get_next_frame (false);
325                 set_image_and_draw ();
326         }
327
328         while (true) {
329                 optional<int> n = time_until_next_frame();
330                 if (!n || *n > 5) {
331                         break;
332                 }
333                 get_next_frame (true);
334                 add_dropped ();
335         }
336 }
337
338
339 void
340 GLVideoView::set_image_and_draw ()
341 {
342         shared_ptr<PlayerVideo> pv = player_video().first;
343         if (pv) {
344                 set_image (pv->image(bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), VIDEO_RANGE_FULL, false, true));
345                 draw (pv->inter_position(), pv->inter_size());
346                 _viewer->image_changed (pv);
347         }
348 }
349
350
351 void
352 GLVideoView::thread ()
353 try
354 {
355         {
356                 boost::mutex::scoped_lock lm (_canvas_mutex);
357
358 #if defined(DCPOMATIC_OSX)
359                 /* Without this we see errors like
360                  * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
361                  */
362                 WXGLSetCurrentContext (_context->GetWXGLContext());
363 #else
364                 /* We must call this here on Linux otherwise we get no image (for reasons
365                  * that aren't clear).  However, doing ensure_context() from this thread
366                  * on macOS gives
367                  * "[NSOpenGLContext setView:] must be called from the main thread".
368                  */
369                 ensure_context ();
370 #endif
371         }
372
373 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
374         if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
375                 /* Enable vsync */
376                 Display* dpy = wxGetX11Display();
377                 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
378                 _vsync_enabled = true;
379         }
380 #endif
381
382 #ifdef DCPOMATIC_WINDOWS
383         if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
384                 /* Enable vsync */
385                 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
386                 if (swap) {
387                         swap (1);
388                         _vsync_enabled = true;
389                 }
390         }
391
392 #endif
393
394 #ifdef DCPOMATIC_OSX
395         /* Enable vsync */
396         GLint swapInterval = 1;
397         CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
398         _vsync_enabled = true;
399 #endif
400
401         glGenTextures (1, &_id);
402         check_gl_error ("glGenTextures");
403         glBindTexture (GL_TEXTURE_2D, _id);
404         check_gl_error ("glBindTexture");
405         glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
406         check_gl_error ("glPixelStorei");
407
408         while (true) {
409                 boost::mutex::scoped_lock lm (_playing_mutex);
410                 while (!_playing && !_one_shot) {
411                         _thread_work_condition.wait (lm);
412                 }
413                 lm.unlock ();
414
415                 if (_playing) {
416                         thread_playing ();
417                 } else if (_one_shot) {
418                         _one_shot = false;
419                         set_image_and_draw ();
420                 }
421
422                 boost::this_thread::interruption_point ();
423                 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
424         }
425
426         /* XXX: leaks _context, but that seems preferable to deleting it here
427          * without also deleting the wxGLCanvas.
428          */
429 }
430 catch (boost::thread_interrupted& e)
431 {
432         store_current ();
433 }
434
435
436 VideoView::NextFrameResult
437 GLVideoView::display_next_frame (bool non_blocking)
438 {
439         NextFrameResult const r = get_next_frame (non_blocking);
440         request_one_shot ();
441         return r;
442 }
443
444
445 void
446 GLVideoView::request_one_shot ()
447 {
448         boost::mutex::scoped_lock lm (_playing_mutex);
449         _one_shot = true;
450         _thread_work_condition.notify_all ();
451 }
452