4fc620936d9eb837bc22cefe089d1fb1f678a384
[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 crop guess rectangle
199  * type = 2: draw XYZ image
200  * type = 3: draw RGB image (with sRGB/Rec709 primaries)
201  * type = 4: draw RGB image (converting from Rec2020 primaries)
202  * See FragmentType enum below.
203  */
204 "uniform int type = 0;\n"
205 "uniform vec4 outline_content_colour;\n"
206 "uniform vec4 crop_guess_colour;\n"
207 "uniform mat4 xyz_rec709_colour_conversion;\n"
208 "uniform mat4 rec2020_rec709_colour_conversion;\n"
209 "\n"
210 "out vec4 FragColor;\n"
211 "\n"
212 "vec4 cubic(float x)\n"
213 "\n"
214 "#define IN_GAMMA 2.6\n"
215 "#define OUT_GAMMA 0.454545455\n"       //  1 /  2.2
216 "#define DCI_COEFFICIENT 0.91655528\n"  // 48 / 53.37
217 "\n"
218 "{\n"
219 "    float x2 = x * x;\n"
220 "    float x3 = x2 * x;\n"
221 "    vec4 w;\n"
222 "    w.x =     -x3 + 3 * x2 - 3 * x + 1;\n"
223 "    w.y =  3 * x3 - 6 * x2         + 4;\n"
224 "    w.z = -3 * x3 + 3 * x2 + 3 * x + 1;\n"
225 "    w.w =  x3;\n"
226 "    return w / 6.f;\n"
227 "}\n"
228 "\n"
229 "vec4 texture_bicubic(sampler2D sampler, vec2 tex_coords)\n"
230 "{\n"
231 "   vec2 tex_size = textureSize(sampler, 0);\n"
232 "   vec2 inv_tex_size = 1.0 / tex_size;\n"
233 "\n"
234 "   tex_coords = tex_coords * tex_size - 0.5;\n"
235 "\n"
236 "   vec2 fxy = fract(tex_coords);\n"
237 "   tex_coords -= fxy;\n"
238 "\n"
239 "   vec4 xcubic = cubic(fxy.x);\n"
240 "   vec4 ycubic = cubic(fxy.y);\n"
241 "\n"
242 "   vec4 c = tex_coords.xxyy + vec2 (-0.5, +1.5).xyxy;\n"
243 "\n"
244 "   vec4 s = vec4(xcubic.xz + xcubic.yw, ycubic.xz + ycubic.yw);\n"
245 "   vec4 offset = c + vec4 (xcubic.yw, ycubic.yw) / s;\n"
246 "\n"
247 "   offset *= inv_tex_size.xxyy;\n"
248 "\n"
249 "   vec4 sample0 = texture(sampler, offset.xz);\n"
250 "   vec4 sample1 = texture(sampler, offset.yz);\n"
251 "   vec4 sample2 = texture(sampler, offset.xw);\n"
252 "   vec4 sample3 = texture(sampler, offset.yw);\n"
253 "\n"
254 "   float sx = s.x / (s.x + s.y);\n"
255 "   float sy = s.z / (s.z + s.w);\n"
256 "\n"
257 "   return mix(\n"
258 "          mix(sample3, sample2, sx), mix(sample1, sample0, sx)\n"
259 "          , sy);\n"
260 "}\n"
261 "\n"
262 "void main()\n"
263 "{\n"
264 "       switch (type) {\n"
265 "               case 0:\n"
266 "                       FragColor = outline_content_colour;\n"
267 "                       break;\n"
268 "               case 1:\n"
269 "                       FragColor = crop_guess_colour;\n"
270 "                       break;\n"
271 "               case 2:\n"
272 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
273 "                       FragColor.x = pow(FragColor.x, IN_GAMMA) / DCI_COEFFICIENT;\n"
274 "                       FragColor.y = pow(FragColor.y, IN_GAMMA) / DCI_COEFFICIENT;\n"
275 "                       FragColor.z = pow(FragColor.z, IN_GAMMA) / DCI_COEFFICIENT;\n"
276 "                       FragColor = xyz_rec709_colour_conversion * FragColor;\n"
277 "                       FragColor.x = pow(FragColor.x, OUT_GAMMA);\n"
278 "                       FragColor.y = pow(FragColor.y, OUT_GAMMA);\n"
279 "                       FragColor.z = pow(FragColor.z, OUT_GAMMA);\n"
280 "                       break;\n"
281 "               case 3:\n"
282 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
283 "                       break;\n"
284 "               case 4:\n"
285 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
286 "                       FragColor = rec2020_rec709_colour_conversion * FragColor;\n"
287 "                       break;\n"
288 "       }\n"
289 "}\n";
290
291
292 enum class FragmentType
293 {
294         OUTLINE_CONTENT = 0,
295         CROP_GUESS = 1,
296         XYZ_IMAGE = 2,
297         REC709_IMAGE = 3,
298         REC2020_IMAGE = 4,
299 };
300
301
302 void
303 GLVideoView::ensure_context ()
304 {
305         if (!_context) {
306                 wxGLContextAttrs attrs;
307                 attrs.PlatformDefaults().CoreProfile().OGLVersion(4, 1).EndList();
308                 _context = new wxGLContext (_canvas, nullptr, &attrs);
309                 if (!_context->IsOK()) {
310                         throw GLError ("Making GL context", -1);
311                 }
312         }
313 }
314
315
316 /* Offset and number of indices for the things in the indices array below */
317 static constexpr int indices_video_texture_offset = 0;
318 static constexpr int indices_video_texture_number = 6;
319 static constexpr int indices_subtitle_texture_offset = indices_video_texture_offset + indices_video_texture_number;
320 static constexpr int indices_subtitle_texture_number = 6;
321 static constexpr int indices_outline_content_offset = indices_subtitle_texture_offset + indices_subtitle_texture_number;
322 static constexpr int indices_outline_content_number = 8;
323 static constexpr int indices_crop_guess_offset = indices_outline_content_offset + indices_outline_content_number;
324 static constexpr int indices_crop_guess_number = 8;
325
326 static constexpr unsigned int indices[] = {
327         0, 1, 3, // video texture triangle #1
328         1, 2, 3, // video texture triangle #2
329         4, 5, 7, // subtitle texture triangle #1
330         5, 6, 7, // subtitle texture triangle #2
331         8, 9,    // outline content line #1
332         9, 10,   // outline content line #2
333         10, 11,  // outline content line #3
334         11, 8,   // outline content line #4
335         12, 13,  // crop guess line #1
336         13, 14,  // crop guess line #2
337         14, 15,  // crop guess line #3
338         15, 12,  // crop guess line #4
339 };
340
341 /* Offsets of things in the GL_ARRAY_BUFFER */
342 static constexpr int array_buffer_video_offset = 0;
343 static constexpr int array_buffer_subtitle_offset = array_buffer_video_offset + 4 * 5 * sizeof(float);
344 static constexpr int array_buffer_outline_content_offset = array_buffer_subtitle_offset + 4 * 5 * sizeof(float);
345 static constexpr int array_buffer_crop_guess_offset = array_buffer_outline_content_offset + 4 * 5 * sizeof(float);
346
347
348 void
349 GLVideoView::setup_shaders ()
350 {
351         DCPOMATIC_ASSERT (_canvas);
352         DCPOMATIC_ASSERT (_context);
353         auto r = _canvas->SetCurrent (*_context);
354         DCPOMATIC_ASSERT (r);
355
356 #ifdef DCPOMATIC_WINDOWS
357         r = glewInit();
358         if (r != GLEW_OK) {
359                 throw GLError(reinterpret_cast<char const*>(glewGetErrorString(r)));
360         }
361 #endif
362
363         auto get_information = [this](GLenum name) {
364                 auto s = glGetString (name);
365                 if (s) {
366                         _information[name] = std::string (reinterpret_cast<char const *>(s));
367                 }
368         };
369
370         get_information (GL_VENDOR);
371         get_information (GL_RENDERER);
372         get_information (GL_VERSION);
373         get_information (GL_SHADING_LANGUAGE_VERSION);
374
375         glGenVertexArrays(1, &_vao);
376         check_gl_error ("glGenVertexArrays");
377         GLuint vbo;
378         glGenBuffers(1, &vbo);
379         check_gl_error ("glGenBuffers");
380         GLuint ebo;
381         glGenBuffers(1, &ebo);
382         check_gl_error ("glGenBuffers");
383
384         glBindVertexArray(_vao);
385         check_gl_error ("glBindVertexArray");
386
387         glBindBuffer(GL_ARRAY_BUFFER, vbo);
388         check_gl_error ("glBindBuffer");
389
390         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
391         check_gl_error ("glBindBuffer");
392         glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
393         check_gl_error ("glBufferData");
394
395         /* position attribute to vertex shader (location = 0) */
396         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), nullptr);
397         glEnableVertexAttribArray(0);
398         /* texture coord attribute to vertex shader (location = 1) */
399         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
400         glEnableVertexAttribArray(1);
401         check_gl_error ("glEnableVertexAttribArray");
402
403         auto compile = [](GLenum type, char const* source) -> GLuint {
404                 auto shader = glCreateShader(type);
405                 DCPOMATIC_ASSERT (shader);
406                 GLchar const * src[] = { static_cast<GLchar const *>(source) };
407                 glShaderSource(shader, 1, src, nullptr);
408                 check_gl_error ("glShaderSource");
409                 glCompileShader(shader);
410                 check_gl_error ("glCompileShader");
411                 GLint ok;
412                 glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
413                 if (!ok) {
414                         GLint log_length;
415                         glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
416                         string log;
417                         if (log_length > 0) {
418                                 std::vector<char> log_char(log_length);
419                                 glGetShaderInfoLog(shader, log_length, nullptr, log_char.data());
420                                 log = string(log_char.data());
421                         }
422                         glDeleteShader(shader);
423                         throw GLError(String::compose("Could not compile shader (%1)", log).c_str(), -1);
424                 }
425                 return shader;
426         };
427
428         auto vertex_shader = compile (GL_VERTEX_SHADER, vertex_source);
429         auto fragment_shader = compile (GL_FRAGMENT_SHADER, fragment_source);
430
431         auto program = glCreateProgram();
432         check_gl_error ("glCreateProgram");
433         glAttachShader (program, vertex_shader);
434         check_gl_error ("glAttachShader");
435         glAttachShader (program, fragment_shader);
436         check_gl_error ("glAttachShader");
437         glLinkProgram (program);
438         check_gl_error ("glLinkProgram");
439         GLint ok;
440         glGetProgramiv (program, GL_LINK_STATUS, &ok);
441         if (!ok) {
442                 GLint log_length;
443                 glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
444                 string log;
445                 if (log_length > 0) {
446                         std::vector<char> log_char(log_length);
447                         glGetProgramInfoLog(program, log_length, nullptr, log_char.data());
448                         log = string(log_char.data());
449                 }
450                 glDeleteProgram (program);
451                 throw GLError(String::compose("Could not link shader (%1)", log).c_str(), -1);
452         }
453         glDeleteShader (vertex_shader);
454         glDeleteShader (fragment_shader);
455
456         glUseProgram (program);
457
458         _fragment_type = glGetUniformLocation (program, "type");
459         check_gl_error ("glGetUniformLocation");
460         set_outline_content_colour (program);
461         set_crop_guess_colour (program);
462
463         auto ublas_to_gl = [](boost::numeric::ublas::matrix<double> const& ublas, GLfloat* gl) {
464                 gl[0] = static_cast<float>(ublas(0, 0));
465                 gl[1] = static_cast<float>(ublas(0, 1));
466                 gl[2] = static_cast<float>(ublas(0, 2));
467                 gl[3] = 0.0f;
468                 gl[4] = static_cast<float>(ublas(1, 0));
469                 gl[5] = static_cast<float>(ublas(1, 1));
470                 gl[6] = static_cast<float>(ublas(1, 2));
471                 gl[7] = 0.0f;
472                 gl[8] = static_cast<float>(ublas(2, 0));
473                 gl[9] = static_cast<float>(ublas(2, 1));
474                 gl[10] = static_cast<float>(ublas(2, 2));
475                 gl[11] = 0.0f;
476                 gl[12] = 0.0f;
477                 gl[13] = 0.0f;
478                 gl[14] = 0.0f;
479                 gl[15] = 1.0f;
480         };
481
482         {
483                 auto conversion = dcp::ColourConversion::rec709_to_xyz();
484                 boost::numeric::ublas::matrix<double> matrix = conversion.xyz_to_rgb ();
485                 GLfloat gl_matrix[16];
486                 ublas_to_gl(matrix, gl_matrix);
487
488                 auto xyz_rec709_colour_conversion = glGetUniformLocation(program, "xyz_rec709_colour_conversion");
489                 check_gl_error ("glGetUniformLocation");
490                 glUniformMatrix4fv(xyz_rec709_colour_conversion, 1, GL_TRUE, gl_matrix);
491         }
492
493         {
494                 auto xyz_rec709 = dcp::ColourConversion::rec709_to_xyz().xyz_to_rgb();
495                 auto rec2020_xyz = dcp::ColourConversion::rec2020_to_xyz().rgb_to_xyz();
496                 auto product = boost::numeric::ublas::prod(xyz_rec709, rec2020_xyz);
497
498                 GLfloat gl_matrix[16];
499                 ublas_to_gl(product, gl_matrix);
500
501                 auto rec2020_rec709_colour_conversion = glGetUniformLocation(program, "rec2020_rec709_colour_conversion");
502                 check_gl_error("glGetUniformLocation");
503                 glUniformMatrix4fv(rec2020_rec709_colour_conversion, 1, GL_TRUE, gl_matrix);
504         }
505
506         glLineWidth (1.0f);
507         check_gl_error ("glLineWidth");
508         glEnable (GL_BLEND);
509         check_gl_error ("glEnable");
510         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
511         check_gl_error ("glBlendFunc");
512
513         /* Reserve space for the GL_ARRAY_BUFFER */
514         glBufferData(GL_ARRAY_BUFFER, 16 * 5 * sizeof(float), nullptr, GL_STATIC_DRAW);
515         check_gl_error ("glBufferData");
516 }
517
518
519 void
520 GLVideoView::set_outline_content_colour (GLuint program)
521 {
522         auto uniform = glGetUniformLocation (program, "outline_content_colour");
523         check_gl_error ("glGetUniformLocation");
524         auto colour = outline_content_colour ();
525         glUniform4f (uniform, colour.Red() / 255.0f, colour.Green() / 255.0f, colour.Blue() / 255.0f, 1.0f);
526         check_gl_error ("glUniform4f");
527 }
528
529
530 void
531 GLVideoView::set_crop_guess_colour (GLuint program)
532 {
533         auto uniform = glGetUniformLocation (program, "crop_guess_colour");
534         check_gl_error ("glGetUniformLocation");
535         auto colour = crop_guess_colour ();
536         glUniform4f (uniform, colour.Red() / 255.0f, colour.Green() / 255.0f, colour.Blue() / 255.0f, 1.0f);
537         check_gl_error ("glUniform4f");
538 }
539
540
541 void
542 GLVideoView::draw ()
543 {
544         auto pad = pad_colour();
545         glClearColor(pad.Red() / 255.0, pad.Green() / 255.0, pad.Blue() / 255.0, 1.0);
546         glClear (GL_COLOR_BUFFER_BIT);
547         check_gl_error ("glClear");
548
549         auto const size = _canvas_size.load();
550         int const width = size.GetWidth();
551         int const height = size.GetHeight();
552
553         if (width < 64 || height < 0) {
554                 return;
555         }
556
557         glViewport (0, 0, width, height);
558         check_gl_error ("glViewport");
559
560         glBindVertexArray(_vao);
561         check_gl_error ("glBindVertexArray");
562         if (_optimise_for_j2k) {
563                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::XYZ_IMAGE));
564         } else if (_rec2020) {
565                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::REC2020_IMAGE));
566         } else {
567                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::REC709_IMAGE));
568         }
569         _video_texture->bind();
570         glDrawElements (GL_TRIANGLES, indices_video_texture_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_video_texture_offset * sizeof(int)));
571         if (_have_subtitle_to_render) {
572                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::REC709_IMAGE));
573                 _subtitle_texture->bind();
574                 glDrawElements (GL_TRIANGLES, indices_subtitle_texture_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_subtitle_texture_offset * sizeof(int)));
575         }
576         if (_viewer->outline_content()) {
577                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::OUTLINE_CONTENT));
578                 glDrawElements (GL_LINES, indices_outline_content_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_outline_content_offset * sizeof(int)));
579                 check_gl_error ("glDrawElements");
580         }
581         if (auto guess = _viewer->crop_guess()) {
582                 glUniform1i(_fragment_type, static_cast<GLint>(FragmentType::CROP_GUESS));
583                 glDrawElements (GL_LINES, indices_crop_guess_number, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_crop_guess_offset * sizeof(int)));
584                 check_gl_error ("glDrawElements");
585         }
586
587         glFlush();
588         check_gl_error ("glFlush");
589
590         _canvas->SwapBuffers();
591 }
592
593
594 void
595 GLVideoView::set_image (shared_ptr<const PlayerVideo> pv)
596 {
597         shared_ptr<const Image> video = _optimise_for_j2k ? pv->raw_image() : pv->image(boost::bind(&PlayerVideo::force, AV_PIX_FMT_RGB24), VideoRange::FULL, true);
598
599         /* Only the player's black frames should be aligned at this stage, so this should
600          * almost always have no work to do.
601          */
602         video = Image::ensure_alignment (video, Image::Alignment::COMPACT);
603
604         /** If _optimise_for_j2k is true we render a XYZ image, doing the colourspace
605          *  conversion, scaling and video range conversion in the GL shader.
606          *  Otherwise we render a RGB image without any shader-side processing.
607          */
608
609         _video_texture->set (video);
610
611         auto const text = pv->text();
612         _have_subtitle_to_render = static_cast<bool>(text) && _optimise_for_j2k;
613         if (_have_subtitle_to_render) {
614                 /* opt: only do this if it's a new subtitle? */
615                 DCPOMATIC_ASSERT (text->image->alignment() == Image::Alignment::COMPACT);
616                 _subtitle_texture->set (text->image);
617         }
618
619
620         auto const canvas_size = _canvas_size.load();
621         int const canvas_width = canvas_size.GetWidth();
622         int const canvas_height = canvas_size.GetHeight();
623         auto const inter_position = player_video().first->inter_position();
624         auto const inter_size = player_video().first->inter_size();
625         auto const out_size = player_video().first->out_size();
626         auto const crop_guess = _viewer->crop_guess();
627
628         auto x_offset = std::max(0, (canvas_width - out_size.width) / 2);
629         auto y_offset = std::max(0, (canvas_height - out_size.height) / 2);
630
631         _last_canvas_size.set_next (canvas_size);
632         _last_video_size.set_next (video->size());
633         _last_inter_position.set_next (inter_position);
634         _last_inter_size.set_next (inter_size);
635         _last_out_size.set_next (out_size);
636         _last_crop_guess.set_next (crop_guess);
637
638         class Rectangle
639         {
640         public:
641                 Rectangle (wxSize canvas_size, float x, float y, dcp::Size size)
642                         : _canvas_size (canvas_size)
643                 {
644                         auto const x1 = x_pixels_to_gl(x);
645                         auto const y1 = y_pixels_to_gl(y);
646                         auto const x2 = x_pixels_to_gl(x + size.width);
647                         auto const y2 = y_pixels_to_gl(y + size.height);
648
649                         /* The texture coordinates here have to account for the fact that when we put images into the texture OpenGL
650                          * expected us to start at the lower left but we actually started at the top left.  So although the
651                          * top of the texture is at 1.0 we pretend it's the other way round.
652                          */
653
654                         // bottom right
655                         _vertices[0] = x2;
656                         _vertices[1] = y2;
657                         _vertices[2] = 0.0f;
658                         _vertices[3] = 1.0f;
659                         _vertices[4] = 1.0f;
660
661                         // top right
662                         _vertices[5] = x2;
663                         _vertices[6] = y1;
664                         _vertices[7] = 0.0f;
665                         _vertices[8] = 1.0f;
666                         _vertices[9] = 0.0f;
667
668                         // top left
669                         _vertices[10] = x1;
670                         _vertices[11] = y1;
671                         _vertices[12] = 0.0f;
672                         _vertices[13] = 0.0f;
673                         _vertices[14] = 0.0f;
674
675                         // bottom left
676                         _vertices[15] = x1;
677                         _vertices[16] = y2;
678                         _vertices[17] = 0.0f;
679                         _vertices[18] = 0.0f;
680                         _vertices[19] = 1.0f;
681                 }
682
683                 float const * vertices () const {
684                         return _vertices;
685                 }
686
687                 int const size () const {
688                         return sizeof(_vertices);
689                 }
690
691         private:
692                 /* @param x x position in pixels where 0 is left and canvas_width is right on screen */
693                 float x_pixels_to_gl(int x) const {
694                         return (x * 2.0f / _canvas_size.GetWidth()) - 1.0f;
695                 }
696
697                 /* @param y y position in pixels where 0 is top and canvas_height is bottom on screen */
698                 float y_pixels_to_gl(int y) const {
699                         return 1.0f - (y * 2.0f / _canvas_size.GetHeight());
700                 }
701
702                 wxSize _canvas_size;
703                 float _vertices[20];
704         };
705
706         auto const sizing_changed = _last_canvas_size.changed() || _last_inter_position.changed() || _last_inter_size.changed() || _last_out_size.changed();
707
708         if (sizing_changed) {
709                 const auto video = _optimise_for_j2k ?
710                         Rectangle(canvas_size, inter_position.x + x_offset, inter_position.y + y_offset, inter_size)
711                         : Rectangle(canvas_size, x_offset, y_offset, out_size);
712
713                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_video_offset, video.size(), video.vertices());
714                 check_gl_error ("glBufferSubData (video)");
715
716                 const auto outline_content = Rectangle(canvas_size, inter_position.x + x_offset, inter_position.y + y_offset, inter_size);
717                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_outline_content_offset, outline_content.size(), outline_content.vertices());
718                 check_gl_error ("glBufferSubData (outline_content)");
719         }
720
721         if ((sizing_changed || _last_crop_guess.changed()) && crop_guess) {
722                 auto const crop_guess_rectangle = Rectangle(
723                         canvas_size,
724                         inter_position.x + x_offset + inter_size.width * crop_guess->x,
725                         inter_position.y + y_offset + inter_size.height * crop_guess->y,
726                         dcp::Size(inter_size.width * crop_guess->width, inter_size.height * crop_guess->height)
727                         );
728                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_crop_guess_offset, crop_guess_rectangle.size(), crop_guess_rectangle.vertices());
729                 check_gl_error ("glBufferSubData (crop_guess_rectangle)");
730         }
731
732         if (_have_subtitle_to_render) {
733                 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());
734                 glBufferSubData (GL_ARRAY_BUFFER, array_buffer_subtitle_offset, subtitle.size(), subtitle.vertices());
735                 check_gl_error ("glBufferSubData (subtitle)");
736         }
737
738         _rec2020 = pv->colour_conversion() && pv->colour_conversion()->about_equal(dcp::ColourConversion::rec2020_to_xyz(), 1e-6);
739
740         /* opt: where should these go? */
741
742         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
743         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
744         check_gl_error ("glTexParameteri");
745
746         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
747         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
748         check_gl_error ("glTexParameterf");
749 }
750
751
752 void
753 GLVideoView::start ()
754 {
755         VideoView::start ();
756
757         boost::mutex::scoped_lock lm (_playing_mutex);
758         _playing = true;
759         _thread_work_condition.notify_all ();
760 }
761
762 void
763 GLVideoView::stop ()
764 {
765         boost::mutex::scoped_lock lm (_playing_mutex);
766         _playing = false;
767 }
768
769
770 void
771 GLVideoView::thread_playing ()
772 {
773         if (length() != dcpomatic::DCPTime()) {
774                 auto const next = position() + one_video_frame();
775
776                 if (next >= length()) {
777                         _viewer->finished ();
778                         return;
779                 }
780
781                 get_next_frame (false);
782                 set_image_and_draw ();
783         }
784
785         while (true) {
786                 optional<int> n = time_until_next_frame();
787                 if (!n || *n > 5) {
788                         break;
789                 }
790                 get_next_frame (true);
791                 add_dropped ();
792         }
793 }
794
795
796 void
797 GLVideoView::set_image_and_draw ()
798 {
799         auto pv = player_video().first;
800         if (pv) {
801                 set_image (pv);
802         }
803
804         draw ();
805
806         if (pv) {
807                 _viewer->image_changed (pv);
808         }
809 }
810
811
812 void
813 GLVideoView::thread ()
814 try
815 {
816         start_of_thread ("GLVideoView");
817
818 #if defined(DCPOMATIC_OSX)
819         /* Without this we see errors like
820          * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
821          */
822         WXGLSetCurrentContext (_context->GetWXGLContext());
823 #else
824         if (!_setup_shaders_done) {
825                 setup_shaders ();
826                 _setup_shaders_done = true;
827         }
828 #endif
829
830 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
831         if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
832                 /* Enable vsync */
833                 Display* dpy = wxGetX11Display();
834                 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
835                 _vsync_enabled = true;
836         }
837 #endif
838
839 #ifdef DCPOMATIC_WINDOWS
840         if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
841                 /* Enable vsync */
842                 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
843                 if (swap) {
844                         swap (1);
845                         _vsync_enabled = true;
846                 }
847         }
848
849 #endif
850
851 #ifdef DCPOMATIC_OSX
852         /* Enable vsync */
853         GLint swapInterval = 1;
854         CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
855         _vsync_enabled = true;
856 #endif
857
858         _video_texture.reset(new Texture(_optimise_for_j2k ? 2 : 1));
859         _subtitle_texture.reset(new Texture(1));
860
861         while (true) {
862                 boost::mutex::scoped_lock lm (_playing_mutex);
863                 while (!_playing && !_one_shot) {
864                         _thread_work_condition.wait (lm);
865                 }
866                 lm.unlock ();
867
868                 if (_playing) {
869                         thread_playing ();
870                 } else if (_one_shot) {
871                         _one_shot = false;
872                         set_image_and_draw ();
873                 }
874
875                 boost::this_thread::interruption_point ();
876                 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
877         }
878
879         /* XXX: leaks _context, but that seems preferable to deleting it here
880          * without also deleting the wxGLCanvas.
881          */
882 }
883 catch (...)
884 {
885         store_current ();
886 }
887
888
889 VideoView::NextFrameResult
890 GLVideoView::display_next_frame (bool non_blocking)
891 {
892         NextFrameResult const r = get_next_frame (non_blocking);
893         request_one_shot ();
894         return r;
895 }
896
897
898 void
899 GLVideoView::request_one_shot ()
900 {
901         boost::mutex::scoped_lock lm (_playing_mutex);
902         _one_shot = true;
903         _thread_work_condition.notify_all ();
904 }
905
906
907 Texture::Texture (GLint unpack_alignment)
908         : _unpack_alignment (unpack_alignment)
909 {
910         glGenTextures (1, &_name);
911         check_gl_error ("glGenTextures");
912 }
913
914
915 Texture::~Texture ()
916 {
917         glDeleteTextures (1, &_name);
918 }
919
920
921 void
922 Texture::bind ()
923 {
924         glBindTexture(GL_TEXTURE_2D, _name);
925         check_gl_error ("glBindTexture");
926 }
927
928
929 void
930 Texture::set (shared_ptr<const Image> image)
931 {
932         auto const create = !_size || image->size() != _size;
933         _size = image->size();
934
935         glPixelStorei (GL_UNPACK_ALIGNMENT, _unpack_alignment);
936         check_gl_error ("glPixelStorei");
937
938         DCPOMATIC_ASSERT (image->alignment() == Image::Alignment::COMPACT);
939
940         GLint internal_format;
941         GLenum format;
942         GLenum type;
943
944         switch (image->pixel_format()) {
945         case AV_PIX_FMT_BGRA:
946                 internal_format = GL_RGBA8;
947                 format = GL_BGRA;
948                 type = GL_UNSIGNED_BYTE;
949                 break;
950         case AV_PIX_FMT_RGBA:
951                 internal_format = GL_RGBA8;
952                 format = GL_RGBA;
953                 type = GL_UNSIGNED_BYTE;
954                 break;
955         case AV_PIX_FMT_RGB24:
956                 internal_format = GL_RGBA8;
957                 format = GL_RGB;
958                 type = GL_UNSIGNED_BYTE;
959                 break;
960         case AV_PIX_FMT_XYZ12:
961                 internal_format = GL_RGBA12;
962                 format = GL_RGB;
963                 type = GL_UNSIGNED_SHORT;
964                 break;
965         default:
966                 throw PixelFormatError ("Texture::set", image->pixel_format());
967         }
968
969         bind ();
970
971         if (create) {
972                 glTexImage2D (GL_TEXTURE_2D, 0, internal_format, _size->width, _size->height, 0, format, type, image->data()[0]);
973                 check_gl_error ("glTexImage2D");
974         } else {
975                 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _size->width, _size->height, format, type, image->data()[0]);
976                 check_gl_error ("glTexSubImage2D");
977         }
978 }
979
980 #endif