Try to make the GL code a little clearer.
[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
28 /* This will only build on an new-enough wxWidgets: see the comment in gl_video_view.h */
29 #if wxCHECK_VERSION(3,1,0)
30
31 #include "film_viewer.h"
32 #include "wx_util.h"
33 #include "lib/butler.h"
34 #include "lib/cross.h"
35 #include "lib/dcpomatic_assert.h"
36 #include "lib/dcpomatic_log.h"
37 #include "lib/exceptions.h"
38 #include "lib/image.h"
39 #include "lib/player_video.h"
40 #include <boost/bind/bind.hpp>
41 #include <iostream>
42
43 #ifdef DCPOMATIC_OSX
44 #define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED
45 #include <OpenGL/OpenGL.h>
46 #include <OpenGL/gl3.h>
47 #endif
48
49 #ifdef DCPOMATIC_LINUX
50 #include <GL/glu.h>
51 #include <GL/glext.h>
52 #endif
53
54 #ifdef DCPOMATIC_WINDOWS
55 #include <GL/glu.h>
56 #include <GL/wglext.h>
57 #endif
58
59
60 using std::cout;
61 using std::shared_ptr;
62 using std::string;
63 using boost::optional;
64 #if BOOST_VERSION >= 106100
65 using namespace boost::placeholders;
66 #endif
67
68
69 static void
70 check_gl_error (char const * last)
71 {
72         GLenum const e = glGetError ();
73         if (e != GL_NO_ERROR) {
74                 throw GLError (last, e);
75         }
76 }
77
78
79 GLVideoView::GLVideoView (FilmViewer* viewer, wxWindow *parent)
80         : VideoView (viewer)
81         , _context (nullptr)
82         , _vsync_enabled (false)
83         , _playing (false)
84         , _one_shot (false)
85 {
86         wxGLAttributes attributes;
87         /* We don't need a depth buffer, and indeed there is apparently a bug with Windows/Intel HD 630
88          * which puts green lines over the OpenGL display if you have a non-zero depth buffer size.
89          * https://community.intel.com/t5/Graphics/Request-for-details-on-Intel-HD-630-green-lines-in-OpenGL-apps/m-p/1202179
90          */
91         attributes.PlatformDefaults().MinRGBA(8, 8, 8, 8).DoubleBuffer().Depth(0).EndList();
92         _canvas = new wxGLCanvas (
93                 parent, attributes, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE
94         );
95         _canvas->Bind (wxEVT_PAINT, boost::bind(&GLVideoView::update, this));
96         _canvas->Bind (wxEVT_SIZE, boost::bind(&GLVideoView::size_changed, this, _1));
97
98         _canvas->Bind (wxEVT_TIMER, boost::bind(&GLVideoView::check_for_butler_errors, this));
99         _timer.reset (new wxTimer(_canvas));
100         _timer->Start (2000);
101 }
102
103
104 void
105 GLVideoView::size_changed (wxSizeEvent const& ev)
106 {
107         auto const scale = _canvas->GetDPIScaleFactor();
108         int const width = std::round(ev.GetSize().GetWidth() * scale);
109         int const height = std::round(ev.GetSize().GetHeight() * scale);
110         _canvas_size = { width, height };
111         LOG_GENERAL("GLVideoView canvas size changed to %1x%2", width, height);
112         Sized ();
113 }
114
115
116 GLVideoView::~GLVideoView ()
117 {
118         boost::this_thread::disable_interruption dis;
119
120         try {
121                 _thread.interrupt ();
122                 _thread.join ();
123         } catch (...) {}
124 }
125
126 void
127 GLVideoView::check_for_butler_errors ()
128 {
129         if (!_viewer->butler()) {
130                 return;
131         }
132
133         try {
134                 _viewer->butler()->rethrow ();
135         } catch (DecodeError& e) {
136                 error_dialog (get(), e.what());
137         } catch (dcp::ReadError& e) {
138                 error_dialog (get(), wxString::Format(_("Could not read DCP: %s"), std_to_wx(e.what())));
139         }
140 }
141
142
143 /** Called from the UI thread */
144 void
145 GLVideoView::update ()
146 {
147         if (!_canvas->IsShownOnScreen()) {
148                 return;
149         }
150
151         /* It appears important to do this from the GUI thread; if we do it from the GL thread
152          * on Linux we get strange failures to create the context for any version of GL higher
153          * than 3.2.
154          */
155         ensure_context ();
156
157 #ifdef DCPOMATIC_OSX
158         /* macOS gives errors if we don't do this (and therefore [NSOpenGLContext setView:]) from the main thread */
159         if (!_setup_shaders_done) {
160                 setup_shaders ();
161                 _setup_shaders_done = true;
162         }
163 #endif
164
165         if (!_thread.joinable()) {
166                 _thread = boost::thread (boost::bind(&GLVideoView::thread, this));
167         }
168
169         request_one_shot ();
170
171         rethrow ();
172 }
173
174
175 static constexpr char vertex_source[] =
176 "#version 330 core\n"
177 "\n"
178 "layout (location = 0) in vec3 in_pos;\n"
179 "layout (location = 1) in vec2 in_tex_coord;\n"
180 "\n"
181 "out vec2 TexCoord;\n"
182 "\n"
183 "void main()\n"
184 "{\n"
185 "       gl_Position = vec4(in_pos, 1.0);\n"
186 "       TexCoord = in_tex_coord;\n"
187 "}\n";
188
189
190 /* Bicubic interpolation stolen from https://stackoverflow.com/questions/13501081/efficient-bicubic-filtering-code-in-glsl */
191 static constexpr char fragment_source[] =
192 "#version 330 core\n"
193 "\n"
194 "in vec2 TexCoord;\n"
195 "\n"
196 "uniform sampler2D texture_sampler;\n"
197 /* type = 0: draw outline content rectangle
198  * type = 1: draw XYZ image
199  * type = 2: draw RGB image
200  * See FragmentType enum below.
201  */
202 "uniform int type = 0;\n"
203 "uniform vec4 outline_content_colour;\n"
204 "uniform mat4 colour_conversion;\n"
205 "\n"
206 "out vec4 FragColor;\n"
207 "\n"
208 "vec4 cubic(float x)\n"
209 "\n"
210 "#define IN_GAMMA 2.2\n"
211 "#define OUT_GAMMA 0.384615385\n"       //  1 /  2.6
212 "#define DCI_COEFFICIENT 0.91655528\n"  // 48 / 53.37
213 "\n"
214 "{\n"
215 "    float x2 = x * x;\n"
216 "    float x3 = x2 * x;\n"
217 "    vec4 w;\n"
218 "    w.x =     -x3 + 3 * x2 - 3 * x + 1;\n"
219 "    w.y =  3 * x3 - 6 * x2         + 4;\n"
220 "    w.z = -3 * x3 + 3 * x2 + 3 * x + 1;\n"
221 "    w.w =  x3;\n"
222 "    return w / 6.f;\n"
223 "}\n"
224 "\n"
225 "vec4 texture_bicubic(sampler2D sampler, vec2 tex_coords)\n"
226 "{\n"
227 "   vec2 tex_size = textureSize(sampler, 0);\n"
228 "   vec2 inv_tex_size = 1.0 / tex_size;\n"
229 "\n"
230 "   tex_coords = tex_coords * tex_size - 0.5;\n"
231 "\n"
232 "   vec2 fxy = fract(tex_coords);\n"
233 "   tex_coords -= fxy;\n"
234 "\n"
235 "   vec4 xcubic = cubic(fxy.x);\n"
236 "   vec4 ycubic = cubic(fxy.y);\n"
237 "\n"
238 "   vec4 c = tex_coords.xxyy + vec2 (-0.5, +1.5).xyxy;\n"
239 "\n"
240 "   vec4 s = vec4(xcubic.xz + xcubic.yw, ycubic.xz + ycubic.yw);\n"
241 "   vec4 offset = c + vec4 (xcubic.yw, ycubic.yw) / s;\n"
242 "\n"
243 "   offset *= inv_tex_size.xxyy;\n"
244 "\n"
245 "   vec4 sample0 = texture(sampler, offset.xz);\n"
246 "   vec4 sample1 = texture(sampler, offset.yz);\n"
247 "   vec4 sample2 = texture(sampler, offset.xw);\n"
248 "   vec4 sample3 = texture(sampler, offset.yw);\n"
249 "\n"
250 "   float sx = s.x / (s.x + s.y);\n"
251 "   float sy = s.z / (s.z + s.w);\n"
252 "\n"
253 "   return mix(\n"
254 "          mix(sample3, sample2, sx), mix(sample1, sample0, sx)\n"
255 "          , sy);\n"
256 "}\n"
257 "\n"
258 "void main()\n"
259 "{\n"
260 "       switch (type) {\n"
261 "               case 0:\n"
262 "                       FragColor = outline_content_colour;\n"
263 "                       break;\n"
264 "               case 1:\n"
265 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
266 "                       FragColor.x = pow(FragColor.x, IN_GAMMA) / DCI_COEFFICIENT;\n"
267 "                       FragColor.y = pow(FragColor.y, IN_GAMMA) / DCI_COEFFICIENT;\n"
268 "                       FragColor.z = pow(FragColor.z, IN_GAMMA) / DCI_COEFFICIENT;\n"
269 "                       FragColor = colour_conversion * FragColor;\n"
270 "                       FragColor.x = pow(FragColor.x, OUT_GAMMA);\n"
271 "                       FragColor.y = pow(FragColor.y, OUT_GAMMA);\n"
272 "                       FragColor.z = pow(FragColor.z, OUT_GAMMA);\n"
273 "                       break;\n"
274 "               case 2:\n"
275 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
276 "                       break;\n"
277 "       }\n"
278 "}\n";
279
280
281 enum class FragmentType
282 {
283         OUTLINE_CONTENT = 0,
284         XYZ_IMAGE = 1,
285         RGB_IMAGE = 2,
286 };
287
288
289 void
290 GLVideoView::ensure_context ()
291 {
292         if (!_context) {
293                 wxGLContextAttrs attrs;
294                 attrs.PlatformDefaults().CoreProfile().OGLVersion(4, 1).EndList();
295                 _context = new wxGLContext (_canvas, nullptr, &attrs);
296                 if (!_context->IsOK()) {
297                         throw GLError ("Making GL context", -1);
298                 }
299         }
300 }
301
302
303 /* Offset and number of indices for the things in the indices array below */
304 static constexpr int indices_video_texture_offset = 0;
305 static constexpr int indices_video_texture_number = 6;
306 static constexpr int indices_subtitle_texture_offset = indices_video_texture_offset + indices_video_texture_number;
307 static constexpr int indices_subtitle_texture_number = 6;
308 static constexpr int indices_outline_content_offset = indices_subtitle_texture_offset + indices_subtitle_texture_number;
309 static constexpr int indices_outline_content_number = 8;
310
311 static constexpr unsigned int indices[] = {
312         0, 1, 3, // video texture triangle #1
313         1, 2, 3, // video texture triangle #2
314         4, 5, 7, // subtitle texture triangle #1
315         5, 6, 7, // subtitle texture triangle #2
316         8, 9,    // outline content line #1
317         9, 10,   // outline content line #2
318         10, 11,  // outline content line #3
319         11, 8,   // outline content line #4
320 };
321
322 /* Offsets of things in the GL_ARRAY_BUFFER */
323 static constexpr int array_buffer_video_offset = 0;
324 static constexpr int array_buffer_subtitle_offset = array_buffer_video_offset + 4 * 5 * sizeof(float);
325 static constexpr int array_buffer_outline_content_offset = array_buffer_subtitle_offset + 4 * 5 * sizeof(float);
326
327
328 void
329 GLVideoView::setup_shaders ()
330 {
331         DCPOMATIC_ASSERT (_canvas);
332         DCPOMATIC_ASSERT (_context);
333         auto r = _canvas->SetCurrent (*_context);
334         DCPOMATIC_ASSERT (r);
335
336 #ifdef DCPOMATIC_WINDOWS
337         r = glewInit();
338         if (r != GLEW_OK) {
339                 throw GLError(reinterpret_cast<char const*>(glewGetErrorString(r)));
340         }
341 #endif
342
343         auto get_information = [this](GLenum name) {
344                 auto s = glGetString (name);
345                 if (s) {
346                         _information[name] = std::string (reinterpret_cast<char const *>(s));
347                 }
348         };
349
350         get_information (GL_VENDOR);
351         get_information (GL_RENDERER);
352         get_information (GL_VERSION);
353         get_information (GL_SHADING_LANGUAGE_VERSION);
354
355         glGenVertexArrays(1, &_vao);
356         check_gl_error ("glGenVertexArrays");
357         GLuint vbo;
358         glGenBuffers(1, &vbo);
359         check_gl_error ("glGenBuffers");
360         GLuint ebo;
361         glGenBuffers(1, &ebo);
362         check_gl_error ("glGenBuffers");
363
364         glBindVertexArray(_vao);
365         check_gl_error ("glBindVertexArray");
366
367         glBindBuffer(GL_ARRAY_BUFFER, vbo);
368         check_gl_error ("glBindBuffer");
369
370         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
371         check_gl_error ("glBindBuffer");
372         glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
373         check_gl_error ("glBufferData");
374
375         /* position attribute to vertex shader (location = 0) */
376         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), nullptr);
377         glEnableVertexAttribArray(0);
378         /* texture coord attribute to vertex shader (location = 1) */
379         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
380         glEnableVertexAttribArray(1);
381         check_gl_error ("glEnableVertexAttribArray");
382
383         auto compile = [](GLenum type, char const* source) -> GLuint {
384                 auto shader = glCreateShader(type);
385                 DCPOMATIC_ASSERT (shader);
386                 GLchar const * src[] = { static_cast<GLchar const *>(source) };
387                 glShaderSource(shader, 1, src, nullptr);
388                 check_gl_error ("glShaderSource");
389                 glCompileShader(shader);
390                 check_gl_error ("glCompileShader");
391                 GLint ok;
392                 glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
393                 if (!ok) {
394                         GLint log_length;
395                         glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
396                         string log;
397                         if (log_length > 0) {
398                                 char* log_char = new char[log_length];
399                                 glGetShaderInfoLog(shader, log_length, nullptr, log_char);
400                                 log = string(log_char);
401                                 delete[] log_char;
402                         }
403                         glDeleteShader(shader);
404                         throw GLError(String::compose("Could not compile shader (%1)", log).c_str(), -1);
405                 }
406                 return shader;
407         };
408
409         auto vertex_shader = compile (GL_VERTEX_SHADER, vertex_source);
410         auto fragment_shader = compile (GL_FRAGMENT_SHADER, fragment_source);
411
412         auto program = glCreateProgram();
413         check_gl_error ("glCreateProgram");
414         glAttachShader (program, vertex_shader);
415         check_gl_error ("glAttachShader");
416         glAttachShader (program, fragment_shader);
417         check_gl_error ("glAttachShader");
418         glLinkProgram (program);
419         check_gl_error ("glLinkProgram");
420         GLint ok;
421         glGetProgramiv (program, GL_LINK_STATUS, &ok);
422         if (!ok) {
423                 GLint log_length;
424                 glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
425                 string log;
426                 if (log_length > 0) {
427                         char* log_char = new char[log_length];
428                         glGetProgramInfoLog(program, log_length, nullptr, log_char);
429                         log = string(log_char);
430                         delete[] log_char;
431                 }
432                 glDeleteProgram (program);
433                 throw GLError(String::compose("Could not link shader (%1)", log).c_str(), -1);
434         }
435         glDeleteShader (vertex_shader);
436         glDeleteShader (fragment_shader);
437
438         glUseProgram (program);
439
440         _fragment_type = glGetUniformLocation (program, "type");
441         check_gl_error ("glGetUniformLocation");
442         set_outline_content_colour (program);
443
444         auto conversion = dcp::ColourConversion::rec709_to_xyz();
445         boost::numeric::ublas::matrix<double> matrix = conversion.xyz_to_rgb ();
446         GLfloat gl_matrix[] = {
447                 static_cast<float>(matrix(0, 0)), static_cast<float>(matrix(0, 1)), static_cast<float>(matrix(0, 2)), 0.0f,
448                 static_cast<float>(matrix(1, 0)), static_cast<float>(matrix(1, 1)), static_cast<float>(matrix(1, 2)), 0.0f,
449                 static_cast<float>(matrix(2, 0)), static_cast<float>(matrix(2, 1)), static_cast<float>(matrix(2, 2)), 0.0f,
450                 0.0f, 0.0f, 0.0f, 1.0f
451                 };
452
453         auto colour_conversion = glGetUniformLocation (program, "colour_conversion");
454         check_gl_error ("glGetUniformLocation");
455         glUniformMatrix4fv (colour_conversion, 1, GL_TRUE, gl_matrix);
456
457         glLineWidth (1.0f);
458         check_gl_error ("glLineWidth");
459         glEnable (GL_BLEND);
460         check_gl_error ("glEnable");
461         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
462         check_gl_error ("glBlendFunc");
463
464         /* Reserve space for the GL_ARRAY_BUFFER */
465         glBufferData(GL_ARRAY_BUFFER, 12 * 5 * sizeof(float), nullptr, GL_STATIC_DRAW);
466         check_gl_error ("glBufferData");
467 }
468
469
470 void
471 GLVideoView::set_outline_content_colour (GLuint program)
472 {
473         auto uniform = glGetUniformLocation (program, "outline_content_colour");
474         check_gl_error ("glGetUniformLocation");
475         auto colour = outline_content_colour ();
476         glUniform4f (uniform, colour.Red() / 255.0f, colour.Green() / 255.0f, colour.Blue() / 255.0f, 1.0f);
477         check_gl_error ("glUniform4f");
478 }
479
480
481 void
482 GLVideoView::draw ()
483 {
484         auto pad = pad_colour();
485         glClearColor(pad.Red() / 255.0, pad.Green() / 255.0, pad.Blue() / 255.0, 1.0);
486         glClear (GL_COLOR_BUFFER_BIT);
487         check_gl_error ("glClear");
488
489         auto const size = _canvas_size.load();
490         int const width = size.GetWidth();
491         int const height = size.GetHeight();
492
493         if (width < 64 || height < 0) {
494                 return;
495         }
496
497         glViewport (0, 0, width, height);
498         check_gl_error ("glViewport");
499
500         glBindVertexArray(_vao);
501         check_gl_error ("glBindVertexArray");
502         glUniform1i(_fragment_type, static_cast<GLint>(_optimise_for_j2k ? FragmentType::XYZ_IMAGE : FragmentType::RGB_IMAGE));
503         _video_texture->bind();
504         glDrawElements (GL_TRIANGLES, indices_video_texture_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_video_texture_offset * sizeof(int)));
505         if (_have_subtitle_to_render) {
506                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::RGB_IMAGE));
507                 _subtitle_texture->bind();
508                 glDrawElements (GL_TRIANGLES, indices_subtitle_texture_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_subtitle_texture_offset * sizeof(int)));
509         }
510         if (_viewer->outline_content()) {
511                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::OUTLINE_CONTENT));
512                 glDrawElements (GL_LINES, indices_outline_content_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_outline_content_offset * sizeof(int)));
513                 check_gl_error ("glDrawElements");
514         }
515
516         glFlush();
517         check_gl_error ("glFlush");
518
519         _canvas->SwapBuffers();
520 }
521
522
523 void
524 GLVideoView::set_image (shared_ptr<const PlayerVideo> pv)
525 {
526         shared_ptr<const Image> video = _optimise_for_j2k ? pv->raw_image() : pv->image(boost::bind(&PlayerVideo::force, AV_PIX_FMT_RGB24), VideoRange::FULL, true);
527
528         /* Only the player's black frames should be aligned at this stage, so this should
529          * almost always have no work to do.
530          */
531         video = Image::ensure_alignment (video, Image::Alignment::COMPACT);
532
533         /** If _optimise_for_j2k is true we render a XYZ image, doing the colourspace
534          *  conversion, scaling and video range conversion in the GL shader.
535          *  Otherwise we render a RGB image without any shader-side processing.
536          */
537
538         /* XXX: video range conversion */
539
540         _video_texture->set (video);
541
542         auto const text = pv->text();
543         _have_subtitle_to_render = static_cast<bool>(text) && _optimise_for_j2k;
544         if (_have_subtitle_to_render) {
545                 /* opt: only do this if it's a new subtitle? */
546                 DCPOMATIC_ASSERT (text->image->alignment() == Image::Alignment::COMPACT);
547                 _subtitle_texture->set (text->image);
548         }
549
550
551         auto const canvas_size = _canvas_size.load();
552         int const canvas_width = canvas_size.GetWidth();
553         int const canvas_height = canvas_size.GetHeight();
554         auto const inter_position = player_video().first->inter_position();
555         auto const inter_size = player_video().first->inter_size();
556         auto const out_size = player_video().first->out_size();
557
558         auto x_offset = std::max(0, (canvas_width - out_size.width) / 2);
559         auto y_offset = std::max(0, (canvas_height - out_size.height) / 2);
560
561         _last_canvas_size.set_next (canvas_size);
562         _last_video_size.set_next (video->size());
563         _last_inter_position.set_next (inter_position);
564         _last_inter_size.set_next (inter_size);
565         _last_out_size.set_next (out_size);
566
567         class Rectangle
568         {
569         public:
570                 Rectangle (wxSize canvas_size, float x, float y, dcp::Size size)
571                         : _canvas_size (canvas_size)
572                 {
573                         auto const x1 = x_pixels_to_gl(x);
574                         auto const y1 = y_pixels_to_gl(y);
575                         auto const x2 = x_pixels_to_gl(x + size.width);
576                         auto const y2 = y_pixels_to_gl(y + size.height);
577
578                         /* The texture coordinates here have to account for the fact that when we put images into the texture OpenGL
579                          * expected us to start at the lower left but we actually started at the top left.  So although the
580                          * top of the texture is at 1.0 we pretend it's the other way round.
581                          */
582
583                         // bottom right
584                         _vertices[0] = x2;
585                         _vertices[1] = y2;
586                         _vertices[2] = 0.0f;
587                         _vertices[3] = 1.0f;
588                         _vertices[4] = 1.0f;
589
590                         // top right
591                         _vertices[5] = x2;
592                         _vertices[6] = y1;
593                         _vertices[7] = 0.0f;
594                         _vertices[8] = 1.0f;
595                         _vertices[9] = 0.0f;
596
597                         // top left
598                         _vertices[10] = x1;
599                         _vertices[11] = y1;
600                         _vertices[12] = 0.0f;
601                         _vertices[13] = 0.0f;
602                         _vertices[14] = 0.0f;
603
604                         // bottom left
605                         _vertices[15] = x1;
606                         _vertices[16] = y2;
607                         _vertices[17] = 0.0f;
608                         _vertices[18] = 0.0f;
609                         _vertices[19] = 1.0f;
610                 }
611
612                 float const * vertices () const {
613                         return _vertices;
614                 }
615
616                 int const size () const {
617                         return sizeof(_vertices);
618                 }
619
620         private:
621                 /* @param x x position in pixels where 0 is left and canvas_width is right on screen */
622                 float x_pixels_to_gl(int x) const {
623                         return (x * 2.0f / _canvas_size.GetWidth()) - 1.0f;
624                 }
625
626                 /* @param y y position in pixels where 0 is top and canvas_height is bottom on screen */
627                 float y_pixels_to_gl(int y) const {
628                         return 1.0f - (y * 2.0f / _canvas_size.GetHeight());
629                 }
630
631                 wxSize _canvas_size;
632                 float _vertices[20];
633         };
634
635         if (_last_canvas_size.changed() || _last_inter_position.changed() || _last_inter_size.changed() || _last_out_size.changed()) {
636
637                 const auto video = _optimise_for_j2k ?
638                         Rectangle(canvas_size, inter_position.x + x_offset, inter_position.y + y_offset, inter_size)
639                         : Rectangle(canvas_size, x_offset, y_offset, out_size);
640
641                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_video_offset, video.size(), video.vertices());
642                 check_gl_error ("glBufferSubData (video)");
643
644                 const auto outline_content = Rectangle(canvas_size, inter_position.x + x_offset, inter_position.y + y_offset, inter_size);
645                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_outline_content_offset, outline_content.size(), outline_content.vertices());
646                 check_gl_error ("glBufferSubData (outline_content)");
647         }
648
649         if (_have_subtitle_to_render) {
650                 const auto subtitle = Rectangle(canvas_size, inter_position.x + x_offset + text->position.x, inter_position.y + y_offset + text->position.y, text->image->size());
651                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_subtitle_offset, subtitle.size(), subtitle.vertices());
652                 check_gl_error ("glBufferSubData (subtitle)");
653         }
654
655         /* opt: where should these go? */
656
657         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
658         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
659         check_gl_error ("glTexParameteri");
660
661         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
662         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
663         check_gl_error ("glTexParameterf");
664 }
665
666
667 void
668 GLVideoView::start ()
669 {
670         VideoView::start ();
671
672         boost::mutex::scoped_lock lm (_playing_mutex);
673         _playing = true;
674         _thread_work_condition.notify_all ();
675 }
676
677 void
678 GLVideoView::stop ()
679 {
680         boost::mutex::scoped_lock lm (_playing_mutex);
681         _playing = false;
682 }
683
684
685 void
686 GLVideoView::thread_playing ()
687 {
688         if (length() != dcpomatic::DCPTime()) {
689                 auto const next = position() + one_video_frame();
690
691                 if (next >= length()) {
692                         _viewer->finished ();
693                         return;
694                 }
695
696                 get_next_frame (false);
697                 set_image_and_draw ();
698         }
699
700         while (true) {
701                 optional<int> n = time_until_next_frame();
702                 if (!n || *n > 5) {
703                         break;
704                 }
705                 get_next_frame (true);
706                 add_dropped ();
707         }
708 }
709
710
711 void
712 GLVideoView::set_image_and_draw ()
713 {
714         auto pv = player_video().first;
715         if (pv) {
716                 set_image (pv);
717         }
718
719         draw ();
720
721         if (pv) {
722                 _viewer->image_changed (pv);
723         }
724 }
725
726
727 void
728 GLVideoView::thread ()
729 try
730 {
731         start_of_thread ("GLVideoView");
732
733 #if defined(DCPOMATIC_OSX)
734         /* Without this we see errors like
735          * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
736          */
737         WXGLSetCurrentContext (_context->GetWXGLContext());
738 #else
739         if (!_setup_shaders_done) {
740                 setup_shaders ();
741                 _setup_shaders_done = true;
742         }
743 #endif
744
745 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
746         if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
747                 /* Enable vsync */
748                 Display* dpy = wxGetX11Display();
749                 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
750                 _vsync_enabled = true;
751         }
752 #endif
753
754 #ifdef DCPOMATIC_WINDOWS
755         if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
756                 /* Enable vsync */
757                 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
758                 if (swap) {
759                         swap (1);
760                         _vsync_enabled = true;
761                 }
762         }
763
764 #endif
765
766 #ifdef DCPOMATIC_OSX
767         /* Enable vsync */
768         GLint swapInterval = 1;
769         CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
770         _vsync_enabled = true;
771 #endif
772
773         _video_texture.reset(new Texture(_optimise_for_j2k ? 2 : 1));
774         _subtitle_texture.reset(new Texture(1));
775
776         while (true) {
777                 boost::mutex::scoped_lock lm (_playing_mutex);
778                 while (!_playing && !_one_shot) {
779                         _thread_work_condition.wait (lm);
780                 }
781                 lm.unlock ();
782
783                 if (_playing) {
784                         thread_playing ();
785                 } else if (_one_shot) {
786                         _one_shot = false;
787                         set_image_and_draw ();
788                 }
789
790                 boost::this_thread::interruption_point ();
791                 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
792         }
793
794         /* XXX: leaks _context, but that seems preferable to deleting it here
795          * without also deleting the wxGLCanvas.
796          */
797 }
798 catch (...)
799 {
800         store_current ();
801 }
802
803
804 VideoView::NextFrameResult
805 GLVideoView::display_next_frame (bool non_blocking)
806 {
807         NextFrameResult const r = get_next_frame (non_blocking);
808         request_one_shot ();
809         return r;
810 }
811
812
813 void
814 GLVideoView::request_one_shot ()
815 {
816         boost::mutex::scoped_lock lm (_playing_mutex);
817         _one_shot = true;
818         _thread_work_condition.notify_all ();
819 }
820
821
822 Texture::Texture (GLint unpack_alignment)
823         : _unpack_alignment (unpack_alignment)
824 {
825         glGenTextures (1, &_name);
826         check_gl_error ("glGenTextures");
827 }
828
829
830 Texture::~Texture ()
831 {
832         glDeleteTextures (1, &_name);
833 }
834
835
836 void
837 Texture::bind ()
838 {
839         glBindTexture(GL_TEXTURE_2D, _name);
840         check_gl_error ("glBindTexture");
841 }
842
843
844 void
845 Texture::set (shared_ptr<const Image> image)
846 {
847         auto const create = !_size || image->size() != _size;
848         _size = image->size();
849
850         glPixelStorei (GL_UNPACK_ALIGNMENT, _unpack_alignment);
851         check_gl_error ("glPixelStorei");
852
853         DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
854
855         GLint internal_format;
856         GLenum format;
857         GLenum type;
858
859         switch (image->pixel_format()) {
860         case AV_PIX_FMT_BGRA:
861                 internal_format = GL_RGBA8;
862                 format = GL_BGRA;
863                 type = GL_UNSIGNED_BYTE;
864                 break;
865         case AV_PIX_FMT_RGBA:
866                 internal_format = GL_RGBA8;
867                 format = GL_RGBA;
868                 type = GL_UNSIGNED_BYTE;
869                 break;
870         case AV_PIX_FMT_RGB24:
871                 internal_format = GL_RGBA8;
872                 format = GL_RGB;
873                 type = GL_UNSIGNED_BYTE;
874                 break;
875         case AV_PIX_FMT_XYZ12:
876                 internal_format = GL_RGBA12;
877                 format = GL_RGB;
878                 type = GL_UNSIGNED_SHORT;
879                 break;
880         default:
881                 throw PixelFormatError ("Texture::set", image->pixel_format());
882         }
883
884         bind ();
885
886         if (create) {
887                 glTexImage2D (GL_TEXTURE_2D, 0, internal_format, _size->width, _size->height, 0, format, type, image->data()[0]);
888                 check_gl_error ("glTexImage2D");
889         } else {
890                 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _size->width, _size->height, format, type, image->data()[0]);
891                 check_gl_error ("glTexSubImage2D");
892         }
893 }
894
895 #endif