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