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