Extract indices array and make some offset constants.
[dcpomatic.git] / src / wx / gl_video_view.cc
1 /*
2     Copyright (C) 2018-2021 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
22 #ifdef DCPOMATIC_WINDOWS
23 #include <GL/glew.h>
24 #endif
25
26 #include "gl_video_view.h"
27 #include "film_viewer.h"
28 #include "wx_util.h"
29 #include "lib/image.h"
30 #include "lib/dcpomatic_assert.h"
31 #include "lib/exceptions.h"
32 #include "lib/cross.h"
33 #include "lib/player_video.h"
34 #include "lib/butler.h"
35 #include <boost/bind/bind.hpp>
36 #include <iostream>
37
38 #ifdef DCPOMATIC_OSX
39 #define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED
40 #include <OpenGL/OpenGL.h>
41 #include <OpenGL/gl3.h>
42 #endif
43
44 #ifdef DCPOMATIC_LINUX
45 #include <GL/glu.h>
46 #include <GL/glext.h>
47 #endif
48
49 #ifdef DCPOMATIC_WINDOWS
50 #include <GL/glu.h>
51 #include <GL/wglext.h>
52 #endif
53
54
55 using std::cout;
56 using std::shared_ptr;
57 using std::string;
58 using boost::optional;
59 #if BOOST_VERSION >= 106100
60 using namespace boost::placeholders;
61 #endif
62
63
64 static void
65 check_gl_error (char const * last)
66 {
67         GLenum const e = glGetError ();
68         if (e != GL_NO_ERROR) {
69                 throw GLError (last, e);
70         }
71 }
72
73
74 GLVideoView::GLVideoView (FilmViewer* viewer, wxWindow *parent)
75         : VideoView (viewer)
76         , _context (nullptr)
77         , _have_storage (false)
78         , _vsync_enabled (false)
79         , _playing (false)
80         , _one_shot (false)
81 {
82         wxGLAttributes attributes;
83         /* We don't need a depth buffer, and indeed there is apparently a bug with Windows/Intel HD 630
84          * which puts green lines over the OpenGL display if you have a non-zero depth buffer size.
85          * https://community.intel.com/t5/Graphics/Request-for-details-on-Intel-HD-630-green-lines-in-OpenGL-apps/m-p/1202179
86          */
87         attributes.PlatformDefaults().MinRGBA(8, 8, 8, 8).DoubleBuffer().Depth(0).EndList();
88         _canvas = new wxGLCanvas (
89                 parent, attributes, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE
90         );
91         _canvas->Bind (wxEVT_PAINT, boost::bind(&GLVideoView::update, this));
92         _canvas->Bind (wxEVT_SIZE, boost::bind(&GLVideoView::size_changed, this, _1));
93
94         _canvas->Bind (wxEVT_TIMER, boost::bind(&GLVideoView::check_for_butler_errors, this));
95         _timer.reset (new wxTimer(_canvas));
96         _timer->Start (2000);
97 }
98
99
100 void
101 GLVideoView::size_changed (wxSizeEvent const& ev)
102 {
103         _canvas_size = ev.GetSize ();
104         Sized ();
105 }
106
107
108
109 GLVideoView::~GLVideoView ()
110 {
111         boost::this_thread::disable_interruption dis;
112
113         try {
114                 _thread.interrupt ();
115                 _thread.join ();
116         } catch (...) {}
117
118         glDeleteTextures (1, &_video_texture);
119 }
120
121 void
122 GLVideoView::check_for_butler_errors ()
123 {
124         if (!_viewer->butler()) {
125                 return;
126         }
127
128         try {
129                 _viewer->butler()->rethrow ();
130         } catch (DecodeError& e) {
131                 error_dialog (get(), e.what());
132         } catch (dcp::ReadError& e) {
133                 error_dialog (get(), wxString::Format(_("Could not read DCP: %s"), std_to_wx(e.what())));
134         }
135 }
136
137
138 /** Called from the UI thread */
139 void
140 GLVideoView::update ()
141 {
142         if (!_canvas->IsShownOnScreen()) {
143                 return;
144         }
145
146         /* It appears important to do this from the GUI thread; if we do it from the GL thread
147          * on Linux we get strange failures to create the context for any version of GL higher
148          * than 3.2.
149          */
150         ensure_context ();
151
152 #ifdef DCPOMATIC_OSX
153         /* macOS gives errors if we don't do this (and therefore [NSOpenGLContext setView:]) from the main thread */
154         if (!_setup_shaders_done) {
155                 setup_shaders ();
156                 _setup_shaders_done = true;
157         }
158 #endif
159
160         if (!_thread.joinable()) {
161                 _thread = boost::thread (boost::bind(&GLVideoView::thread, this));
162         }
163
164         request_one_shot ();
165
166         rethrow ();
167 }
168
169
170 static constexpr char vertex_source[] =
171 "#version 330 core\n"
172 "\n"
173 "layout (location = 0) in vec3 in_pos;\n"
174 "layout (location = 1) in vec2 in_tex_coord;\n"
175 "\n"
176 "out vec2 TexCoord;\n"
177 "\n"
178 "void main()\n"
179 "{\n"
180 "       gl_Position = vec4(in_pos, 1.0);\n"
181 "       TexCoord = in_tex_coord;\n"
182 "}\n";
183
184
185 /* Bicubic interpolation stolen from https://stackoverflow.com/questions/13501081/efficient-bicubic-filtering-code-in-glsl */
186 static constexpr char fragment_source[] =
187 "#version 330 core\n"
188 "\n"
189 "in vec2 TexCoord;\n"
190 "\n"
191 "uniform sampler2D texture_sampler;\n"
192 /* type = 0: draw border
193  * type = 1: draw XYZ image
194  * type = 2: draw RGB image
195  */
196 "uniform int type = 0;\n"
197 "uniform vec4 border_colour;\n"
198 "uniform mat4 colour_conversion;\n"
199 "\n"
200 "out vec4 FragColor;\n"
201 "\n"
202 "vec4 cubic(float x)\n"
203 "\n"
204 "#define IN_GAMMA 2.2\n"
205 "#define OUT_GAMMA 0.384615385\n"       //  1 /  2.6
206 "#define DCI_COEFFICIENT 0.91655528\n"  // 48 / 53.37
207 "\n"
208 "{\n"
209 "    float x2 = x * x;\n"
210 "    float x3 = x2 * x;\n"
211 "    vec4 w;\n"
212 "    w.x =     -x3 + 3 * x2 - 3 * x + 1;\n"
213 "    w.y =  3 * x3 - 6 * x2         + 4;\n"
214 "    w.z = -3 * x3 + 3 * x2 + 3 * x + 1;\n"
215 "    w.w =  x3;\n"
216 "    return w / 6.f;\n"
217 "}\n"
218 "\n"
219 "vec4 texture_bicubic(sampler2D sampler, vec2 tex_coords)\n"
220 "{\n"
221 "   vec2 tex_size = textureSize(sampler, 0);\n"
222 "   vec2 inv_tex_size = 1.0 / tex_size;\n"
223 "\n"
224 "   tex_coords = tex_coords * tex_size - 0.5;\n"
225 "\n"
226 "   vec2 fxy = fract(tex_coords);\n"
227 "   tex_coords -= fxy;\n"
228 "\n"
229 "   vec4 xcubic = cubic(fxy.x);\n"
230 "   vec4 ycubic = cubic(fxy.y);\n"
231 "\n"
232 "   vec4 c = tex_coords.xxyy + vec2 (-0.5, +1.5).xyxy;\n"
233 "\n"
234 "   vec4 s = vec4(xcubic.xz + xcubic.yw, ycubic.xz + ycubic.yw);\n"
235 "   vec4 offset = c + vec4 (xcubic.yw, ycubic.yw) / s;\n"
236 "\n"
237 "   offset *= inv_tex_size.xxyy;\n"
238 "\n"
239 "   vec4 sample0 = texture(sampler, offset.xz);\n"
240 "   vec4 sample1 = texture(sampler, offset.yz);\n"
241 "   vec4 sample2 = texture(sampler, offset.xw);\n"
242 "   vec4 sample3 = texture(sampler, offset.yw);\n"
243 "\n"
244 "   float sx = s.x / (s.x + s.y);\n"
245 "   float sy = s.z / (s.z + s.w);\n"
246 "\n"
247 "   return mix(\n"
248 "          mix(sample3, sample2, sx), mix(sample1, sample0, sx)\n"
249 "          , sy);\n"
250 "}\n"
251 "\n"
252 "void main()\n"
253 "{\n"
254 "       switch (type) {\n"
255 "               case 0:\n"
256 "                       FragColor = border_colour;\n"
257 "                       break;\n"
258 "               case 1:\n"
259 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
260 "                       FragColor.x = pow(FragColor.x, IN_GAMMA) / DCI_COEFFICIENT;\n"
261 "                       FragColor.y = pow(FragColor.y, IN_GAMMA) / DCI_COEFFICIENT;\n"
262 "                       FragColor.z = pow(FragColor.z, IN_GAMMA) / DCI_COEFFICIENT;\n"
263 "                       FragColor = colour_conversion * FragColor;\n"
264 "                       FragColor.x = pow(FragColor.x, OUT_GAMMA);\n"
265 "                       FragColor.y = pow(FragColor.y, OUT_GAMMA);\n"
266 "                       FragColor.z = pow(FragColor.z, OUT_GAMMA);\n"
267 "                       break;\n"
268 "               case 2:\n"
269 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
270 "                       break;\n"
271 "       }\n"
272 "}\n";
273
274
275 void
276 GLVideoView::ensure_context ()
277 {
278         if (!_context) {
279                 wxGLContextAttrs attrs;
280                 attrs.PlatformDefaults().CoreProfile().OGLVersion(4, 1).EndList();
281                 _context = new wxGLContext (_canvas, nullptr, &attrs);
282                 if (!_context->IsOK()) {
283                         throw GLError ("Making GL context", -1);
284                 }
285         }
286 }
287
288
289 /* Offset of video texture triangles in indices */
290 static constexpr int indices_video_texture = 0;
291 /* Offset of border lines in indices */
292 static constexpr int indices_border = 6;
293
294 static constexpr unsigned int indices[] = {
295         0, 1, 3, // video texture triangle #1
296         1, 2, 3, // video texture triangle #2
297         4, 5,    // border line #1
298         5, 6,    // border line #2
299         6, 7,    // border line #3
300         7, 4,    // border line #4
301 };
302
303
304 void
305 GLVideoView::setup_shaders ()
306 {
307         DCPOMATIC_ASSERT (_canvas);
308         DCPOMATIC_ASSERT (_context);
309         auto r = _canvas->SetCurrent (*_context);
310         DCPOMATIC_ASSERT (r);
311
312 #ifdef DCPOMATIC_WINDOWS
313         r = glewInit();
314         if (r != GLEW_OK) {
315                 throw GLError(reinterpret_cast<char const*>(glewGetErrorString(r)));
316         }
317 #endif
318
319         auto get_information = [this](GLenum name) {
320                 auto s = glGetString (name);
321                 if (s) {
322                         _information[name] = std::string (reinterpret_cast<char const *>(s));
323                 }
324         };
325
326         get_information (GL_VENDOR);
327         get_information (GL_RENDERER);
328         get_information (GL_VERSION);
329         get_information (GL_SHADING_LANGUAGE_VERSION);
330
331         glGenVertexArrays(1, &_vao);
332         check_gl_error ("glGenVertexArrays");
333         GLuint vbo;
334         glGenBuffers(1, &vbo);
335         check_gl_error ("glGenBuffers");
336         GLuint ebo;
337         glGenBuffers(1, &ebo);
338         check_gl_error ("glGenBuffers");
339
340         glBindVertexArray(_vao);
341         check_gl_error ("glBindVertexArray");
342
343         glBindBuffer(GL_ARRAY_BUFFER, vbo);
344         check_gl_error ("glBindBuffer");
345
346         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
347         check_gl_error ("glBindBuffer");
348         glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
349         check_gl_error ("glBufferData");
350
351         /* position attribute to vertex shader (location = 0) */
352         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), nullptr);
353         glEnableVertexAttribArray(0);
354         /* texture coord attribute to vertex shader (location = 1) */
355         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
356         glEnableVertexAttribArray(1);
357         check_gl_error ("glEnableVertexAttribArray");
358
359         auto compile = [](GLenum type, char const* source) -> GLuint {
360                 auto shader = glCreateShader(type);
361                 DCPOMATIC_ASSERT (shader);
362                 GLchar const * src[] = { static_cast<GLchar const *>(source) };
363                 glShaderSource(shader, 1, src, nullptr);
364                 check_gl_error ("glShaderSource");
365                 glCompileShader(shader);
366                 check_gl_error ("glCompileShader");
367                 GLint ok;
368                 glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
369                 if (!ok) {
370                         GLint log_length;
371                         glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
372                         string log;
373                         if (log_length > 0) {
374                                 char* log_char = new char[log_length];
375                                 glGetShaderInfoLog(shader, log_length, nullptr, log_char);
376                                 log = string(log_char);
377                                 delete[] log_char;
378                         }
379                         glDeleteShader(shader);
380                         throw GLError(String::compose("Could not compile shader (%1)", log).c_str(), -1);
381                 }
382                 return shader;
383         };
384
385         auto vertex_shader = compile (GL_VERTEX_SHADER, vertex_source);
386         auto fragment_shader = compile (GL_FRAGMENT_SHADER, fragment_source);
387
388         auto program = glCreateProgram();
389         check_gl_error ("glCreateProgram");
390         glAttachShader (program, vertex_shader);
391         check_gl_error ("glAttachShader");
392         glAttachShader (program, fragment_shader);
393         check_gl_error ("glAttachShader");
394         glLinkProgram (program);
395         check_gl_error ("glLinkProgram");
396         GLint ok;
397         glGetProgramiv (program, GL_LINK_STATUS, &ok);
398         if (!ok) {
399                 GLint log_length;
400                 glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
401                 string log;
402                 if (log_length > 0) {
403                         char* log_char = new char[log_length];
404                         glGetProgramInfoLog(program, log_length, nullptr, log_char);
405                         log = string(log_char);
406                         delete[] log_char;
407                 }
408                 glDeleteProgram (program);
409                 throw GLError(String::compose("Could not link shader (%1)", log).c_str(), -1);
410         }
411         glDeleteShader (vertex_shader);
412         glDeleteShader (fragment_shader);
413
414         glUseProgram (program);
415
416         _fragment_type = glGetUniformLocation (program, "type");
417         check_gl_error ("glGetUniformLocation");
418         set_border_colour (program);
419
420         auto conversion = dcp::ColourConversion::rec709_to_xyz();
421         boost::numeric::ublas::matrix<double> matrix = conversion.xyz_to_rgb ();
422         GLfloat gl_matrix[] = {
423                 static_cast<float>(matrix(0, 0)), static_cast<float>(matrix(0, 1)), static_cast<float>(matrix(0, 2)), 0.0f,
424                 static_cast<float>(matrix(1, 0)), static_cast<float>(matrix(1, 1)), static_cast<float>(matrix(1, 2)), 0.0f,
425                 static_cast<float>(matrix(2, 0)), static_cast<float>(matrix(2, 1)), static_cast<float>(matrix(2, 2)), 0.0f,
426                 0.0f, 0.0f, 0.0f, 1.0f
427                 };
428
429         auto colour_conversion = glGetUniformLocation (program, "colour_conversion");
430         check_gl_error ("glGetUniformLocation");
431         glUniformMatrix4fv (colour_conversion, 1, GL_TRUE, gl_matrix);
432
433         glLineWidth (2.0f);
434 }
435
436
437 void
438 GLVideoView::set_border_colour (GLuint program)
439 {
440         auto uniform = glGetUniformLocation (program, "border_colour");
441         check_gl_error ("glGetUniformLocation");
442         auto colour = outline_content_colour ();
443         glUniform4f (uniform, colour.Red() / 255.0f, colour.Green() / 255.0f, colour.Blue() / 255.0f, 1.0f);
444         check_gl_error ("glUniform4f");
445 }
446
447
448 void
449 GLVideoView::draw (Position<int>, dcp::Size)
450 {
451         auto pad = pad_colour();
452         glClearColor(pad.Red() / 255.0, pad.Green() / 255.0, pad.Blue() / 255.0, 1.0);
453         glClear (GL_COLOR_BUFFER_BIT);
454         check_gl_error ("glClear");
455
456         auto const size = _canvas_size.load();
457         int const width = size.GetWidth();
458         int const height = size.GetHeight();
459
460         if (width < 64 || height < 0) {
461                 return;
462         }
463
464         glViewport (0, 0, width, height);
465         check_gl_error ("glViewport");
466
467         glBindTexture(GL_TEXTURE_2D, _video_texture);
468         glBindVertexArray(_vao);
469         check_gl_error ("glBindVertexArray");
470         glUniform1i(_fragment_type, _optimise_for_j2k ? 1 : 2);
471         glDrawElements (GL_TRIANGLES, 6, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_video_texture));
472         if (_viewer->outline_content()) {
473                 glUniform1i(_fragment_type, 1);
474                 glDrawElements (GL_LINES, 8, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_border * sizeof(int)));
475                 check_gl_error ("glDrawElements");
476         }
477
478         glFlush();
479         check_gl_error ("glFlush");
480
481         _canvas->SwapBuffers();
482 }
483
484
485 void
486 GLVideoView::set_image (shared_ptr<const PlayerVideo> pv)
487 {
488         auto image = _optimise_for_j2k ? pv->raw_image() : pv->image(bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), VideoRange::FULL, false, true);
489
490         DCPOMATIC_ASSERT (!image->aligned());
491
492         /** If _optimise_for_j2k is true we render a XYZ image, doing the colourspace
493          *  conversion, scaling and video range conversion in the GL shader.
494          *  Othewise we render a RGB image without any shader-side processing.
495          */
496
497         /* XXX: video range conversion */
498         /* XXX: subs */
499
500         if (image->size() != _size) {
501                 _have_storage = false;
502         }
503
504         _size = image->size ();
505         glPixelStorei (GL_UNPACK_ALIGNMENT, _optimise_for_j2k ? 2 : 1);
506         check_gl_error ("glPixelStorei");
507
508         auto const format = _optimise_for_j2k ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
509
510         if (_have_storage) {
511                 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _size->width, _size->height, GL_RGB, format, image->data()[0]);
512                 check_gl_error ("glTexSubImage2D");
513         } else {
514                 glTexImage2D (GL_TEXTURE_2D, 0, _optimise_for_j2k ? GL_RGBA12 : GL_RGBA8, _size->width, _size->height, 0, GL_RGB, format, image->data()[0]);
515                 check_gl_error ("glTexImage2D");
516
517                 auto const canvas_size = _canvas_size.load();
518                 int const canvas_width = canvas_size.GetWidth();
519                 int const canvas_height = canvas_size.GetHeight();
520
521                 float const image_x = float(_size->width) / canvas_width;
522                 float const image_y = float(_size->height) / canvas_height;
523
524                 auto x_pixels_to_gl = [canvas_width](int x) {
525                         return (x * 2.0f / canvas_width) - 1.0f;
526                 };
527
528                 auto y_pixels_to_gl = [canvas_height](int y) {
529                         return (y * 2.0f / canvas_height) - 1.0f;
530                 };
531
532                 auto inter_position = player_video().first->inter_position();
533                 auto inter_size = player_video().first->inter_size();
534
535                 float const border_x1 = x_pixels_to_gl (inter_position.x) + 1.0f - image_x;
536                 float const border_y1 = y_pixels_to_gl (inter_position.y) + 1.0f - image_y;
537                 float const border_x2 = x_pixels_to_gl (inter_position.x + inter_size.width) + 1.0f - image_x;
538                 float const border_y2 = y_pixels_to_gl (inter_position.y + inter_size.height) + 1.0f - image_y;
539
540                 float vertices[] = {
541                         // positions                  // texture coords
542                          image_x,   image_y,   0.0f,  1.0f, 0.0f,   // top right           (index 0)
543                          image_x,  -image_y,   0.0f,  1.0f, 1.0f,   // bottom right        (index 1)
544                         -image_x,  -image_y,   0.0f,  0.0f, 1.0f,   // bottom left         (index 2)
545                         -image_x,   image_y,   0.0f,  0.0f, 0.0f,   // top left            (index 3)
546                          border_x1, border_y1, 0.0f,  0.0f, 0.0f,   // border bottom left  (index 4)
547                          border_x1, border_y2, 0.0f,  0.0f, 0.0f,   // border top left     (index 5)
548                          border_x2, border_y2, 0.0f,  0.0f, 0.0f,   // border top right    (index 6)
549                          border_x2, border_y1, 0.0f,  0.0f, 0.0f,   // border bottom right (index 7)
550                 };
551
552                 /* Set the vertex shader's input data (GL_ARRAY_BUFFER) */
553                 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
554                 check_gl_error ("glBufferData");
555
556                 _have_storage = true;
557         }
558
559         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
560         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
561         check_gl_error ("glTexParameteri");
562
563         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
564         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
565         check_gl_error ("glTexParameterf");
566 }
567
568
569 void
570 GLVideoView::start ()
571 {
572         VideoView::start ();
573
574         boost::mutex::scoped_lock lm (_playing_mutex);
575         _playing = true;
576         _thread_work_condition.notify_all ();
577 }
578
579 void
580 GLVideoView::stop ()
581 {
582         boost::mutex::scoped_lock lm (_playing_mutex);
583         _playing = false;
584 }
585
586
587 void
588 GLVideoView::thread_playing ()
589 {
590         if (length() != dcpomatic::DCPTime()) {
591                 auto const next = position() + one_video_frame();
592
593                 if (next >= length()) {
594                         _viewer->finished ();
595                         return;
596                 }
597
598                 get_next_frame (false);
599                 set_image_and_draw ();
600         }
601
602         while (true) {
603                 optional<int> n = time_until_next_frame();
604                 if (!n || *n > 5) {
605                         break;
606                 }
607                 get_next_frame (true);
608                 add_dropped ();
609         }
610 }
611
612
613 void
614 GLVideoView::set_image_and_draw ()
615 {
616         auto pv = player_video().first;
617         if (pv) {
618                 set_image (pv);
619                 draw (pv->inter_position(), pv->inter_size());
620                 _viewer->image_changed (pv);
621         }
622 }
623
624
625 void
626 GLVideoView::thread ()
627 try
628 {
629         start_of_thread ("GLVideoView");
630
631 #if defined(DCPOMATIC_OSX)
632         /* Without this we see errors like
633          * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
634          */
635         WXGLSetCurrentContext (_context->GetWXGLContext());
636 #else
637         if (!_setup_shaders_done) {
638                 setup_shaders ();
639                 _setup_shaders_done = true;
640         }
641 #endif
642
643 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
644         if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
645                 /* Enable vsync */
646                 Display* dpy = wxGetX11Display();
647                 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
648                 _vsync_enabled = true;
649         }
650 #endif
651
652 #ifdef DCPOMATIC_WINDOWS
653         if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
654                 /* Enable vsync */
655                 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
656                 if (swap) {
657                         swap (1);
658                         _vsync_enabled = true;
659                 }
660         }
661
662 #endif
663
664 #ifdef DCPOMATIC_OSX
665         /* Enable vsync */
666         GLint swapInterval = 1;
667         CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
668         _vsync_enabled = true;
669 #endif
670
671         glGenTextures (1, &_video_texture);
672         check_gl_error ("glGenTextures");
673         glBindTexture (GL_TEXTURE_2D, _video_texture);
674         check_gl_error ("glBindTexture");
675
676         while (true) {
677                 boost::mutex::scoped_lock lm (_playing_mutex);
678                 while (!_playing && !_one_shot) {
679                         _thread_work_condition.wait (lm);
680                 }
681                 lm.unlock ();
682
683                 if (_playing) {
684                         thread_playing ();
685                 } else if (_one_shot) {
686                         _one_shot = false;
687                         set_image_and_draw ();
688                 }
689
690                 boost::this_thread::interruption_point ();
691                 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
692         }
693
694         /* XXX: leaks _context, but that seems preferable to deleting it here
695          * without also deleting the wxGLCanvas.
696          */
697 }
698 catch (...)
699 {
700         store_current ();
701 }
702
703
704 VideoView::NextFrameResult
705 GLVideoView::display_next_frame (bool non_blocking)
706 {
707         NextFrameResult const r = get_next_frame (non_blocking);
708         request_one_shot ();
709         return r;
710 }
711
712
713 void
714 GLVideoView::request_one_shot ()
715 {
716         boost::mutex::scoped_lock lm (_playing_mutex);
717         _one_shot = true;
718         _thread_work_condition.notify_all ();
719 }
720