2 Copyright (C) 2018-2021 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
22 #ifdef DCPOMATIC_WINDOWS
26 #include "gl_video_view.h"
27 #include "film_viewer.h"
29 #include "lib/image.h"
30 #include "lib/dcpomatic_assert.h"
31 #include "lib/exceptions.h"
32 #include "lib/cross.h"
33 #include "lib/player_video.h"
34 #include "lib/butler.h"
35 #include <boost/bind/bind.hpp>
39 #define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED
40 #include <OpenGL/OpenGL.h>
41 #include <OpenGL/gl3.h>
44 #ifdef DCPOMATIC_LINUX
49 #ifdef DCPOMATIC_WINDOWS
51 #include <GL/wglext.h>
56 using std::shared_ptr;
58 using boost::optional;
59 #if BOOST_VERSION >= 106100
60 using namespace boost::placeholders;
65 check_gl_error (char const * last)
67 GLenum const e = glGetError ();
68 if (e != GL_NO_ERROR) {
69 throw GLError (last, e);
74 GLVideoView::GLVideoView (FilmViewer* viewer, wxWindow *parent)
77 , _have_storage (false)
78 , _vsync_enabled (false)
82 wxGLAttributes attributes;
83 /* We don't need a depth buffer, and indeed there is apparently a bug with Windows/Intel HD 630
84 * which puts green lines over the OpenGL display if you have a non-zero depth buffer size.
85 * https://community.intel.com/t5/Graphics/Request-for-details-on-Intel-HD-630-green-lines-in-OpenGL-apps/m-p/1202179
87 attributes.PlatformDefaults().MinRGBA(8, 8, 8, 8).DoubleBuffer().Depth(0).EndList();
88 _canvas = new wxGLCanvas (
89 parent, attributes, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE
91 _canvas->Bind (wxEVT_PAINT, boost::bind(&GLVideoView::update, this));
92 _canvas->Bind (wxEVT_SIZE, boost::bind(&GLVideoView::size_changed, this, _1));
94 _canvas->Bind (wxEVT_TIMER, boost::bind(&GLVideoView::check_for_butler_errors, this));
95 _timer.reset (new wxTimer(_canvas));
101 GLVideoView::size_changed (wxSizeEvent const& ev)
103 _canvas_size = ev.GetSize ();
109 GLVideoView::~GLVideoView ()
111 boost::this_thread::disable_interruption dis;
114 _thread.interrupt ();
118 glDeleteTextures (1, &_video_texture);
122 GLVideoView::check_for_butler_errors ()
124 if (!_viewer->butler()) {
129 _viewer->butler()->rethrow ();
130 } catch (DecodeError& e) {
131 error_dialog (get(), e.what());
132 } catch (dcp::ReadError& e) {
133 error_dialog (get(), wxString::Format(_("Could not read DCP: %s"), std_to_wx(e.what())));
138 /** Called from the UI thread */
140 GLVideoView::update ()
142 if (!_canvas->IsShownOnScreen()) {
146 /* It appears important to do this from the GUI thread; if we do it from the GL thread
147 * on Linux we get strange failures to create the context for any version of GL higher
153 /* macOS gives errors if we don't do this (and therefore [NSOpenGLContext setView:]) from the main thread */
154 if (!_setup_shaders_done) {
156 _setup_shaders_done = true;
160 if (!_thread.joinable()) {
161 _thread = boost::thread (boost::bind(&GLVideoView::thread, this));
170 static constexpr char vertex_source[] =
171 "#version 330 core\n"
173 "layout (location = 0) in vec3 in_pos;\n"
174 "layout (location = 1) in vec2 in_tex_coord;\n"
176 "out vec2 TexCoord;\n"
180 " gl_Position = vec4(in_pos, 1.0);\n"
181 " TexCoord = in_tex_coord;\n"
185 /* Bicubic interpolation stolen from https://stackoverflow.com/questions/13501081/efficient-bicubic-filtering-code-in-glsl */
186 static constexpr char fragment_source[] =
187 "#version 330 core\n"
189 "in vec2 TexCoord;\n"
191 "uniform sampler2D texture_sampler;\n"
192 /* type = 0: draw border
193 * type = 1: draw XYZ image
194 * type = 2: draw RGB image
196 "uniform int type = 0;\n"
197 "uniform vec4 border_colour;\n"
198 "uniform mat4 colour_conversion;\n"
200 "out vec4 FragColor;\n"
202 "vec4 cubic(float x)\n"
204 "#define IN_GAMMA 2.2\n"
205 "#define OUT_GAMMA 0.384615385\n" // 1 / 2.6
206 "#define DCI_COEFFICIENT 0.91655528\n" // 48 / 53.37
209 " float x2 = x * x;\n"
210 " float x3 = x2 * x;\n"
212 " w.x = -x3 + 3 * x2 - 3 * x + 1;\n"
213 " w.y = 3 * x3 - 6 * x2 + 4;\n"
214 " w.z = -3 * x3 + 3 * x2 + 3 * x + 1;\n"
219 "vec4 texture_bicubic(sampler2D sampler, vec2 tex_coords)\n"
221 " vec2 tex_size = textureSize(sampler, 0);\n"
222 " vec2 inv_tex_size = 1.0 / tex_size;\n"
224 " tex_coords = tex_coords * tex_size - 0.5;\n"
226 " vec2 fxy = fract(tex_coords);\n"
227 " tex_coords -= fxy;\n"
229 " vec4 xcubic = cubic(fxy.x);\n"
230 " vec4 ycubic = cubic(fxy.y);\n"
232 " vec4 c = tex_coords.xxyy + vec2 (-0.5, +1.5).xyxy;\n"
234 " vec4 s = vec4(xcubic.xz + xcubic.yw, ycubic.xz + ycubic.yw);\n"
235 " vec4 offset = c + vec4 (xcubic.yw, ycubic.yw) / s;\n"
237 " offset *= inv_tex_size.xxyy;\n"
239 " vec4 sample0 = texture(sampler, offset.xz);\n"
240 " vec4 sample1 = texture(sampler, offset.yz);\n"
241 " vec4 sample2 = texture(sampler, offset.xw);\n"
242 " vec4 sample3 = texture(sampler, offset.yw);\n"
244 " float sx = s.x / (s.x + s.y);\n"
245 " float sy = s.z / (s.z + s.w);\n"
248 " mix(sample3, sample2, sx), mix(sample1, sample0, sx)\n"
256 " FragColor = border_colour;\n"
259 " FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
260 " FragColor.x = pow(FragColor.x, IN_GAMMA) / DCI_COEFFICIENT;\n"
261 " FragColor.y = pow(FragColor.y, IN_GAMMA) / DCI_COEFFICIENT;\n"
262 " FragColor.z = pow(FragColor.z, IN_GAMMA) / DCI_COEFFICIENT;\n"
263 " FragColor = colour_conversion * FragColor;\n"
264 " FragColor.x = pow(FragColor.x, OUT_GAMMA);\n"
265 " FragColor.y = pow(FragColor.y, OUT_GAMMA);\n"
266 " FragColor.z = pow(FragColor.z, OUT_GAMMA);\n"
269 " FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
276 GLVideoView::ensure_context ()
279 wxGLContextAttrs attrs;
280 attrs.PlatformDefaults().CoreProfile().OGLVersion(4, 1).EndList();
281 _context = new wxGLContext (_canvas, nullptr, &attrs);
282 if (!_context->IsOK()) {
283 throw GLError ("Making GL context", -1);
289 GLVideoView::setup_shaders ()
291 DCPOMATIC_ASSERT (_canvas);
292 DCPOMATIC_ASSERT (_context);
293 auto r = _canvas->SetCurrent (*_context);
294 DCPOMATIC_ASSERT (r);
296 #ifdef DCPOMATIC_WINDOWS
299 throw GLError(reinterpret_cast<char const*>(glewGetErrorString(r)));
303 auto get_information = [this](GLenum name) {
304 auto s = glGetString (name);
306 _information[name] = std::string (reinterpret_cast<char const *>(s));
310 get_information (GL_VENDOR);
311 get_information (GL_RENDERER);
312 get_information (GL_VERSION);
313 get_information (GL_SHADING_LANGUAGE_VERSION);
315 unsigned int indices[] = {
316 0, 1, 3, // texture triangle #1
317 1, 2, 3, // texture triangle #2
318 4, 5, // border line #1
319 5, 6, // border line #2
320 6, 7, // border line #3
321 7, 4, // border line #4
324 glGenVertexArrays(1, &_vao);
325 check_gl_error ("glGenVertexArrays");
327 glGenBuffers(1, &vbo);
328 check_gl_error ("glGenBuffers");
330 glGenBuffers(1, &ebo);
331 check_gl_error ("glGenBuffers");
333 glBindVertexArray(_vao);
334 check_gl_error ("glBindVertexArray");
336 glBindBuffer(GL_ARRAY_BUFFER, vbo);
337 check_gl_error ("glBindBuffer");
339 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
340 check_gl_error ("glBindBuffer");
341 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
342 check_gl_error ("glBufferData");
344 /* position attribute to vertex shader (location = 0) */
345 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), nullptr);
346 glEnableVertexAttribArray(0);
347 /* texture coord attribute to vertex shader (location = 1) */
348 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
349 glEnableVertexAttribArray(1);
350 check_gl_error ("glEnableVertexAttribArray");
352 auto compile = [](GLenum type, char const* source) -> GLuint {
353 auto shader = glCreateShader(type);
354 DCPOMATIC_ASSERT (shader);
355 GLchar const * src[] = { static_cast<GLchar const *>(source) };
356 glShaderSource(shader, 1, src, nullptr);
357 check_gl_error ("glShaderSource");
358 glCompileShader(shader);
359 check_gl_error ("glCompileShader");
361 glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
364 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
366 if (log_length > 0) {
367 char* log_char = new char[log_length];
368 glGetShaderInfoLog(shader, log_length, nullptr, log_char);
369 log = string(log_char);
372 glDeleteShader(shader);
373 throw GLError(String::compose("Could not compile shader (%1)", log).c_str(), -1);
378 auto vertex_shader = compile (GL_VERTEX_SHADER, vertex_source);
379 auto fragment_shader = compile (GL_FRAGMENT_SHADER, fragment_source);
381 auto program = glCreateProgram();
382 check_gl_error ("glCreateProgram");
383 glAttachShader (program, vertex_shader);
384 check_gl_error ("glAttachShader");
385 glAttachShader (program, fragment_shader);
386 check_gl_error ("glAttachShader");
387 glLinkProgram (program);
388 check_gl_error ("glLinkProgram");
390 glGetProgramiv (program, GL_LINK_STATUS, &ok);
393 glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
395 if (log_length > 0) {
396 char* log_char = new char[log_length];
397 glGetProgramInfoLog(program, log_length, nullptr, log_char);
398 log = string(log_char);
401 glDeleteProgram (program);
402 throw GLError(String::compose("Could not link shader (%1)", log).c_str(), -1);
404 glDeleteShader (vertex_shader);
405 glDeleteShader (fragment_shader);
407 glUseProgram (program);
409 _fragment_type = glGetUniformLocation (program, "type");
410 check_gl_error ("glGetUniformLocation");
411 set_border_colour (program);
413 auto conversion = dcp::ColourConversion::rec709_to_xyz();
414 boost::numeric::ublas::matrix<double> matrix = conversion.xyz_to_rgb ();
415 GLfloat gl_matrix[] = {
416 static_cast<float>(matrix(0, 0)), static_cast<float>(matrix(0, 1)), static_cast<float>(matrix(0, 2)), 0.0f,
417 static_cast<float>(matrix(1, 0)), static_cast<float>(matrix(1, 1)), static_cast<float>(matrix(1, 2)), 0.0f,
418 static_cast<float>(matrix(2, 0)), static_cast<float>(matrix(2, 1)), static_cast<float>(matrix(2, 2)), 0.0f,
419 0.0f, 0.0f, 0.0f, 1.0f
422 auto colour_conversion = glGetUniformLocation (program, "colour_conversion");
423 check_gl_error ("glGetUniformLocation");
424 glUniformMatrix4fv (colour_conversion, 1, GL_TRUE, gl_matrix);
431 GLVideoView::set_border_colour (GLuint program)
433 auto uniform = glGetUniformLocation (program, "border_colour");
434 check_gl_error ("glGetUniformLocation");
435 auto colour = outline_content_colour ();
436 glUniform4f (uniform, colour.Red() / 255.0f, colour.Green() / 255.0f, colour.Blue() / 255.0f, 1.0f);
437 check_gl_error ("glUniform4f");
442 GLVideoView::draw (Position<int>, dcp::Size)
444 auto pad = pad_colour();
445 glClearColor(pad.Red() / 255.0, pad.Green() / 255.0, pad.Blue() / 255.0, 1.0);
446 glClear (GL_COLOR_BUFFER_BIT);
447 check_gl_error ("glClear");
449 auto const size = _canvas_size.load();
450 int const width = size.GetWidth();
451 int const height = size.GetHeight();
453 if (width < 64 || height < 0) {
457 glViewport (0, 0, width, height);
458 check_gl_error ("glViewport");
460 glBindTexture(GL_TEXTURE_2D, _video_texture);
461 glBindVertexArray(_vao);
462 check_gl_error ("glBindVertexArray");
463 glUniform1i(_fragment_type, _optimise_for_j2k ? 1 : 2);
464 glDrawElements (GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
465 if (_viewer->outline_content()) {
466 glUniform1i(_fragment_type, 1);
467 glDrawElements (GL_LINES, 8, GL_UNSIGNED_INT, reinterpret_cast<void*>(6 * sizeof(int)));
468 check_gl_error ("glDrawElements");
472 check_gl_error ("glFlush");
474 _canvas->SwapBuffers();
479 GLVideoView::set_image (shared_ptr<const PlayerVideo> pv)
481 auto image = _optimise_for_j2k ? pv->raw_image() : pv->image(bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), VideoRange::FULL, false, true);
483 DCPOMATIC_ASSERT (!image->aligned());
485 /** If _optimise_for_j2k is true we render a XYZ image, doing the colourspace
486 * conversion, scaling and video range conversion in the GL shader.
487 * Othewise we render a RGB image without any shader-side processing.
490 /* XXX: video range conversion */
493 if (image->size() != _size) {
494 _have_storage = false;
497 _size = image->size ();
498 glPixelStorei (GL_UNPACK_ALIGNMENT, _optimise_for_j2k ? 2 : 1);
499 check_gl_error ("glPixelStorei");
501 auto const format = _optimise_for_j2k ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
504 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _size->width, _size->height, GL_RGB, format, image->data()[0]);
505 check_gl_error ("glTexSubImage2D");
507 glTexImage2D (GL_TEXTURE_2D, 0, _optimise_for_j2k ? GL_RGBA12 : GL_RGBA8, _size->width, _size->height, 0, GL_RGB, format, image->data()[0]);
508 check_gl_error ("glTexImage2D");
510 auto const canvas_size = _canvas_size.load();
511 int const canvas_width = canvas_size.GetWidth();
512 int const canvas_height = canvas_size.GetHeight();
514 float const image_x = float(_size->width) / canvas_width;
515 float const image_y = float(_size->height) / canvas_height;
517 auto x_pixels_to_gl = [canvas_width](int x) {
518 return (x * 2.0f / canvas_width) - 1.0f;
521 auto y_pixels_to_gl = [canvas_height](int y) {
522 return (y * 2.0f / canvas_height) - 1.0f;
525 auto inter_position = player_video().first->inter_position();
526 auto inter_size = player_video().first->inter_size();
528 float const border_x1 = x_pixels_to_gl (inter_position.x) + 1.0f - image_x;
529 float const border_y1 = y_pixels_to_gl (inter_position.y) + 1.0f - image_y;
530 float const border_x2 = x_pixels_to_gl (inter_position.x + inter_size.width) + 1.0f - image_x;
531 float const border_y2 = y_pixels_to_gl (inter_position.y + inter_size.height) + 1.0f - image_y;
534 // positions // texture coords
535 image_x, image_y, 0.0f, 1.0f, 0.0f, // top right (index 0)
536 image_x, -image_y, 0.0f, 1.0f, 1.0f, // bottom right (index 1)
537 -image_x, -image_y, 0.0f, 0.0f, 1.0f, // bottom left (index 2)
538 -image_x, image_y, 0.0f, 0.0f, 0.0f, // top left (index 3)
539 border_x1, border_y1, 0.0f, 0.0f, 0.0f, // border bottom left (index 4)
540 border_x1, border_y2, 0.0f, 0.0f, 0.0f, // border top left (index 5)
541 border_x2, border_y2, 0.0f, 0.0f, 0.0f, // border top right (index 6)
542 border_x2, border_y1, 0.0f, 0.0f, 0.0f, // border bottom right (index 7)
545 /* Set the vertex shader's input data (GL_ARRAY_BUFFER) */
546 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
547 check_gl_error ("glBufferData");
549 _have_storage = true;
552 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
553 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
554 check_gl_error ("glTexParameteri");
556 glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
557 glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
558 check_gl_error ("glTexParameterf");
563 GLVideoView::start ()
567 boost::mutex::scoped_lock lm (_playing_mutex);
569 _thread_work_condition.notify_all ();
575 boost::mutex::scoped_lock lm (_playing_mutex);
581 GLVideoView::thread_playing ()
583 if (length() != dcpomatic::DCPTime()) {
584 auto const next = position() + one_video_frame();
586 if (next >= length()) {
587 _viewer->finished ();
591 get_next_frame (false);
592 set_image_and_draw ();
596 optional<int> n = time_until_next_frame();
600 get_next_frame (true);
607 GLVideoView::set_image_and_draw ()
609 auto pv = player_video().first;
612 draw (pv->inter_position(), pv->inter_size());
613 _viewer->image_changed (pv);
619 GLVideoView::thread ()
622 start_of_thread ("GLVideoView");
624 #if defined(DCPOMATIC_OSX)
625 /* Without this we see errors like
626 * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
628 WXGLSetCurrentContext (_context->GetWXGLContext());
630 if (!_setup_shaders_done) {
632 _setup_shaders_done = true;
636 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
637 if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
639 Display* dpy = wxGetX11Display();
640 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
641 _vsync_enabled = true;
645 #ifdef DCPOMATIC_WINDOWS
646 if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
648 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
651 _vsync_enabled = true;
659 GLint swapInterval = 1;
660 CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
661 _vsync_enabled = true;
664 glGenTextures (1, &_video_texture);
665 check_gl_error ("glGenTextures");
666 glBindTexture (GL_TEXTURE_2D, _video_texture);
667 check_gl_error ("glBindTexture");
670 boost::mutex::scoped_lock lm (_playing_mutex);
671 while (!_playing && !_one_shot) {
672 _thread_work_condition.wait (lm);
678 } else if (_one_shot) {
680 set_image_and_draw ();
683 boost::this_thread::interruption_point ();
684 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
687 /* XXX: leaks _context, but that seems preferable to deleting it here
688 * without also deleting the wxGLCanvas.
697 VideoView::NextFrameResult
698 GLVideoView::display_next_frame (bool non_blocking)
700 NextFrameResult const r = get_next_frame (non_blocking);
707 GLVideoView::request_one_shot ()
709 boost::mutex::scoped_lock lm (_playing_mutex);
711 _thread_work_condition.notify_all ();