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