Add basic Texture wrapper for a GL texture.
[dcpomatic.git] / src / wx / gl_video_view.cc
1 /*
2     Copyright (C) 2018-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #ifdef DCPOMATIC_WINDOWS
23 #include <GL/glew.h>
24 #endif
25
26 #include "gl_video_view.h"
27 #include "film_viewer.h"
28 #include "wx_util.h"
29 #include "lib/image.h"
30 #include "lib/dcpomatic_assert.h"
31 #include "lib/exceptions.h"
32 #include "lib/cross.h"
33 #include "lib/player_video.h"
34 #include "lib/butler.h"
35 #include <boost/bind/bind.hpp>
36 #include <iostream>
37
38 #ifdef DCPOMATIC_OSX
39 #define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED
40 #include <OpenGL/OpenGL.h>
41 #include <OpenGL/gl3.h>
42 #endif
43
44 #ifdef DCPOMATIC_LINUX
45 #include <GL/glu.h>
46 #include <GL/glext.h>
47 #endif
48
49 #ifdef DCPOMATIC_WINDOWS
50 #include <GL/glu.h>
51 #include <GL/wglext.h>
52 #endif
53
54
55 using std::cout;
56 using std::shared_ptr;
57 using std::string;
58 using boost::optional;
59 #if BOOST_VERSION >= 106100
60 using namespace boost::placeholders;
61 #endif
62
63
64 static void
65 check_gl_error (char const * last)
66 {
67         GLenum const e = glGetError ();
68         if (e != GL_NO_ERROR) {
69                 throw GLError (last, e);
70         }
71 }
72
73
74 GLVideoView::GLVideoView (FilmViewer* viewer, wxWindow *parent)
75         : VideoView (viewer)
76         , _context (nullptr)
77         , _have_storage (false)
78         , _vsync_enabled (false)
79         , _playing (false)
80         , _one_shot (false)
81 {
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
86          */
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
90         );
91         _canvas->Bind (wxEVT_PAINT, boost::bind(&GLVideoView::update, this));
92         _canvas->Bind (wxEVT_SIZE, boost::bind(&GLVideoView::size_changed, this, _1));
93
94         _canvas->Bind (wxEVT_TIMER, boost::bind(&GLVideoView::check_for_butler_errors, this));
95         _timer.reset (new wxTimer(_canvas));
96         _timer->Start (2000);
97 }
98
99
100 void
101 GLVideoView::size_changed (wxSizeEvent const& ev)
102 {
103         _canvas_size = ev.GetSize ();
104         Sized ();
105 }
106
107
108
109 GLVideoView::~GLVideoView ()
110 {
111         boost::this_thread::disable_interruption dis;
112
113         try {
114                 _thread.interrupt ();
115                 _thread.join ();
116         } catch (...) {}
117 }
118
119 void
120 GLVideoView::check_for_butler_errors ()
121 {
122         if (!_viewer->butler()) {
123                 return;
124         }
125
126         try {
127                 _viewer->butler()->rethrow ();
128         } catch (DecodeError& e) {
129                 error_dialog (get(), e.what());
130         } catch (dcp::ReadError& e) {
131                 error_dialog (get(), wxString::Format(_("Could not read DCP: %s"), std_to_wx(e.what())));
132         }
133 }
134
135
136 /** Called from the UI thread */
137 void
138 GLVideoView::update ()
139 {
140         if (!_canvas->IsShownOnScreen()) {
141                 return;
142         }
143
144         /* It appears important to do this from the GUI thread; if we do it from the GL thread
145          * on Linux we get strange failures to create the context for any version of GL higher
146          * than 3.2.
147          */
148         ensure_context ();
149
150 #ifdef DCPOMATIC_OSX
151         /* macOS gives errors if we don't do this (and therefore [NSOpenGLContext setView:]) from the main thread */
152         if (!_setup_shaders_done) {
153                 setup_shaders ();
154                 _setup_shaders_done = true;
155         }
156 #endif
157
158         if (!_thread.joinable()) {
159                 _thread = boost::thread (boost::bind(&GLVideoView::thread, this));
160         }
161
162         request_one_shot ();
163
164         rethrow ();
165 }
166
167
168 static constexpr char vertex_source[] =
169 "#version 330 core\n"
170 "\n"
171 "layout (location = 0) in vec3 in_pos;\n"
172 "layout (location = 1) in vec2 in_tex_coord;\n"
173 "\n"
174 "out vec2 TexCoord;\n"
175 "\n"
176 "void main()\n"
177 "{\n"
178 "       gl_Position = vec4(in_pos, 1.0);\n"
179 "       TexCoord = in_tex_coord;\n"
180 "}\n";
181
182
183 /* Bicubic interpolation stolen from https://stackoverflow.com/questions/13501081/efficient-bicubic-filtering-code-in-glsl */
184 static constexpr char fragment_source[] =
185 "#version 330 core\n"
186 "\n"
187 "in vec2 TexCoord;\n"
188 "\n"
189 "uniform sampler2D texture_sampler;\n"
190 /* type = 0: draw border
191  * type = 1: draw XYZ image
192  * type = 2: draw RGB image
193  */
194 "uniform int type = 0;\n"
195 "uniform vec4 border_colour;\n"
196 "uniform mat4 colour_conversion;\n"
197 "\n"
198 "out vec4 FragColor;\n"
199 "\n"
200 "vec4 cubic(float x)\n"
201 "\n"
202 "#define IN_GAMMA 2.2\n"
203 "#define OUT_GAMMA 0.384615385\n"       //  1 /  2.6
204 "#define DCI_COEFFICIENT 0.91655528\n"  // 48 / 53.37
205 "\n"
206 "{\n"
207 "    float x2 = x * x;\n"
208 "    float x3 = x2 * x;\n"
209 "    vec4 w;\n"
210 "    w.x =     -x3 + 3 * x2 - 3 * x + 1;\n"
211 "    w.y =  3 * x3 - 6 * x2         + 4;\n"
212 "    w.z = -3 * x3 + 3 * x2 + 3 * x + 1;\n"
213 "    w.w =  x3;\n"
214 "    return w / 6.f;\n"
215 "}\n"
216 "\n"
217 "vec4 texture_bicubic(sampler2D sampler, vec2 tex_coords)\n"
218 "{\n"
219 "   vec2 tex_size = textureSize(sampler, 0);\n"
220 "   vec2 inv_tex_size = 1.0 / tex_size;\n"
221 "\n"
222 "   tex_coords = tex_coords * tex_size - 0.5;\n"
223 "\n"
224 "   vec2 fxy = fract(tex_coords);\n"
225 "   tex_coords -= fxy;\n"
226 "\n"
227 "   vec4 xcubic = cubic(fxy.x);\n"
228 "   vec4 ycubic = cubic(fxy.y);\n"
229 "\n"
230 "   vec4 c = tex_coords.xxyy + vec2 (-0.5, +1.5).xyxy;\n"
231 "\n"
232 "   vec4 s = vec4(xcubic.xz + xcubic.yw, ycubic.xz + ycubic.yw);\n"
233 "   vec4 offset = c + vec4 (xcubic.yw, ycubic.yw) / s;\n"
234 "\n"
235 "   offset *= inv_tex_size.xxyy;\n"
236 "\n"
237 "   vec4 sample0 = texture(sampler, offset.xz);\n"
238 "   vec4 sample1 = texture(sampler, offset.yz);\n"
239 "   vec4 sample2 = texture(sampler, offset.xw);\n"
240 "   vec4 sample3 = texture(sampler, offset.yw);\n"
241 "\n"
242 "   float sx = s.x / (s.x + s.y);\n"
243 "   float sy = s.z / (s.z + s.w);\n"
244 "\n"
245 "   return mix(\n"
246 "          mix(sample3, sample2, sx), mix(sample1, sample0, sx)\n"
247 "          , sy);\n"
248 "}\n"
249 "\n"
250 "void main()\n"
251 "{\n"
252 "       switch (type) {\n"
253 "               case 0:\n"
254 "                       FragColor = border_colour;\n"
255 "                       break;\n"
256 "               case 1:\n"
257 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
258 "                       FragColor.x = pow(FragColor.x, IN_GAMMA) / DCI_COEFFICIENT;\n"
259 "                       FragColor.y = pow(FragColor.y, IN_GAMMA) / DCI_COEFFICIENT;\n"
260 "                       FragColor.z = pow(FragColor.z, IN_GAMMA) / DCI_COEFFICIENT;\n"
261 "                       FragColor = colour_conversion * FragColor;\n"
262 "                       FragColor.x = pow(FragColor.x, OUT_GAMMA);\n"
263 "                       FragColor.y = pow(FragColor.y, OUT_GAMMA);\n"
264 "                       FragColor.z = pow(FragColor.z, OUT_GAMMA);\n"
265 "                       break;\n"
266 "               case 2:\n"
267 "                       FragColor = texture_bicubic(texture_sampler, TexCoord);\n"
268 "                       break;\n"
269 "       }\n"
270 "}\n";
271
272
273 void
274 GLVideoView::ensure_context ()
275 {
276         if (!_context) {
277                 wxGLContextAttrs attrs;
278                 attrs.PlatformDefaults().CoreProfile().OGLVersion(4, 1).EndList();
279                 _context = new wxGLContext (_canvas, nullptr, &attrs);
280                 if (!_context->IsOK()) {
281                         throw GLError ("Making GL context", -1);
282                 }
283         }
284 }
285
286
287 /* Offset of video texture triangles in indices */
288 static constexpr int indices_video_texture = 0;
289 /* Offset of border lines in indices */
290 static constexpr int indices_border = 6;
291
292 static constexpr unsigned int indices[] = {
293         0, 1, 3, // video texture triangle #1
294         1, 2, 3, // video texture triangle #2
295         4, 5,    // border line #1
296         5, 6,    // border line #2
297         6, 7,    // border line #3
298         7, 4,    // border line #4
299 };
300
301
302 void
303 GLVideoView::setup_shaders ()
304 {
305         DCPOMATIC_ASSERT (_canvas);
306         DCPOMATIC_ASSERT (_context);
307         auto r = _canvas->SetCurrent (*_context);
308         DCPOMATIC_ASSERT (r);
309
310 #ifdef DCPOMATIC_WINDOWS
311         r = glewInit();
312         if (r != GLEW_OK) {
313                 throw GLError(reinterpret_cast<char const*>(glewGetErrorString(r)));
314         }
315 #endif
316
317         auto get_information = [this](GLenum name) {
318                 auto s = glGetString (name);
319                 if (s) {
320                         _information[name] = std::string (reinterpret_cast<char const *>(s));
321                 }
322         };
323
324         get_information (GL_VENDOR);
325         get_information (GL_RENDERER);
326         get_information (GL_VERSION);
327         get_information (GL_SHADING_LANGUAGE_VERSION);
328
329         glGenVertexArrays(1, &_vao);
330         check_gl_error ("glGenVertexArrays");
331         GLuint vbo;
332         glGenBuffers(1, &vbo);
333         check_gl_error ("glGenBuffers");
334         GLuint ebo;
335         glGenBuffers(1, &ebo);
336         check_gl_error ("glGenBuffers");
337
338         glBindVertexArray(_vao);
339         check_gl_error ("glBindVertexArray");
340
341         glBindBuffer(GL_ARRAY_BUFFER, vbo);
342         check_gl_error ("glBindBuffer");
343
344         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
345         check_gl_error ("glBindBuffer");
346         glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
347         check_gl_error ("glBufferData");
348
349         /* position attribute to vertex shader (location = 0) */
350         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), nullptr);
351         glEnableVertexAttribArray(0);
352         /* texture coord attribute to vertex shader (location = 1) */
353         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
354         glEnableVertexAttribArray(1);
355         check_gl_error ("glEnableVertexAttribArray");
356
357         auto compile = [](GLenum type, char const* source) -> GLuint {
358                 auto shader = glCreateShader(type);
359                 DCPOMATIC_ASSERT (shader);
360                 GLchar const * src[] = { static_cast<GLchar const *>(source) };
361                 glShaderSource(shader, 1, src, nullptr);
362                 check_gl_error ("glShaderSource");
363                 glCompileShader(shader);
364                 check_gl_error ("glCompileShader");
365                 GLint ok;
366                 glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
367                 if (!ok) {
368                         GLint log_length;
369                         glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
370                         string log;
371                         if (log_length > 0) {
372                                 char* log_char = new char[log_length];
373                                 glGetShaderInfoLog(shader, log_length, nullptr, log_char);
374                                 log = string(log_char);
375                                 delete[] log_char;
376                         }
377                         glDeleteShader(shader);
378                         throw GLError(String::compose("Could not compile shader (%1)", log).c_str(), -1);
379                 }
380                 return shader;
381         };
382
383         auto vertex_shader = compile (GL_VERTEX_SHADER, vertex_source);
384         auto fragment_shader = compile (GL_FRAGMENT_SHADER, fragment_source);
385
386         auto program = glCreateProgram();
387         check_gl_error ("glCreateProgram");
388         glAttachShader (program, vertex_shader);
389         check_gl_error ("glAttachShader");
390         glAttachShader (program, fragment_shader);
391         check_gl_error ("glAttachShader");
392         glLinkProgram (program);
393         check_gl_error ("glLinkProgram");
394         GLint ok;
395         glGetProgramiv (program, GL_LINK_STATUS, &ok);
396         if (!ok) {
397                 GLint log_length;
398                 glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
399                 string log;
400                 if (log_length > 0) {
401                         char* log_char = new char[log_length];
402                         glGetProgramInfoLog(program, log_length, nullptr, log_char);
403                         log = string(log_char);
404                         delete[] log_char;
405                 }
406                 glDeleteProgram (program);
407                 throw GLError(String::compose("Could not link shader (%1)", log).c_str(), -1);
408         }
409         glDeleteShader (vertex_shader);
410         glDeleteShader (fragment_shader);
411
412         glUseProgram (program);
413
414         _fragment_type = glGetUniformLocation (program, "type");
415         check_gl_error ("glGetUniformLocation");
416         set_border_colour (program);
417
418         auto conversion = dcp::ColourConversion::rec709_to_xyz();
419         boost::numeric::ublas::matrix<double> matrix = conversion.xyz_to_rgb ();
420         GLfloat gl_matrix[] = {
421                 static_cast<float>(matrix(0, 0)), static_cast<float>(matrix(0, 1)), static_cast<float>(matrix(0, 2)), 0.0f,
422                 static_cast<float>(matrix(1, 0)), static_cast<float>(matrix(1, 1)), static_cast<float>(matrix(1, 2)), 0.0f,
423                 static_cast<float>(matrix(2, 0)), static_cast<float>(matrix(2, 1)), static_cast<float>(matrix(2, 2)), 0.0f,
424                 0.0f, 0.0f, 0.0f, 1.0f
425                 };
426
427         auto colour_conversion = glGetUniformLocation (program, "colour_conversion");
428         check_gl_error ("glGetUniformLocation");
429         glUniformMatrix4fv (colour_conversion, 1, GL_TRUE, gl_matrix);
430
431         glLineWidth (2.0f);
432 }
433
434
435 void
436 GLVideoView::set_border_colour (GLuint program)
437 {
438         auto uniform = glGetUniformLocation (program, "border_colour");
439         check_gl_error ("glGetUniformLocation");
440         auto colour = outline_content_colour ();
441         glUniform4f (uniform, colour.Red() / 255.0f, colour.Green() / 255.0f, colour.Blue() / 255.0f, 1.0f);
442         check_gl_error ("glUniform4f");
443 }
444
445
446 void
447 GLVideoView::draw (Position<int>, dcp::Size)
448 {
449         auto pad = pad_colour();
450         glClearColor(pad.Red() / 255.0, pad.Green() / 255.0, pad.Blue() / 255.0, 1.0);
451         glClear (GL_COLOR_BUFFER_BIT);
452         check_gl_error ("glClear");
453
454         auto const size = _canvas_size.load();
455         int const width = size.GetWidth();
456         int const height = size.GetHeight();
457
458         if (width < 64 || height < 0) {
459                 return;
460         }
461
462         glViewport (0, 0, width, height);
463         check_gl_error ("glViewport");
464
465         glBindVertexArray(_vao);
466         check_gl_error ("glBindVertexArray");
467         glUniform1i(_fragment_type, _optimise_for_j2k ? 1 : 2);
468         glDrawElements (GL_TRIANGLES, 6, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_video_texture));
469         if (_viewer->outline_content()) {
470                 glUniform1i(_fragment_type, 1);
471                 glDrawElements (GL_LINES, 8, GL_UNSIGNED_INT, reinterpret_cast<void*>(indices_border * sizeof(int)));
472                 check_gl_error ("glDrawElements");
473         }
474
475         glFlush();
476         check_gl_error ("glFlush");
477
478         _canvas->SwapBuffers();
479 }
480
481
482 void
483 GLVideoView::set_image (shared_ptr<const PlayerVideo> pv)
484 {
485         auto image = _optimise_for_j2k ? pv->raw_image() : pv->image(bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), VideoRange::FULL, false, true);
486
487         DCPOMATIC_ASSERT (!image->aligned());
488
489         /** If _optimise_for_j2k is true we render a XYZ image, doing the colourspace
490          *  conversion, scaling and video range conversion in the GL shader.
491          *  Othewise we render a RGB image without any shader-side processing.
492          */
493
494         /* XXX: video range conversion */
495         /* XXX: subs */
496
497         if (image->size() != _video_size) {
498                 _have_storage = false;
499         }
500
501         _video_size = image->size ();
502         glPixelStorei (GL_UNPACK_ALIGNMENT, _optimise_for_j2k ? 2 : 1);
503         check_gl_error ("glPixelStorei");
504
505         auto const format = _optimise_for_j2k ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
506
507         if (_have_storage) {
508                 glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, _video_size->width, _video_size->height, GL_RGB, format, image->data()[0]);
509                 check_gl_error ("glTexSubImage2D");
510         } else {
511                 glTexImage2D (GL_TEXTURE_2D, 0, _optimise_for_j2k ? GL_RGBA12 : GL_RGBA8, _video_size->width, _video_size->height, 0, GL_RGB, format, image->data()[0]);
512                 check_gl_error ("glTexImage2D");
513
514                 auto const canvas_size = _canvas_size.load();
515                 int const canvas_width = canvas_size.GetWidth();
516                 int const canvas_height = canvas_size.GetHeight();
517
518                 float const image_x = float(_video_size->width) / canvas_width;
519                 float const image_y = float(_video_size->height) / canvas_height;
520
521                 auto x_pixels_to_gl = [canvas_width](int x) {
522                         return (x * 2.0f / canvas_width) - 1.0f;
523                 };
524
525                 auto y_pixels_to_gl = [canvas_height](int y) {
526                         return (y * 2.0f / canvas_height) - 1.0f;
527                 };
528
529                 auto inter_position = player_video().first->inter_position();
530                 auto inter_size = player_video().first->inter_size();
531
532                 float const border_x1 = x_pixels_to_gl (inter_position.x) + 1.0f - image_x;
533                 float const border_y1 = y_pixels_to_gl (inter_position.y) + 1.0f - image_y;
534                 float const border_x2 = x_pixels_to_gl (inter_position.x + inter_size.width) + 1.0f - image_x;
535                 float const border_y2 = y_pixels_to_gl (inter_position.y + inter_size.height) + 1.0f - image_y;
536
537                 float vertices[] = {
538                         // positions                  // texture coords
539                          image_x,   image_y,   0.0f,  1.0f, 0.0f,   // video texture top right    (index 0)
540                          image_x,  -image_y,   0.0f,  1.0f, 1.0f,   // video texture bottom right (index 1)
541                         -image_x,  -image_y,   0.0f,  0.0f, 1.0f,   // video texture bottom left  (index 2)
542                         -image_x,   image_y,   0.0f,  0.0f, 0.0f,   // video texture top left     (index 3)
543                          border_x1, border_y1, 0.0f,  0.0f, 0.0f,   // border bottom left         (index 4)
544                          border_x1, border_y2, 0.0f,  0.0f, 0.0f,   // border top left            (index 5)
545                          border_x2, border_y2, 0.0f,  0.0f, 0.0f,   // border top right           (index 6)
546                          border_x2, border_y1, 0.0f,  0.0f, 0.0f,   // border bottom right        (index 7)
547                 };
548
549                 /* Set the vertex shader's input data (GL_ARRAY_BUFFER) */
550                 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
551                 check_gl_error ("glBufferData");
552
553                 _have_storage = true;
554         }
555
556         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
557         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
558         check_gl_error ("glTexParameteri");
559
560         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
561         glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
562         check_gl_error ("glTexParameterf");
563 }
564
565
566 void
567 GLVideoView::start ()
568 {
569         VideoView::start ();
570
571         boost::mutex::scoped_lock lm (_playing_mutex);
572         _playing = true;
573         _thread_work_condition.notify_all ();
574 }
575
576 void
577 GLVideoView::stop ()
578 {
579         boost::mutex::scoped_lock lm (_playing_mutex);
580         _playing = false;
581 }
582
583
584 void
585 GLVideoView::thread_playing ()
586 {
587         if (length() != dcpomatic::DCPTime()) {
588                 auto const next = position() + one_video_frame();
589
590                 if (next >= length()) {
591                         _viewer->finished ();
592                         return;
593                 }
594
595                 get_next_frame (false);
596                 set_image_and_draw ();
597         }
598
599         while (true) {
600                 optional<int> n = time_until_next_frame();
601                 if (!n || *n > 5) {
602                         break;
603                 }
604                 get_next_frame (true);
605                 add_dropped ();
606         }
607 }
608
609
610 void
611 GLVideoView::set_image_and_draw ()
612 {
613         auto pv = player_video().first;
614         if (pv) {
615                 set_image (pv);
616                 draw (pv->inter_position(), pv->inter_size());
617                 _viewer->image_changed (pv);
618         }
619 }
620
621
622 void
623 GLVideoView::thread ()
624 try
625 {
626         start_of_thread ("GLVideoView");
627
628 #if defined(DCPOMATIC_OSX)
629         /* Without this we see errors like
630          * ../src/osx/cocoa/glcanvas.mm(194): assert ""context"" failed in SwapBuffers(): should have current context [in thread 700006970000]
631          */
632         WXGLSetCurrentContext (_context->GetWXGLContext());
633 #else
634         if (!_setup_shaders_done) {
635                 setup_shaders ();
636                 _setup_shaders_done = true;
637         }
638 #endif
639
640 #if defined(DCPOMATIC_LINUX) && defined(DCPOMATIC_HAVE_GLX_SWAP_INTERVAL_EXT)
641         if (_canvas->IsExtensionSupported("GLX_EXT_swap_control")) {
642                 /* Enable vsync */
643                 Display* dpy = wxGetX11Display();
644                 glXSwapIntervalEXT (dpy, DefaultScreen(dpy), 1);
645                 _vsync_enabled = true;
646         }
647 #endif
648
649 #ifdef DCPOMATIC_WINDOWS
650         if (_canvas->IsExtensionSupported("WGL_EXT_swap_control")) {
651                 /* Enable vsync */
652                 PFNWGLSWAPINTERVALEXTPROC swap = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
653                 if (swap) {
654                         swap (1);
655                         _vsync_enabled = true;
656                 }
657         }
658
659 #endif
660
661 #ifdef DCPOMATIC_OSX
662         /* Enable vsync */
663         GLint swapInterval = 1;
664         CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
665         _vsync_enabled = true;
666 #endif
667
668         _video_texture.reset(new Texture());
669         _video_texture->bind();
670
671         while (true) {
672                 boost::mutex::scoped_lock lm (_playing_mutex);
673                 while (!_playing && !_one_shot) {
674                         _thread_work_condition.wait (lm);
675                 }
676                 lm.unlock ();
677
678                 if (_playing) {
679                         thread_playing ();
680                 } else if (_one_shot) {
681                         _one_shot = false;
682                         set_image_and_draw ();
683                 }
684
685                 boost::this_thread::interruption_point ();
686                 dcpomatic_sleep_milliseconds (time_until_next_frame().get_value_or(0));
687         }
688
689         /* XXX: leaks _context, but that seems preferable to deleting it here
690          * without also deleting the wxGLCanvas.
691          */
692 }
693 catch (...)
694 {
695         store_current ();
696 }
697
698
699 VideoView::NextFrameResult
700 GLVideoView::display_next_frame (bool non_blocking)
701 {
702         NextFrameResult const r = get_next_frame (non_blocking);
703         request_one_shot ();
704         return r;
705 }
706
707
708 void
709 GLVideoView::request_one_shot ()
710 {
711         boost::mutex::scoped_lock lm (_playing_mutex);
712         _one_shot = true;
713         _thread_work_condition.notify_all ();
714 }
715
716
717 Texture::Texture ()
718 {
719         glGenTextures (1, &_name);
720         check_gl_error ("glGenTextures");
721 }
722
723
724 Texture::~Texture ()
725 {
726         glDeleteTextures (1, &_name);
727 }
728
729
730 void
731 Texture::bind ()
732 {
733         glBindTexture(GL_TEXTURE_2D, _name);
734         check_gl_error ("glBindTexture");
735 }
736