Make the GL thread access the canvas size in a less ridiculous way.
[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(&GLVideoView::size_changed, this, _1));
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
87 void
88 GLVideoView::size_changed (wxSizeEvent const& ev)
89 {
90         _canvas_size = ev.GetSize ();
91         Sized ();
92 }
93
94
95
96 GLVideoView::~GLVideoView ()
97 {
98         boost::this_thread::disable_interruption dis;
99
100         try {
101                 _thread.interrupt ();
102                 _thread.join ();
103         } catch (...) {}
104
105         glDeleteTextures (1, &_id);
106 }
107
108 void
109 GLVideoView::check_for_butler_errors ()
110 {
111         if (!_viewer->butler()) {
112                 return;
113         }
114
115         try {
116                 _viewer->butler()->rethrow ();
117         } catch (DecodeError& e) {
118                 error_dialog (get(), e.what());
119         } catch (dcp::ReadError& e) {
120                 error_dialog (get(), wxString::Format(_("Could not read DCP: %s"), std_to_wx(e.what())));
121         }
122 }
123
124
125 void
126 GLVideoView::update ()
127 {
128         {
129                 boost::mutex::scoped_lock lm (_canvas_mutex);
130                 if (!_canvas->IsShownOnScreen()) {
131                         return;
132                 }
133
134 #ifdef DCPOMATIC_OSX
135                 /* macOS gives errors if we don't do this (and therefore [NSOpenGLContext setView:]) from the main thread */
136                 ensure_context ();
137 #endif
138         }
139
140         if (!_thread.joinable()) {
141                 _thread = boost::thread (boost::bind(&GLVideoView::thread, this));
142         }
143
144         request_one_shot ();
145 }
146
147
148 void
149 GLVideoView::ensure_context ()
150 {
151         if (!_context) {
152                 _context = new wxGLContext (_canvas);
153                 _canvas->SetCurrent (*_context);
154         }
155 }
156
157 void
158 GLVideoView::draw (Position<int> inter_position, dcp::Size inter_size)
159 {
160         glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
161         check_gl_error ("glClear");
162
163         glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
164         check_gl_error ("glClearColor");
165         glEnable (GL_TEXTURE_2D);
166         check_gl_error ("glEnable GL_TEXTURE_2D");
167         glEnable (GL_BLEND);
168         check_gl_error ("glEnable GL_BLEND");
169         glDisable (GL_DEPTH_TEST);
170         check_gl_error ("glDisable GL_DEPTH_TEST");
171         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
172
173         auto const size = _canvas_size.load();
174         int const width = size.GetWidth();
175         int const height = size.GetHeight();
176
177         if (width < 64 || height < 0) {
178                 return;
179         }
180
181         glViewport (0, 0, width, height);
182         check_gl_error ("glViewport");
183         glMatrixMode (GL_PROJECTION);
184         glLoadIdentity ();
185
186 DCPOMATIC_DISABLE_WARNINGS
187         gluOrtho2D (0, width, height, 0);
188 DCPOMATIC_ENABLE_WARNINGS
189         check_gl_error ("gluOrtho2d");
190         glMatrixMode (GL_MODELVIEW);
191         glLoadIdentity ();
192
193         glTranslatef (0, 0, 0);
194
195         dcp::Size const out_size = _viewer->out_size ();
196
197         if (_size) {
198                 /* Render our image (texture) */
199                 glBegin (GL_QUADS);
200                 glTexCoord2f (0, 1);
201                 glVertex2f (0, _size->height);
202                 glTexCoord2f (1, 1);
203                 glVertex2f (_size->width, _size->height);
204                 glTexCoord2f (1, 0);
205                 glVertex2f (_size->width, 0);
206                 glTexCoord2f (0, 0);
207                 glVertex2f (0, 0);
208                 glEnd ();
209         } else {
210                 /* No image, so just fill with black */
211                 glBegin (GL_QUADS);
212                 glColor3ub (0, 0, 0);
213                 glVertex2f (0, 0);
214                 glVertex2f (out_size.width, 0);
215                 glVertex2f (out_size.width, out_size.height);
216                 glVertex2f (0, out_size.height);
217                 glVertex2f (0, 0);
218                 glEnd ();
219         }
220
221         if (!_viewer->pad_black() && out_size.width < width) {
222                 glBegin (GL_QUADS);
223                 /* XXX: these colours are right for GNOME; may need adjusting for other OS */
224                 glColor3ub (240, 240, 240);
225                 glVertex2f (out_size.width, 0);
226                 glVertex2f (width, 0);
227                 glVertex2f (width, height);
228                 glVertex2f (out_size.width, height);
229                 glEnd ();
230                 glColor3ub (255, 255, 255);
231         }
232
233         if (!_viewer->pad_black() && out_size.height < height) {
234                 glColor3ub (240, 240, 240);
235                 int const gap = (height - out_size.height) / 2;
236                 glBegin (GL_QUADS);
237                 glVertex2f (0, 0);
238                 glVertex2f (width, 0);
239                 glVertex2f (width, gap);
240                 glVertex2f (0, gap);
241                 glEnd ();
242                 glBegin (GL_QUADS);
243                 glVertex2f (0, gap + out_size.height + 1);
244                 glVertex2f (width, gap + out_size.height + 1);
245                 glVertex2f (width, 2 * gap + out_size.height + 2);
246                 glVertex2f (0, 2 * gap + out_size.height + 2);
247                 glEnd ();
248                 glColor3ub (255, 255, 255);
249         }
250
251         if (_viewer->outline_content()) {
252                 glColor3ub (255, 0, 0);
253                 glBegin (GL_LINE_LOOP);
254                 glVertex2f (inter_position.x, inter_position.y + (height - out_size.height) / 2);
255                 glVertex2f (inter_position.x + inter_size.width, inter_position.y + (height - out_size.height) / 2);
256                 glVertex2f (inter_position.x + inter_size.width, inter_position.y + (height - out_size.height) / 2 + inter_size.height);
257                 glVertex2f (inter_position.x, inter_position.y + (height - out_size.height) / 2 + inter_size.height);
258                 glEnd ();
259                 glColor3ub (255, 255, 255);
260         }
261
262         glFlush();
263         check_gl_error ("glFlush");
264
265         boost::mutex::scoped_lock lm (_canvas_mutex);
266         _canvas->SwapBuffers();
267 }
268
269 void
270 GLVideoView::set_image (shared_ptr<const Image> image)
271 {
272         if (!image) {
273                 _size = optional<dcp::Size>();
274                 return;
275         }
276
277         DCPOMATIC_ASSERT (image->pixel_format() == AV_PIX_FMT_RGB24);
278         DCPOMATIC_ASSERT (!image->aligned());
279
280         if (image->size() != _size) {
281                 _have_storage = false;
282         }
283
284         _size = image->size ();
285         glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
286         check_gl_error ("glPixelStorei");
287         if (_have_storage) {
288                 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _size->width, _size->height, GL_RGB, GL_UNSIGNED_BYTE, image->data()[0]);
289                 check_gl_error ("glTexSubImage2D");
290         } else {
291                 glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB8, _size->width, _size->height, 0, GL_RGB, GL_UNSIGNED_BYTE, image->data()[0]);
292                 _have_storage = true;
293                 check_gl_error ("glTexImage2D");
294         }
295
296         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
297         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
298         check_gl_error ("glTexParameteri");
299
300         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
301         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
302         check_gl_error ("glTexParameterf");
303 }
304
305 void
306 GLVideoView::start ()
307 {
308         VideoView::start ();
309
310         boost::mutex::scoped_lock lm (_playing_mutex);
311         _playing = true;
312         _thread_work_condition.notify_all ();
313 }
314
315 void
316 GLVideoView::stop ()
317 {
318         boost::mutex::scoped_lock lm (_playing_mutex);
319         _playing = false;
320 }
321
322
323 void
324 GLVideoView::thread_playing ()
325 {
326         if (length() != dcpomatic::DCPTime()) {
327                 dcpomatic::DCPTime const next = position() + one_video_frame();
328
329                 if (next >= length()) {
330                         _viewer->finished ();
331                         return;
332                 }
333
334                 get_next_frame (false);
335                 set_image_and_draw ();
336         }
337
338         while (true) {
339                 optional<int> n = time_until_next_frame();
340                 if (!n || *n > 5) {
341                         break;
342                 }
343                 get_next_frame (true);
344                 add_dropped ();
345         }
346 }
347
348
349 void
350 GLVideoView::set_image_and_draw ()
351 {
352         shared_ptr<PlayerVideo> pv = player_video().first;
353         if (pv) {
354                 set_image (pv->image(bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), VideoRange::FULL, false, true));
355                 draw (pv->inter_position(), pv->inter_size());
356                 _viewer->image_changed (pv);
357         }
358 }
359
360
361 void
362 GLVideoView::thread ()
363 try
364 {
365         start_of_thread ("GLVideoView");
366
367         {
368                 boost::mutex::scoped_lock lm (_canvas_mutex);
369
370 #if defined(DCPOMATIC_OSX)
371                 /* Without this we see errors like
372                  * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
373                  */
374                 WXGLSetCurrentContext (_context->GetWXGLContext());
375 #else
376                 /* We must call this here on Linux otherwise we get no image (for reasons
377                  * that aren't clear).  However, doing ensure_context() from this thread
378                  * on macOS gives
379                  * "[NSOpenGLContext setView:] must be called from the main thread".
380                  */
381                 ensure_context ();
382 #endif
383         }
384
385 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
386         if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
387                 /* Enable vsync */
388                 Display* dpy = wxGetX11Display();
389                 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
390                 _vsync_enabled = true;
391         }
392 #endif
393
394 #ifdef DCPOMATIC_WINDOWS
395         if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
396                 /* Enable vsync */
397                 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
398                 if (swap) {
399                         swap (1);
400                         _vsync_enabled = true;
401                 }
402         }
403
404 #endif
405
406 #ifdef DCPOMATIC_OSX
407         /* Enable vsync */
408         GLint swapInterval = 1;
409         CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
410         _vsync_enabled = true;
411 #endif
412
413         glGenTextures (1, &_id);
414         check_gl_error ("glGenTextures");
415         glBindTexture (GL_TEXTURE_2D, _id);
416         check_gl_error ("glBindTexture");
417         glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
418         check_gl_error ("glPixelStorei");
419
420         while (true) {
421                 boost::mutex::scoped_lock lm (_playing_mutex);
422                 while (!_playing && !_one_shot) {
423                         _thread_work_condition.wait (lm);
424                 }
425                 lm.unlock ();
426
427                 if (_playing) {
428                         thread_playing ();
429                 } else if (_one_shot) {
430                         _one_shot = false;
431                         set_image_and_draw ();
432                 }
433
434                 boost::this_thread::interruption_point ();
435                 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
436         }
437
438         /* XXX: leaks _context, but that seems preferable to deleting it here
439          * without also deleting the wxGLCanvas.
440          */
441 }
442 catch (boost::thread_interrupted& e)
443 {
444         store_current ();
445 }
446
447
448 VideoView::NextFrameResult
449 GLVideoView::display_next_frame (bool non_blocking)
450 {
451         NextFrameResult const r = get_next_frame (non_blocking);
452         request_one_shot ();
453         return r;
454 }
455
456
457 void
458 GLVideoView::request_one_shot ()
459 {
460         boost::mutex::scoped_lock lm (_playing_mutex);
461         _one_shot = true;
462         _thread_work_condition.notify_all ();
463 }
464