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