1c7ddc75701e8fbcbebc5779aebe4e32e3bc6028
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / playback3d.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2009 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program 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  * This program 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 this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #define GL_GLEXT_PROTOTYPES
23
24 #include "bccolors.h"
25 #include "bcsignals.h"
26 #include "bcwindowbase.h"
27 #include "canvas.h"
28 #include "clip.h"
29 #include "condition.h"
30 #include "edl.h"
31 #include "maskautos.h"
32 #include "maskauto.h"
33 #include "mutex.h"
34 #include "mwindow.h"
35 #include "overlayframe.inc"
36 #include "overlayframe.h"
37 #include "playback3d.h"
38 #include "pluginclient.h"
39 #include "pluginvclient.h"
40 #include "edlsession.h"
41 #include "transportque.inc"
42 #include "vframe.h"
43
44 #ifdef HAVE_GL
45 #include <GL/gl.h>
46 #include <GL/glext.h>
47 #include <GL/glu.h>
48 #endif
49
50 #include <string.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53
54 #define QQ(q)#q
55 #define SS(s)QQ(s)
56
57
58 // Shaders
59 // These should be passed to VFrame::make_shader to construct shaders.
60 // Can't hard code sampler2D
61
62
63 #ifdef HAVE_GL
64 static const char *yuv_to_rgb_frag =
65         "uniform sampler2D tex;\n"
66         "uniform mat3 yuv_to_rgb_matrix;\n"
67         "uniform float yminf;\n"
68         "void main()\n"
69         "{\n"
70         "       vec4 yuva = texture2D(tex, gl_TexCoord[0].st);\n"
71         "       yuva.rgb -= vec3(yminf, 0.5, 0.5);\n"
72         "       gl_FragColor = vec4(yuv_to_rgb_matrix * yuva.rgb, yuva.a);\n"
73         "}\n";
74
75 static const char *yuva_to_yuv_frag =
76         "uniform sampler2D tex;\n"
77         "void main()\n"
78         "{\n"
79         "       vec4 yuva = texture2D(tex, gl_TexCoord[0].st);\n"
80         "       float a = yuva.a;\n"
81         "       float anti_a = 1.0 - a;\n"
82         "       yuva.r *= a;\n"
83         "       yuva.g = yuva.g * a + 0.5 * anti_a;\n"
84         "       yuva.b = yuva.b * a + 0.5 * anti_a;\n"
85         "       yuva.a = 1.0;\n"
86         "       gl_FragColor = yuva;\n"
87         "}\n";
88
89 static const char *yuva_to_rgb_frag =
90         "uniform sampler2D tex;\n"
91         "uniform mat3 yuv_to_rgb_matrix;\n"
92         "uniform float yminf;\n"
93         "void main()\n"
94         "{\n"
95         "       vec4 yuva = texture2D(tex, gl_TexCoord[0].st);\n"
96         "       yuva.rgb -= vec3(yminf, 0.5, 0.5);\n"
97         "       yuva.rgb = yuv_to_rgb_matrix * yuva.rgb;\n"
98         "       yuva.rgb *= yuva.a;\n"
99         "       yuva.a = 1.0;\n"
100         "       gl_FragColor = yuva;\n"
101         "}\n";
102
103 static const char *rgb_to_yuv_frag =
104         "uniform sampler2D tex;\n"
105         "uniform mat3 rgb_to_yuv_matrix;\n"
106         "uniform float yminf;\n"
107         "void main()\n"
108         "{\n"
109         "       vec4 rgba = texture2D(tex, gl_TexCoord[0].st);\n"
110         "       rgba.rgb = rgb_to_yuv_matrix * rgba.rgb;\n"
111         "       rgba.rgb += vec3(yminf, 0.5, 0.5);\n"
112         "       gl_FragColor = rgba;\n"
113         "}\n";
114
115
116 static const char *rgba_to_rgb_frag =
117         "uniform sampler2D tex;\n"
118         "void main()\n"
119         "{\n"
120         "       vec4 rgba = texture2D(tex, gl_TexCoord[0].st);\n"
121         "       rgba.rgb *= rgba.a;\n"
122         "       rgba.a = 1.0;\n"
123         "       gl_FragColor = rgba;\n"
124         "}\n";
125
126 static const char *rgba_to_yuv_frag =
127         "uniform sampler2D tex;\n"
128         "uniform mat3 rgb_to_yuv_matrix;\n"
129         "uniform float yminf;\n"
130         "void main()\n"
131         "{\n"
132         "       vec4 rgba = texture2D(tex, gl_TexCoord[0].st);\n"
133         "       rgba.rgb *= rgba.a;\n"
134         "       rgba.a = 1.0;\n"
135         "       rgba.rgb = rgb_to_yuv_matrix * rgba.rgb;\n"
136         "       rgba.rgb += vec3(yminf, 0.5, 0.5);\n"
137         "       gl_FragColor = rgba;\n"
138         "}\n";
139
140 //static const char *rgba_to_rgb_flatten =
141 //      "void main() {\n"
142 //      "       gl_FragColor.rgb *= gl_FragColor.a;\n"
143 //      "       gl_FragColor.a = 1.0;\n"
144 //      "}\n";
145
146 #define GL_STD_BLEND(FN) \
147 static const char *blend_##FN##_frag = \
148         "uniform sampler2D tex2;\n" \
149         "uniform vec2 tex2_dimensions;\n" \
150         "uniform float alpha;\n" \
151         "void main() {\n" \
152         "       vec4 canvas = texture2D(tex2, gl_FragCoord.xy / tex2_dimensions);\n" \
153         "       vec4 result;\n" \
154         "       result.rgb = " SS(COLOR_##FN(1.0, gl_FragColor.rgb, gl_FragColor.a, canvas.rgb, canvas.a)) ";\n" \
155         "       result.a = " SS(ALPHA_##FN(1.0, gl_FragColor.a, canvas.a)) ";\n" \
156         "       gl_FragColor = mix(canvas, result, alpha);\n" \
157         "}\n"
158
159 #define GL_VEC_BLEND(FN) \
160 static const char *blend_##FN##_frag = \
161         "uniform sampler2D tex2;\n" \
162         "uniform vec2 tex2_dimensions;\n" \
163         "uniform float alpha;\n" \
164         "void main() {\n" \
165         "       vec4 canvas = texture2D(tex2, gl_FragCoord.xy / tex2_dimensions);\n" \
166         "       vec4 result;\n" \
167         "       result.r = " SS(COLOR_##FN(1.0, gl_FragColor.r, gl_FragColor.a, canvas.r, canvas.a)) ";\n" \
168         "       result.g = " SS(COLOR_##FN(1.0, gl_FragColor.g, gl_FragColor.a, canvas.g, canvas.a)) ";\n" \
169         "       result.b = " SS(COLOR_##FN(1.0, gl_FragColor.b, gl_FragColor.a, canvas.b, canvas.a)) ";\n" \
170         "       result.a = " SS(ALPHA_##FN(1.0, gl_FragColor.a, canvas.a)) ";\n" \
171         "       result = clamp(result, 0.0, 1.0);\n" \
172         "       gl_FragColor = mix(canvas, result, alpha);\n" \
173         "}\n"
174
175 #undef mabs
176 #define mabs abs
177 #undef mmin
178 #define mmin min
179 #undef mmax
180 #define mmax max
181
182 #undef ZERO
183 #define ZERO 0.0
184 #undef ONE
185 #define ONE 1.0
186 #undef TWO
187 #define TWO 2.0
188
189 // NORMAL
190 static const char *blend_NORMAL_frag =
191         "uniform sampler2D tex2;\n"
192         "uniform vec2 tex2_dimensions;\n"
193         "uniform float alpha;\n"
194         "void main() {\n"
195         "       vec4 canvas = texture2D(tex2, gl_FragCoord.xy / tex2_dimensions);\n"
196         "       vec4 result = mix(canvas, gl_FragColor, gl_FragColor.a);\n"
197         "       gl_FragColor = mix(canvas, result, alpha);\n"
198         "}\n";
199
200 // REPLACE
201 static const char *blend_REPLACE_frag =
202         "uniform float alpha;\n"
203         "void main() {\n"
204         "}\n";
205
206 // ADDITION
207 static const char *blend_ADDITION_frag =
208         "uniform sampler2D tex2;\n"
209         "uniform vec2 tex2_dimensions;\n"
210         "uniform float alpha;\n"
211         "void main() {\n"
212         "       vec4 canvas = texture2D(tex2, gl_FragCoord.xy / tex2_dimensions);\n"
213         "       vec4 result = clamp(gl_FragColor + canvas, 0.0, 1.0);\n"
214         "       gl_FragColor = mix(canvas, result, alpha);\n"
215         "}\n";
216
217 // SUBTRACT
218 static const char *blend_SUBTRACT_frag =
219         "uniform sampler2D tex2;\n"
220         "uniform vec2 tex2_dimensions;\n"
221         "uniform float alpha;\n"
222         "void main() {\n"
223         "       vec4 canvas = texture2D(tex2, gl_FragCoord.xy / tex2_dimensions);\n"
224         "       vec4 result = clamp(gl_FragColor - canvas, 0.0, 1.0);\n"
225         "       gl_FragColor = mix(canvas, result, alpha);\n"
226         "}\n";
227
228 GL_STD_BLEND(MULTIPLY);
229 GL_VEC_BLEND(DIVIDE);
230 GL_VEC_BLEND(MAX);
231 GL_VEC_BLEND(MIN);
232 GL_VEC_BLEND(DARKEN);
233 GL_VEC_BLEND(LIGHTEN);
234 GL_STD_BLEND(DST);
235 GL_STD_BLEND(DST_ATOP);
236 GL_STD_BLEND(DST_IN);
237 GL_STD_BLEND(DST_OUT);
238 GL_STD_BLEND(DST_OVER);
239 GL_STD_BLEND(SRC);
240 GL_STD_BLEND(SRC_ATOP);
241 GL_STD_BLEND(SRC_IN);
242 GL_STD_BLEND(SRC_OUT);
243 GL_STD_BLEND(SRC_OVER);
244 GL_STD_BLEND(AND);
245 GL_STD_BLEND(OR);
246 GL_STD_BLEND(XOR);
247 GL_VEC_BLEND(OVERLAY);
248 GL_STD_BLEND(SCREEN);
249 GL_VEC_BLEND(BURN);
250 GL_VEC_BLEND(DODGE);
251 GL_VEC_BLEND(HARDLIGHT);
252 GL_VEC_BLEND(SOFTLIGHT);
253 GL_VEC_BLEND(DIFFERENCE);
254
255 static const char *read_texture_frag =
256         "uniform sampler2D tex;\n"
257         "void main()\n"
258         "{\n"
259         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
260         "}\n";
261
262 static const char *in_vertex_frag =
263         "#version 430 // vertex shader\n"
264         "in vec3 in_pos;\n"
265         "void main() {\n"
266         "       gl_Position = vec4(in_pos-vec3(0.5,0.5,0.), .5);\n"
267         "}\n";
268
269 static const char *feather_frag =
270         "#version 430\n"
271         "layout(location=0) out vec4 color;\n"
272         "uniform sampler2D tex;\n"
273 // apparently, only doubles index properly in shared buffers
274         "buffer buf { dvec2 points[]; };\n"
275         "uniform float r;\n"
276         "uniform float v;\n"
277         "void main() {\n"
278         "       vec2 tex_st = gl_FragCoord.xy/textureSize(tex,0);\n"
279         "       color = texture(tex, tex_st);\n"
280         "       if( r==0. ) return;\n"
281         "       float rv = r*v>0. ? 1 : -1;\n"
282         "       float rr = r*r, dr = 1./rr;\n"
283         "       float vv = v>=0 ? 1.-v : 1.+v;\n"
284         "       float fg = rv>=0 ? vv : 1.;\n"
285         "       float bg = rv>=0 ? 1. : vv;\n"
286         "       int len = points.length();\n"
287         "       for( int i=0; i<len; ++i ) {\n"
288         "               float dx = float(points[i].x) - gl_FragCoord.x;\n"
289         "               float dy = float(points[i].y) - gl_FragCoord.y;\n"
290         "               float dd = dx*dx + dy*dy;\n"
291         "               if( dd >= rr ) continue;\n"
292         "               float d = dd*dr;\n"
293         "               float a = (1.-d)*fg + d*bg;\n"
294         "               if( rv*(color.a-a) > 0 ) color = vec4(a);\n"
295         "       }\n"
296         "}\n";
297
298 static const char *multiply_mask4_frag =
299         "uniform sampler2D tex;\n"
300         "uniform sampler2D tex1;\n"
301         "void main()\n"
302         "{\n"
303         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
304         "       gl_FragColor.a *= texture2D(tex1, gl_TexCoord[0].st).r;\n"
305         "}\n";
306
307 static const char *multiply_mask3_frag =
308         "uniform sampler2D tex;\n"
309         "uniform sampler2D tex1;\n"
310         "void main()\n"
311         "{\n"
312         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
313         "       float a = texture2D(tex1, gl_TexCoord[0].st).r;\n"
314         "       gl_FragColor.rgb *= vec3(a, a, a);\n"
315         "}\n";
316
317 static const char *multiply_yuvmask3_frag =
318         "uniform sampler2D tex;\n"
319         "uniform sampler2D tex1;\n"
320         "void main()\n"
321         "{\n"
322         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
323         "       float a = texture2D(tex1, gl_TexCoord[0].st).r;\n"
324         "       gl_FragColor.gb -= vec2(0.5, 0.5);\n"
325         "       gl_FragColor.rgb *= vec3(a, a, a);\n"
326         "       gl_FragColor.gb += vec2(0.5, 0.5);\n"
327         "}\n";
328
329 static const char *fade_rgba_frag =
330         "uniform sampler2D tex;\n"
331         "uniform float alpha;\n"
332         "void main()\n"
333         "{\n"
334         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
335         "       gl_FragColor.a *= alpha;\n"
336         "}\n";
337
338 static const char *fade_yuv_frag =
339         "uniform sampler2D tex;\n"
340         "uniform float alpha;\n"
341         "void main()\n"
342         "{\n"
343         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
344         "       gl_FragColor.r *= alpha;\n"
345         "       gl_FragColor.gb -= vec2(0.5, 0.5);\n"
346         "       gl_FragColor.g *= alpha;\n"
347         "       gl_FragColor.b *= alpha;\n"
348         "       gl_FragColor.gb += vec2(0.5, 0.5);\n"
349         "}\n";
350
351 #endif
352
353
354 Playback3DCommand::Playback3DCommand()
355  : BC_SynchronousCommand()
356 {
357         canvas = 0;
358         is_nested = 0;
359 }
360
361 void Playback3DCommand::copy_from(BC_SynchronousCommand *command)
362 {
363         Playback3DCommand *ptr = (Playback3DCommand*)command;
364         this->canvas = ptr->canvas;
365         this->is_cleared = ptr->is_cleared;
366
367         this->in_x1 = ptr->in_x1;
368         this->in_y1 = ptr->in_y1;
369         this->in_x2 = ptr->in_x2;
370         this->in_y2 = ptr->in_y2;
371         this->out_x1 = ptr->out_x1;
372         this->out_y1 = ptr->out_y1;
373         this->out_x2 = ptr->out_x2;
374         this->out_y2 = ptr->out_y2;
375         this->alpha = ptr->alpha;
376         this->mode = ptr->mode;
377         this->interpolation_type = ptr->interpolation_type;
378
379         this->input = ptr->input;
380         this->start_position_project = ptr->start_position_project;
381         this->keyframe_set = ptr->keyframe_set;
382         this->keyframe = ptr->keyframe;
383         this->default_auto = ptr->default_auto;
384         this->plugin_client = ptr->plugin_client;
385         this->want_texture = ptr->want_texture;
386         this->is_nested = ptr->is_nested;
387         this->dst_cmodel = ptr->dst_cmodel;
388
389         BC_SynchronousCommand::copy_from(command);
390 }
391
392 Playback3D::Playback3D(MWindow *mwindow)
393  : BC_Synchronous()
394 {
395         this->mwindow = mwindow;
396         temp_texture = 0;
397 }
398
399 Playback3D::~Playback3D()
400 {
401 }
402
403
404
405
406 BC_SynchronousCommand* Playback3D::new_command()
407 {
408         return new Playback3DCommand;
409 }
410
411
412
413 void Playback3D::handle_command(BC_SynchronousCommand *command)
414 {
415 //printf("Playback3D::handle_command 1 %d\n", command->command);
416         switch(command->command)
417         {
418                 case Playback3DCommand::WRITE_BUFFER:
419                         write_buffer_sync((Playback3DCommand*)command);
420                         break;
421
422                 case Playback3DCommand::CLEAR_OUTPUT:
423                         clear_output_sync((Playback3DCommand*)command);
424                         break;
425
426                 case Playback3DCommand::CLEAR_INPUT:
427                         clear_input_sync((Playback3DCommand*)command);
428                         break;
429
430                 case Playback3DCommand::DO_CAMERA:
431                         do_camera_sync((Playback3DCommand*)command);
432                         break;
433
434                 case Playback3DCommand::OVERLAY:
435                         overlay_sync((Playback3DCommand*)command);
436                         break;
437
438                 case Playback3DCommand::DO_FADE:
439                         do_fade_sync((Playback3DCommand*)command);
440                         break;
441
442                 case Playback3DCommand::DO_MASK:
443                         do_mask_sync((Playback3DCommand*)command);
444                         break;
445
446                 case Playback3DCommand::PLUGIN:
447                         run_plugin_sync((Playback3DCommand*)command);
448                         break;
449
450                 case Playback3DCommand::COPY_FROM:
451                         copy_from_sync((Playback3DCommand*)command);
452                         break;
453
454                 case Playback3DCommand::CONVERT_CMODEL:
455                         convert_cmodel_sync((Playback3DCommand*)command);
456                         break;
457
458 //              case Playback3DCommand::DRAW_REFRESH:
459 //                      draw_refresh_sync((Playback3DCommand*)command);
460 //                      break;
461         }
462 //printf("Playback3D::handle_command 10\n");
463 }
464
465
466
467
468 void Playback3D::copy_from(Canvas *canvas,
469         VFrame *dst,
470         VFrame *src,
471         int want_texture)
472 {
473         Playback3DCommand command;
474         command.command = Playback3DCommand::COPY_FROM;
475         command.canvas = canvas;
476         command.frame = dst;
477         command.input = src;
478         command.want_texture = want_texture;
479         send_command(&command);
480 }
481
482 void Playback3D::copy_from_sync(Playback3DCommand *command)
483 {
484 #ifdef HAVE_GL
485         BC_WindowBase *window =
486                 command->canvas->lock_canvas("Playback3D::copy_from_sync");
487         if( window ) {
488                 window->enable_opengl();
489                 glFinish();
490                 int w = command->input->get_w();
491                 int h = command->input->get_h();
492
493                 if(command->input->get_opengl_state() == VFrame::SCREEN &&
494                         w == command->frame->get_w() && h == command->frame->get_h())
495                 {
496 // printf("Playback3D::copy_from_sync 1 %d %d %d %d %d\n",
497 // command->input->get_w(),
498 // command->input->get_h(),
499 // command->frame->get_w(),
500 // command->frame->get_h(),
501 // command->frame->get_color_model());
502 // With NVidia at least,
503                         if(w % 4)
504                         {
505                                 printf("Playback3D::copy_from_sync: w=%d not supported because it is not divisible by 4.\n", w);
506                         }
507                         else
508 // Copy to texture
509                         if(command->want_texture)
510                         {
511 //printf("Playback3D::copy_from_sync 1 dst=%p src=%p\n", command->frame, command->input);
512 // Screen_to_texture requires the source pbuffer enabled.
513                                 command->input->enable_opengl();
514                                 command->frame->screen_to_texture();
515                                 command->frame->set_opengl_state(VFrame::TEXTURE);
516                         }
517                         else
518 // Copy to RAM
519                         {
520                                 command->input->to_texture();
521                                 command->input->bind_texture(0);
522                                 command->frame->enable_opengl();
523                                 command->frame->init_screen();
524                                 unsigned int shader = BC_CModels::is_yuv(command->input->get_color_model()) ?
525                                         VFrame::make_shader(0, yuv_to_rgb_frag, 0) : 0;
526                                 if( shader > 0 ) {
527                                         glUseProgram(shader);
528                                         int variable = glGetUniformLocation(shader, "tex");
529                                         glUniform1i(variable, 0);
530                                         BC_GL_YUV_TO_RGB(shader);
531                                 }
532                                 else
533                                         glUseProgram(0);
534                                 command->input->draw_texture(1);
535                                 command->frame->screen_to_ram();
536                                 glUseProgram(0);
537                         }
538                 }
539                 else
540                 {
541                         printf("Playback3D::copy_from_sync: invalid formats opengl_state=%d %dx%d -> %dx%d\n",
542                                 command->input->get_opengl_state(), w, h,
543                                 command->frame->get_w(), command->frame->get_h());
544                 }
545         }
546         command->canvas->unlock_canvas();
547 #endif
548 }
549
550
551
552
553 // void Playback3D::draw_refresh(Canvas *canvas,
554 //      VFrame *frame,
555 //      float in_x1,
556 //      float in_y1,
557 //      float in_x2,
558 //      float in_y2,
559 //      float out_x1,
560 //      float out_y1,
561 //      float out_x2,
562 //      float out_y2)
563 // {
564 //      Playback3DCommand command;
565 //      command.command = Playback3DCommand::DRAW_REFRESH;
566 //      command.canvas = canvas;
567 //      command.frame = frame;
568 //      command.in_x1 = in_x1;
569 //      command.in_y1 = in_y1;
570 //      command.in_x2 = in_x2;
571 //      command.in_y2 = in_y2;
572 //      command.out_x1 = out_x1;
573 //      command.out_y1 = out_y1;
574 //      command.out_x2 = out_x2;
575 //      command.out_y2 = out_y2;
576 //      send_command(&command);
577 // }
578 //
579 // void Playback3D::draw_refresh_sync(Playback3DCommand *command)
580 // {
581 // #ifdef HAVE_GL
582 //      BC_WindowBase *window =
583 //              command->canvas->lock_canvas("Playback3D::draw_refresh_sync");
584 //      if( window ) {
585 //              window->enable_opengl();
586 //
587 // // Read output pbuffer back to RAM in project colormodel
588 // // RGB 8bit is fastest for OpenGL to read back.
589 //              command->frame->reallocate(0,
590 //                      0,
591 //                      0,
592 //                      0,
593 //                      command->frame->get_w(),
594 //                      command->frame->get_h(),
595 //                      BC_RGB888,
596 //                      -1);
597 //              command->frame->screen_to_ram();
598 //
599 //              window->clear_box(0,
600 //                                              0,
601 //                                              window->get_w(),
602 //                                              window->get_h());
603 //              window->draw_vframe(command->frame,
604 //                                                      (int)command->out_x1,
605 //                                                      (int)command->out_y1,
606 //                                                      (int)(command->out_x2 - command->out_x1),
607 //                                                      (int)(command->out_y2 - command->out_y1),
608 //                                                      (int)command->in_x1,
609 //                                                      (int)command->in_y1,
610 //                                                      (int)(command->in_x2 - command->in_x1),
611 //                                                      (int)(command->in_y2 - command->in_y1),
612 //                                                      0);
613 //
614 //      }
615 //      command->canvas->unlock_canvas();
616 // #endif
617 // }
618
619
620
621
622
623 void Playback3D::write_buffer(Canvas *canvas,
624         VFrame *frame,
625         float in_x1,
626         float in_y1,
627         float in_x2,
628         float in_y2,
629         float out_x1,
630         float out_y1,
631         float out_x2,
632         float out_y2,
633         int is_cleared)
634 {
635         Playback3DCommand command;
636         command.command = Playback3DCommand::WRITE_BUFFER;
637         command.canvas = canvas;
638         command.frame = frame;
639         command.in_x1 = in_x1;
640         command.in_y1 = in_y1;
641         command.in_x2 = in_x2;
642         command.in_y2 = in_y2;
643         command.out_x1 = out_x1;
644         command.out_y1 = out_y1;
645         command.out_x2 = out_x2;
646         command.out_y2 = out_y2;
647         command.is_cleared = is_cleared;
648         send_command(&command);
649 }
650
651
652 void Playback3D::write_buffer_sync(Playback3DCommand *command)
653 {
654 #ifdef HAVE_GL
655         BC_WindowBase *window =
656                 command->canvas->lock_canvas("Playback3D::write_buffer_sync");
657         if( window ) {
658                 window->enable_opengl();
659 // Update hidden cursor
660                 window->update_video_cursor();
661                 command->frame->enable_opengl();
662                 command->frame->init_screen();
663 //printf("Playback3D::write_buffer_sync 1 %d\n", window->get_id());
664                 int frame_state = command->frame->get_opengl_state();
665                 if( frame_state != VFrame::TEXTURE )
666                         command->frame->to_texture();
667                 if( frame_state != VFrame::RAM ) {
668                         command->in_y1 = command->frame->get_h() - command->in_y1;
669                         command->in_y2 = command->frame->get_h() - command->in_y2;
670                 }
671                 window->enable_opengl();
672                 draw_output(command, 1);
673                 command->frame->set_opengl_state(frame_state);
674         }
675         command->canvas->unlock_canvas();
676 #endif
677 }
678
679
680
681 void Playback3D::draw_output(Playback3DCommand *command, int flip_y)
682 {
683 #ifdef HAVE_GL
684         int texture_id = command->frame->get_texture_id();
685         BC_WindowBase *window = command->canvas->get_canvas();
686
687 // printf("Playback3D::draw_output 1 texture_id=%d window=%p\n",
688 // texture_id,
689 // command->canvas->get_canvas());
690
691
692
693
694 // If virtual console is being used, everything in this function has
695 // already been done except the page flip.
696         if(texture_id >= 0)
697         {
698                 canvas_w = window->get_w();
699                 canvas_h = window->get_h();
700                 VFrame::init_screen(canvas_w, canvas_h);
701                 int color_model = command->frame->get_color_model();
702                 int is_yuv = BC_CModels::is_yuv(color_model);
703
704                 if(!command->is_cleared)
705                 {
706 // If we get here, the virtual console was not used.
707                         init_frame(command, 0);
708                 }
709
710 // Texture
711 // Undo any previous shader settings
712                 command->frame->bind_texture(0);
713
714 // Convert colormodel
715                 unsigned int shader = is_yuv ? VFrame::make_shader(0, yuv_to_rgb_frag, 0) : 0;
716                 if( shader > 0 ) {
717                         glUseProgram(shader);
718 // Set texture unit of the texture
719                         int variable = glGetUniformLocation(shader, "tex");
720                         glUniform1i(variable, 0);
721                         BC_GL_YUV_TO_RGB(shader);
722                 }
723
724 //              if(BC_CModels::components(color_model) == 4)
725 //              {
726 //                      glEnable(GL_BLEND);
727 //                      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
728 //              }
729
730                 command->frame->draw_texture(
731                         command->in_x1, command->in_y1, command->in_x2, command->in_y2,
732                         command->out_x1, command->out_y1, command->out_x2, command->out_y2,
733                         flip_y);
734
735
736 //printf("Playback3D::draw_output 2 %f,%f %f,%f -> %f,%f %f,%f\n",
737 // command->in_x1, command->in_y1, command->in_x2, command->in_y2,
738 // command->out_x1, command->out_y1, command->out_x2, command->out_y2);
739
740                 glUseProgram(0);
741
742                 command->canvas->get_canvas()->flip_opengl();
743
744         }
745 #endif
746 }
747
748
749 void Playback3D::init_frame(Playback3DCommand *command, int is_yuv)
750 {
751 #ifdef HAVE_GL
752         float gbuv = is_yuv ? 0.5 : 0.0;
753         glClearColor(0.0, gbuv, gbuv, 0.0);
754         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
755 #endif
756 }
757
758
759 void Playback3D::clear_output(Canvas *canvas, VFrame *output)
760 {
761         Playback3DCommand command;
762         command.command = Playback3DCommand::CLEAR_OUTPUT;
763         command.canvas = canvas;
764         command.frame = output;
765         send_command(&command);
766 }
767
768 void Playback3D::clear_output_sync(Playback3DCommand *command)
769 {
770 #ifdef HAVE_GL
771         BC_WindowBase *window =
772                 command->canvas->lock_canvas("Playback3D::clear_output_sync");
773         if( window ) {
774 // If we get here, the virtual console is being used.
775                 command->canvas->get_canvas()->enable_opengl();
776                 int is_yuv = 0;
777 // Using pbuffer for refresh frame.
778                 if( command->frame ) {
779                         command->frame->enable_opengl();
780                         int color_model = command->canvas->mwindow->edl->session->color_model;
781                         is_yuv = BC_CModels::is_yuv(color_model);
782                 }
783
784                 init_frame(command, is_yuv);
785         }
786         command->canvas->unlock_canvas();
787 #endif
788 }
789
790
791 void Playback3D::clear_input(Canvas *canvas, VFrame *frame)
792 {
793         Playback3DCommand command;
794         command.command = Playback3DCommand::CLEAR_INPUT;
795         command.canvas = canvas;
796         command.frame = frame;
797         send_command(&command);
798 }
799
800 void Playback3D::clear_input_sync(Playback3DCommand *command)
801 {
802 #ifdef HAVE_GL
803         BC_WindowBase *window =
804                 command->canvas->lock_canvas("Playback3D::clear_input_sync");
805         if( window ) {
806                 command->canvas->get_canvas()->enable_opengl();
807                 command->frame->enable_opengl();
808                 command->frame->clear_pbuffer();
809                 command->frame->set_opengl_state(VFrame::SCREEN);
810         }
811         command->canvas->unlock_canvas();
812 #endif
813 }
814
815 void Playback3D::do_camera(Canvas *canvas,
816         VFrame *output,
817         VFrame *input,
818         float in_x1,
819         float in_y1,
820         float in_x2,
821         float in_y2,
822         float out_x1,
823         float out_y1,
824         float out_x2,
825         float out_y2)
826 {
827         Playback3DCommand command;
828         command.command = Playback3DCommand::DO_CAMERA;
829         command.canvas = canvas;
830         command.input = input;
831         command.frame = output;
832         command.in_x1 = in_x1;
833         command.in_y1 = in_y1;
834         command.in_x2 = in_x2;
835         command.in_y2 = in_y2;
836         command.out_x1 = out_x1;
837         command.out_y1 = out_y1;
838         command.out_x2 = out_x2;
839         command.out_y2 = out_y2;
840         send_command(&command);
841 }
842
843 void Playback3D::do_camera_sync(Playback3DCommand *command)
844 {
845 #ifdef HAVE_GL
846         BC_WindowBase *window =
847                 command->canvas->lock_canvas("Playback3D::do_camera_sync");
848         if( window ) {
849                 command->canvas->get_canvas()->enable_opengl();
850
851                 command->input->to_texture();
852                 command->frame->enable_opengl();
853                 command->frame->init_screen();
854                 command->frame->clear_pbuffer();
855
856                 command->input->bind_texture(0);
857 // Must call draw_texture in input frame to get the texture coordinates right.
858
859 // printf("Playback3D::do_camera_sync 1 %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f\n",
860 // command->in_x1,
861 // command->in_y2,
862 // command->in_x2,
863 // command->in_y1,
864 // command->out_x1,
865 // (float)command->input->get_h() - command->out_y1,
866 // command->out_x2,
867 // (float)command->input->get_h() - command->out_y2);
868                 command->input->draw_texture(
869                         command->in_x1, command->in_y2,
870                         command->in_x2, command->in_y1,
871                         command->out_x1,
872                         (float)command->frame->get_h() - command->out_y1,
873                         command->out_x2,
874                         (float)command->frame->get_h() - command->out_y2);
875
876
877                 command->frame->set_opengl_state(VFrame::SCREEN);
878                 command->frame->screen_to_ram();
879         }
880         command->canvas->unlock_canvas();
881 #endif
882 }
883
884 void Playback3D::overlay(Canvas *canvas, VFrame *input,
885         float in_x1, float in_y1, float in_x2, float in_y2,
886         float out_x1, float out_y1, float out_x2, float out_y2,
887         float alpha, int mode, int interpolation_type,
888         VFrame *output, int is_nested)
889 {
890         Playback3DCommand command;
891         command.command = Playback3DCommand::OVERLAY;
892         command.canvas = canvas;
893         command.frame = output;
894         command.input = input;
895         command.in_x1 = in_x1;
896         command.in_y1 = in_y1;
897         command.in_x2 = in_x2;
898         command.in_y2 = in_y2;
899         command.out_x1 = out_x1;
900         command.out_y1 = out_y1;
901         command.out_x2 = out_x2;
902         command.out_y2 = out_y2;
903         command.alpha = alpha;
904         command.mode = mode;
905         command.interpolation_type = interpolation_type;
906         command.is_nested = is_nested;
907         send_command(&command);
908 }
909
910 void Playback3D::overlay_sync(Playback3DCommand *command)
911 {
912 #ifdef HAVE_GL
913 // To do these operations, we need to copy the input buffer to a texture
914 // and blend 2 textures in a shader
915         static const char * const overlay_shaders[TRANSFER_TYPES] = {
916                 blend_NORMAL_frag,      // TRANSFER_NORMAL
917                 blend_ADDITION_frag,    // TRANSFER_ADDITION
918                 blend_SUBTRACT_frag,    // TRANSFER_SUBTRACT
919                 blend_MULTIPLY_frag,    // TRANSFER_MULTIPLY
920                 blend_DIVIDE_frag,      // TRANSFER_DIVIDE
921                 blend_REPLACE_frag,     // TRANSFER_REPLACE
922                 blend_MAX_frag,         // TRANSFER_MAX
923                 blend_MIN_frag,         // TRANSFER_MIN
924                 blend_DARKEN_frag,      // TRANSFER_DARKEN
925                 blend_LIGHTEN_frag,     // TRANSFER_LIGHTEN
926                 blend_DST_frag,         // TRANSFER_DST
927                 blend_DST_ATOP_frag,    // TRANSFER_DST_ATOP
928                 blend_DST_IN_frag,      // TRANSFER_DST_IN
929                 blend_DST_OUT_frag,     // TRANSFER_DST_OUT
930                 blend_DST_OVER_frag,    // TRANSFER_DST_OVER
931                 blend_SRC_frag,         // TRANSFER_SRC
932                 blend_SRC_ATOP_frag,    // TRANSFER_SRC_ATOP
933                 blend_SRC_IN_frag,      // TRANSFER_SRC_IN
934                 blend_SRC_OUT_frag,     // TRANSFER_SRC_OUT
935                 blend_SRC_OVER_frag,    // TRANSFER_SRC_OVER
936                 blend_AND_frag,         // TRANSFER_AND
937                 blend_OR_frag,          // TRANSFER_OR
938                 blend_XOR_frag,         // TRANSFER_XOR
939                 blend_OVERLAY_frag,     // TRANSFER_OVERLAY
940                 blend_SCREEN_frag,      // TRANSFER_SCREEN
941                 blend_BURN_frag,        // TRANSFER_BURN
942                 blend_DODGE_frag,       // TRANSFER_DODGE
943                 blend_HARDLIGHT_frag,   // TRANSFER_HARDLIGHT
944                 blend_SOFTLIGHT_frag,   // TRANSFER_SOFTLIGHT
945                 blend_DIFFERENCE_frag,  // TRANSFER_DIFFERENCE
946         };
947
948         BC_WindowBase *window =
949                 command->canvas->lock_canvas("Playback3D::overlay_sync");
950         if( window ) {
951 // Make sure OpenGL is enabled first.
952                 window->enable_opengl();
953                 window->update_video_cursor();
954
955                 glColor4f(1, 1, 1, 1);
956                 glDisable(GL_BLEND);
957
958
959 //printf("Playback3D::overlay_sync 1 %d\n", command->input->get_opengl_state());
960                 switch( command->input->get_opengl_state() ) {
961 // Upload texture and composite to screen
962                 case VFrame::RAM:
963                         command->input->to_texture();
964                         break;
965 // Just composite texture to screen
966                 case VFrame::TEXTURE:
967                         break;
968 // read from PBuffer to texture, then composite texture to screen
969                 case VFrame::SCREEN:
970                         command->input->enable_opengl();
971                         command->input->screen_to_texture();
972                         break;
973                 default:
974                         printf("Playback3D::overlay_sync unknown state\n");
975                         break;
976                 }
977
978                 if(command->frame) {
979 // Render to PBuffer
980                         command->frame->enable_opengl();
981                         command->frame->set_opengl_state(VFrame::SCREEN);
982                         canvas_w = command->frame->get_w();
983                         canvas_h = command->frame->get_h();
984                 }
985                 else {
986 // Render to canvas
987                         window->enable_opengl();
988                         canvas_w = window->get_w();
989                         canvas_h = window->get_h();
990                 }
991
992
993                 const char *shader_stack[16];
994                 memset(shader_stack,0, sizeof(shader_stack));
995                 int total_shaders = 0, need_matrix = 0;
996
997                 VFrame::init_screen(canvas_w, canvas_h);
998
999 // Enable texture
1000                 command->input->bind_texture(0);
1001
1002 // Convert colormodel to RGB if not nested.
1003 // The color model setting in the output frame is ignored.
1004 //              if( command->is_nested <= 0 &&  // not nested
1005 //                  BC_CModels::is_yuv(command->input->get_color_model()) ) {
1006 //                      need_matrix = 1;
1007 //                      shader_stack[total_shaders++] = yuv_to_rgb_frag;
1008 //              }
1009
1010 // get the shaders
1011 #define add_shader(s) \
1012   if(!total_shaders) shader_stack[total_shaders++] = read_texture_frag; \
1013   shader_stack[total_shaders++] = s
1014
1015                 switch(command->mode) {
1016                 case TRANSFER_REPLACE:
1017 // This requires overlaying an alpha multiplied image on a black screen.
1018                         if( command->input->get_texture_components() != 4 ) break;
1019                         add_shader(overlay_shaders[command->mode]);
1020                         break;
1021                 default:
1022                         enable_overlay_texture(command);
1023                         add_shader(overlay_shaders[command->mode]);
1024                         break;
1025                 }
1026
1027 // if to flatten alpha
1028 //              if( command->is_nested < 0 ) {
1029 //                      switch(command->input->get_color_model()) {
1030 //// yuv has already been converted to rgb
1031 //                      case BC_YUVA8888:
1032 //                      case BC_RGBA_FLOAT:
1033 //                      case BC_RGBA8888:
1034 //                              add_shader(rgba_to_rgb_flatten);
1035 //                              break;
1036 //                      }
1037 //              }
1038
1039 // run the shaders
1040                 add_shader(0);
1041                 unsigned int shader = !shader_stack[0] ? 0 :
1042                         VFrame::make_shader(shader_stack);
1043                 if( shader > 0 ) {
1044                         glUseProgram(shader);
1045                         if( need_matrix ) BC_GL_YUV_TO_RGB(shader);
1046 // Set texture unit of the texture
1047                         glUniform1i(glGetUniformLocation(shader, "tex"), 0);
1048 // Set texture unit of the temp texture
1049                         glUniform1i(glGetUniformLocation(shader, "tex2"), 1);
1050 // Set alpha
1051                         int variable = glGetUniformLocation(shader, "alpha");
1052                         glUniform1f(variable, command->alpha);
1053 // Set dimensions of the temp texture
1054                         if(temp_texture)
1055                                 glUniform2f(glGetUniformLocation(shader, "tex2_dimensions"),
1056                                         (float)temp_texture->get_texture_w(),
1057                                         (float)temp_texture->get_texture_h());
1058                 }
1059                 else
1060                         glUseProgram(0);
1061
1062
1063 //printf("Playback3D::overlay_sync %f %f %f %f %f %f %f %f\n",
1064 // command->in_x1, command->in_y1, command->in_x2, command->in_y2,
1065 // command->out_x1, command->out_y1, command->out_x2, command->out_y2);
1066
1067                 command->input->draw_texture(
1068                         command->in_x1, command->in_y1, command->in_x2, command->in_y2,
1069                         command->out_x1, command->out_y1, command->out_x2, command->out_y2,
1070                         !command->is_nested);
1071                 glUseProgram(0);
1072
1073 // Delete temp texture
1074                 if(temp_texture) {
1075                         delete temp_texture;
1076                         temp_texture = 0;
1077                         glActiveTexture(GL_TEXTURE1);
1078                         glDisable(GL_TEXTURE_2D);
1079                 }
1080                 glActiveTexture(GL_TEXTURE0);
1081                 glDisable(GL_TEXTURE_2D);
1082         }
1083         command->canvas->unlock_canvas();
1084 #endif
1085 }
1086
1087 void Playback3D::enable_overlay_texture(Playback3DCommand *command)
1088 {
1089 #ifdef HAVE_GL
1090         glDisable(GL_BLEND);
1091
1092         glActiveTexture(GL_TEXTURE1);
1093         BC_Texture::new_texture(&temp_texture, canvas_w, canvas_h,
1094                 command->input->get_color_model());
1095         temp_texture->bind(1);
1096
1097 // Read canvas into texture
1098         glReadBuffer(GL_BACK);
1099         glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, canvas_w, canvas_h);
1100 #endif
1101 }
1102
1103
1104 void Playback3D::do_mask(Canvas *canvas,
1105         VFrame *output,
1106         int64_t start_position_project,
1107         MaskAutos *keyframe_set,
1108         MaskAuto *keyframe,
1109         MaskAuto *default_auto)
1110 {
1111         Playback3DCommand command;
1112         command.command = Playback3DCommand::DO_MASK;
1113         command.canvas = canvas;
1114         command.frame = output;
1115         command.start_position_project = start_position_project;
1116         command.keyframe_set = keyframe_set;
1117         command.keyframe = keyframe;
1118         command.default_auto = default_auto;
1119
1120         send_command(&command);
1121 }
1122
1123
1124 void Playback3D::draw_spots(MaskSpots &spots, int ix1,int iy1, int ix2,int iy2)
1125 {
1126         int x1 = iy1 < iy2 ? ix1 : ix2;
1127         int y1 = iy1 < iy2 ? iy1 : iy2;
1128         int x2 = iy1 < iy2 ? ix2 : ix1;
1129         int y2 = iy1 < iy2 ? iy2 : iy1;
1130
1131         int x = x1, y = y1;
1132         int dx = x2-x1, dy = y2-y1;
1133         int dx2 = 2*dx, dy2 = 2*dy;
1134         if( dx < 0 ) dx = -dx;
1135         int m = dx > dy ? dx : dy, n = m;
1136         if( dy >= dx ) {
1137                 if( dx2 >= 0 ) do {     /* +Y, +X */
1138                         spots.append(x, y++);
1139                         if( (m -= dx2) < 0 ) { m += dy2;  ++x; }
1140                 } while( --n >= 0 );
1141                 else do {              /* +Y, -X */
1142                         spots.append(x, y++);
1143                         if( (m += dx2) < 0 ) { m += dy2;  --x; }
1144                 } while( --n >= 0 );
1145         }
1146         else {
1147                 if( dx2 >= 0 ) do {     /* +X, +Y */
1148                         spots.append(x++, y);
1149                         if( (m -= dy2) < 0 ) { m += dx2;  ++y; }
1150                 } while( --n >= 0 );
1151                 else do {              /* -X, +Y */
1152                         spots.append(x--, y);
1153                         if( (m -= dy2) < 0 ) { m -= dx2;  ++y; }
1154                 } while( --n >= 0 );
1155         }
1156 }
1157
1158 #ifdef HAVE_GL
1159 class fb_texture : public BC_Texture
1160 {
1161 public:
1162         fb_texture(int w, int h, int colormodel);
1163         ~fb_texture();
1164         void bind(int texture_unit);
1165         void read_screen(int x, int y, int w, int h);
1166         void set_output_texture();
1167         GLuint fb, rb;
1168 };
1169
1170 fb_texture::fb_texture(int w, int h, int colormodel)
1171  : BC_Texture(w, h, colormodel)
1172 {
1173         fb = 0;  rb = 0;
1174 //      glGenRenderbuffers(1, &rb);
1175 //      glBindRenderbuffer(GL_RENDERBUFFER, rb);
1176 //      glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, get_texture_w(), get_texture_w());
1177         glGenFramebuffers(1, &fb);
1178         glBindFramebuffer(GL_FRAMEBUFFER, fb);
1179 //      glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb);
1180 }
1181
1182 fb_texture::~fb_texture()
1183 {
1184         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1185         glDeleteFramebuffers(1, (GLuint *)&fb);
1186 //      glBindRenderbuffer(GL_RENDERBUFFER, 0);
1187 //      glGenRenderbuffers(1, &rb);
1188 }
1189
1190 void fb_texture::bind(int texture_unit)
1191 {
1192         glBindFramebuffer(GL_FRAMEBUFFER, fb);
1193 //      glBindRenderbuffer(GL_RENDERBUFFER, rb);
1194         BC_Texture::bind(texture_unit);
1195 }
1196
1197 void fb_texture::read_screen(int x, int y, int w, int h)
1198 {
1199         glBindFramebuffer(GL_FRAMEBUFFER, 0);
1200         glReadBuffer(GL_BACK);
1201         glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0,0, x,y, w,h);
1202 }
1203
1204 void fb_texture::set_output_texture()
1205 {
1206         glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, get_texture_id(), 0);
1207         GLenum dbo[1] = { GL_COLOR_ATTACHMENT0, }; // bind layout(location=0) out vec4 color;
1208         glDrawBuffers(1, dbo);
1209         int ret = glCheckFramebufferStatus(GL_FRAMEBUFFER);
1210         if( ret != GL_FRAMEBUFFER_COMPLETE ) {
1211                 printf("glDrawBuffer error 0x%04x\n", ret);
1212                 return;
1213         }
1214 }
1215
1216 static void combineData(GLdouble coords[3],
1217                 GLdouble *vertex_data[4], GLfloat weight[4],
1218                 GLdouble **outData, void *data)
1219 {
1220         ArrayList<double *> *invented = (ArrayList<double *> *)data;
1221         GLdouble *vertex = new double[6];
1222         invented->append(vertex);
1223         vertex[0] = coords[0];
1224         vertex[1] = coords[1];
1225         vertex[2] = coords[2];
1226         for( int i=3; i<6; ++i ) {
1227                 GLdouble v = 0;
1228                 for( int k=0; k<4; ++k ) {
1229                         if( !weight[k] || !vertex_data[k] ) continue;
1230                         v += weight[k] * vertex_data[k][i];
1231                 }
1232                 vertex[i] = v;
1233         }
1234         *outData = vertex;
1235 }
1236
1237 // dbug
1238 static void zglBegin(GLenum mode) { glBegin(mode); }
1239 static void zglEnd() { glEnd(); }
1240 static void zglVertex3dv(const GLdouble *v) { glVertex3dv(v); }
1241
1242 #endif
1243
1244 void Playback3D::do_mask_sync(Playback3DCommand *command)
1245 {
1246 #ifdef HAVE_GL
1247         BC_WindowBase *window =
1248                 command->canvas->lock_canvas("Playback3D::do_mask_sync");
1249         if( window ) {
1250                 window->enable_opengl();
1251
1252                 switch( command->frame->get_opengl_state() ) {
1253                 case VFrame::RAM:
1254 // upload frame to the texture
1255                         command->frame->to_texture();
1256                         break;
1257
1258                 case VFrame::SCREEN:
1259 // Read back from PBuffer
1260 // Bind context to pbuffer
1261                         command->frame->enable_opengl();
1262                         command->frame->screen_to_texture();
1263                         break;
1264                 }
1265
1266 // Initialize coordinate system
1267                 command->frame->enable_opengl();
1268                 command->frame->init_screen();
1269                 int color_model = command->frame->get_color_model();
1270                 int w = command->frame->get_w();
1271                 int h = command->frame->get_h();
1272                 MaskEdges edges;
1273                 float faders[SUBMASKS], feathers[SUBMASKS], bg = 1;
1274                 MaskPointSet point_set[SUBMASKS];
1275 // Draw every submask as a new polygon
1276                 int total_submasks = command->keyframe_set->total_submasks(
1277                         command->start_position_project, PLAY_FORWARD);
1278
1279                 for(int k = 0; k < total_submasks; k++) {
1280                         MaskPointSet &points = point_set[k];
1281                         command->keyframe_set->get_points(&points,
1282                                 k, command->start_position_project, PLAY_FORWARD);
1283                         float fader = command->keyframe_set->get_fader(
1284                                 command->start_position_project, k, PLAY_FORWARD);
1285                         float v = fader/100.;
1286                         faders[k] = v;
1287                         if( v < 0 && (v+=1) < bg ) bg = v;
1288                         float feather = command->keyframe_set->get_feather(
1289                                 command->start_position_project, k, PLAY_FORWARD);
1290                         feathers[k] = feather;
1291                 }
1292 // clear screen
1293                 glDisable(GL_TEXTURE_2D);
1294                 glClearColor(bg, bg, bg, bg);
1295                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1296
1297                 for(int k = 0; k < total_submasks; k++) {
1298                         MaskPointSet &points = point_set[k];
1299                         MaskEdge &edge = *edges.append(new MaskEdge());
1300                         int first_point = 0;
1301 // Need to tabulate every vertex in persistent memory because
1302 // gluTessVertex doesn't copy them.
1303                         for(int i = 0; i < points.total; i++) {
1304                                 MaskPoint *point1 = points.values[i];
1305                                 MaskPoint *point2 = (i >= points.total - 1) ?
1306                                         points.values[0] : points.values[i + 1];
1307
1308                                 float x, y;
1309                                 int segments = 0;
1310                                 if( point1->control_x2 == 0 && point1->control_y2 == 0 &&
1311                                     point2->control_x1 == 0 && point2->control_y1 == 0 )
1312                                         segments = 1;
1313
1314                                 float x0 = point1->x, y0 = point1->y;
1315                                 float x1 = point1->x + point1->control_x2;
1316                                 float y1 = point1->y + point1->control_y2;
1317                                 float x2 = point2->x + point2->control_x1;
1318                                 float y2 = point2->y + point2->control_y1;
1319                                 float x3 = point2->x, y3 = point2->y;
1320
1321                                 // forward differencing bezier curves implementation taken from GPL code at
1322                                 // http://cvs.sourceforge.net/viewcvs.py/guliverkli/guliverkli/src/subtitles/Rasterizer.cpp?rev=1.3
1323
1324                                 float cx3, cx2, cx1, cx0, cy3, cy2, cy1, cy0;
1325
1326                                 // [-1 +3 -3 +1]
1327                                 // [+3 -6 +3  0]
1328                                 // [-3 +3  0  0]
1329                                 // [+1  0  0  0]
1330
1331                                 cx3 = -  x0 + 3*x1 - 3*x2 + x3;
1332                                 cx2 =  3*x0 - 6*x1 + 3*x2;
1333                                 cx1 = -3*x0 + 3*x1;
1334                                 cx0 =    x0;
1335
1336                                 cy3 = -  y0 + 3*y1 - 3*y2 + y3;
1337                                 cy2 =  3*y0 - 6*y1 + 3*y2;
1338                                 cy1 = -3*y0 + 3*y1;
1339                                 cy0 =    y0;
1340
1341                                 // This equation is from Graphics Gems I.
1342                                 //
1343                                 // The idea is that since we're approximating a cubic curve with lines,
1344                                 // any error we incur is due to the curvature of the line, which we can
1345                                 // estimate by calculating the maximum acceleration of the curve.  For
1346                                 // a cubic, the acceleration (second derivative) is a line, meaning that
1347                                 // the absolute maximum acceleration must occur at either the beginning
1348                                 // (|c2|) or the end (|c2+c3|).  Our bounds here are a little more
1349                                 // conservative than that, but that's okay.
1350                                 if (segments == 0) {
1351                                         float maxaccel1 = fabs(2*cy2) + fabs(6*cy3);
1352                                         float maxaccel2 = fabs(2*cx2) + fabs(6*cx3);
1353
1354                                         float maxaccel = maxaccel1 > maxaccel2 ? maxaccel1 : maxaccel2;
1355                                         float h = 1.0;
1356
1357                                         if(maxaccel > 8.0) h = sqrt((8.0) / maxaccel);
1358                                         segments = int(1/h);
1359                                 }
1360
1361                                 for(int j = 0; j <= segments; j++) {
1362                                         float t = (float)j / segments;
1363                                         x = cx0 + t*(cx1 + t*(cx2 + t*cx3));
1364                                         y = cy0 + t*(cy1 + t*(cy2 + t*cy3));
1365
1366                                         if(j > 0 || first_point) {
1367                                                 edge.append(x, y - h);
1368                                                 first_point = 0;
1369                                         }
1370                                 }
1371                         }
1372                         if( edge.size() > 0 ) {
1373 // draw polygon
1374                                 float fader = faders[k];
1375                                 float v = fader < 0 ? 1 : 1-fader;
1376                                 glColor4f(v, v, v, v);
1377                                 int display_list = glGenLists(1);
1378                                 glNewList(display_list, GL_COMPILE);
1379 #if 0
1380                                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1381                                 glBegin(GL_POLYGON);
1382                                 MaskCoord *c = &edge[0];
1383                                 for( int i=edge.size(); --i>=0; ++c )
1384                                         glVertex2f(c->x, c->y);
1385                                 glEnd();
1386 #else
1387                                 GLUtesselator *tess = gluNewTess();
1388                                 gluTessCallback(tess, GLU_TESS_VERTEX,(GLvoid (*)()) &zglVertex3dv);
1389                                 gluTessCallback(tess, GLU_TESS_BEGIN,(GLvoid (*)()) &zglBegin);
1390                                 gluTessCallback(tess, GLU_TESS_END,(GLvoid (*)()) &zglEnd);
1391                                 gluTessCallback(tess, GLU_TESS_COMBINE_DATA,(GLvoid (*)()) &combineData);
1392                                 ArrayList<double *> invented;
1393                                 invented.set_array_delete();
1394
1395                                 gluTessBeginPolygon(tess, &invented);
1396                                 gluTessBeginContour(tess);
1397                                 MaskCoord *c = &edge[0];
1398                                 for( int i=edge.size(); --i>=0; ++c )
1399                                         gluTessVertex(tess, (GLdouble *)c, c);
1400                                 gluTessEndContour(tess);
1401                                 gluTessEndPolygon(tess);
1402                                 gluDeleteTess(tess);
1403                                 invented.remove_all_objects();
1404 #endif
1405                                 glEndList();
1406                                 glCallList(display_list);
1407                                 glDeleteLists(1, display_list);
1408                         }
1409                 }
1410
1411 // in/out textures
1412                 fb_texture *in = new fb_texture(w, h, color_model);
1413                 in->bind(0);
1414                 in->read_screen(0,0, w,h);
1415                 fb_texture *out = new fb_texture(w, h, color_model);
1416
1417                 unsigned int frag_shader =
1418                         VFrame::make_shader(0, in_vertex_frag, feather_frag, 0);
1419                 if( frag_shader > 0 ) {
1420                         GLuint points[1];
1421                         glGenBuffers(1, points);
1422                         for(int k = 0; k < total_submasks; k++) {
1423                                 MaskEdge &edge = *edges[k];
1424                                 if( !edge.size() ) continue;
1425                                 if( !faders[k] ) continue;
1426                                 if( !feathers[k] ) continue;
1427                                 MaskSpots spots;
1428                                 for( int i=0; i<edge.size(); ++i ) {
1429                                         MaskCoord &a = edge[i];
1430                                         MaskCoord &b = i<edge.size()-1 ? edge[i+1] : edge[0];
1431                                         draw_spots(spots, a.x,a.y+h, b.x,b.y+h);
1432                                 }
1433                                 int sz = spots.size() * sizeof(MaskSpot);
1434                                 glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, points[0], 0, sz);
1435                                 glBufferData(GL_SHADER_STORAGE_BUFFER, sz, &spots[0], GL_DYNAMIC_COPY);
1436                                 glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
1437                                 glUseProgram(frag_shader);
1438                                 float r = feathers[k], v = faders[k];
1439                                 glUniform1f(glGetUniformLocation(frag_shader, "r"), r);
1440                                 glUniform1f(glGetUniformLocation(frag_shader, "v"), v);
1441                                 in->bind(0);
1442                                 glUniform1i(glGetUniformLocation(frag_shader, "tex"), 0);
1443                                 out->set_output_texture();
1444                                 glViewport(0,0, w,h);
1445                                 out->draw_texture(0,0, w,h, 0,0, w,h);
1446                                 glUseProgram(0);
1447                                 fb_texture *t = in;  in = out;  out = t;
1448                         }
1449                         glDeleteBuffers(1, points);
1450                 }
1451
1452                 glDrawBuffers(0, 0);
1453                 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1454
1455                 const char *alpha_shader = BC_CModels::has_alpha(color_model) ?
1456                                 multiply_mask4_frag :
1457                         !BC_CModels::is_yuv(color_model) ?
1458                                 multiply_mask3_frag :
1459                                 multiply_yuvmask3_frag;
1460                 unsigned int shader = VFrame::make_shader(0, alpha_shader, 0);
1461                 glUseProgram(shader);
1462                 if( shader > 0 ) {
1463                         command->frame->bind_texture(0);
1464                         in->BC_Texture::bind(1);
1465                         glUniform1i(glGetUniformLocation(shader, "tex"), 0);
1466                         glUniform1i(glGetUniformLocation(shader, "tex1"), 1);
1467                 }
1468                 command->frame->draw_texture();
1469                 command->frame->set_opengl_state(VFrame::SCREEN);
1470                 glUseProgram(0);
1471                 delete in;
1472                 delete out;
1473 // Default drawable
1474                 glDisable(GL_TEXTURE_2D);
1475                 glColor4f(1, 1, 1, 1);
1476                 glActiveTexture(GL_TEXTURE0);
1477                 window->enable_opengl();
1478         }
1479         command->canvas->unlock_canvas();
1480 #endif
1481 }
1482
1483
1484 void Playback3D::convert_cmodel(Canvas *canvas,
1485         VFrame *output,
1486         int dst_cmodel)
1487 {
1488 // Do nothing if colormodels are equivalent in OpenGL & the image is in hardware.
1489         int src_cmodel = output->get_color_model();
1490         if(
1491                 (output->get_opengl_state() == VFrame::TEXTURE ||
1492                 output->get_opengl_state() == VFrame::SCREEN) &&
1493 // OpenGL has no floating point.
1494                 ( (src_cmodel == BC_RGB888 && dst_cmodel == BC_RGB_FLOAT) ||
1495                   (src_cmodel == BC_RGBA8888 && dst_cmodel == BC_RGBA_FLOAT) ||
1496                   (src_cmodel == BC_RGB_FLOAT && dst_cmodel == BC_RGB888) ||
1497                   (src_cmodel == BC_RGBA_FLOAT && dst_cmodel == BC_RGBA8888) ||
1498 // OpenGL sets alpha to 1 on import
1499                   (src_cmodel == BC_RGB888 && dst_cmodel == BC_RGBA8888) ||
1500                   (src_cmodel == BC_YUV888 && dst_cmodel == BC_YUVA8888) ||
1501                   (src_cmodel == BC_RGB_FLOAT && dst_cmodel == BC_RGBA_FLOAT) )
1502                 ) return;
1503
1504
1505
1506         Playback3DCommand command;
1507         command.command = Playback3DCommand::CONVERT_CMODEL;
1508         command.canvas = canvas;
1509         command.frame = output;
1510         command.dst_cmodel = dst_cmodel;
1511         send_command(&command);
1512 }
1513
1514 void Playback3D::convert_cmodel_sync(Playback3DCommand *command)
1515 {
1516 #ifdef HAVE_GL
1517         BC_WindowBase *window =
1518                 command->canvas->lock_canvas("Playback3D::convert_cmodel_sync");
1519         if( window ) {
1520                 window->enable_opengl();
1521
1522 // Import into hardware
1523                 command->frame->enable_opengl();
1524                 command->frame->init_screen();
1525                 command->frame->to_texture();
1526
1527 // Colormodel permutation
1528                 int src_cmodel = command->frame->get_color_model();
1529                 int dst_cmodel = command->dst_cmodel;
1530                 typedef struct {
1531                         int src, dst, typ;
1532                         const char *shader;
1533                 } cmodel_shader_table_t;
1534                 enum { rgb_to_rgb, rgb_to_yuv, yuv_to_rgb, yuv_to_yuv, };
1535                 int type = -1;
1536                 static cmodel_shader_table_t cmodel_shader_table[]  = {
1537                         { BC_RGB888,    BC_YUV888,      rgb_to_yuv, rgb_to_yuv_frag  },
1538                         { BC_RGB888,    BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1539                         { BC_RGBA8888,  BC_RGB888,      rgb_to_rgb, rgba_to_rgb_frag },
1540                         { BC_RGBA8888,  BC_RGB_FLOAT,   rgb_to_rgb, rgba_to_rgb_frag },
1541                         { BC_RGBA8888,  BC_YUV888,      rgb_to_yuv, rgba_to_yuv_frag },
1542                         { BC_RGBA8888,  BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1543                         { BC_RGB_FLOAT, BC_YUV888,      rgb_to_yuv, rgb_to_yuv_frag  },
1544                         { BC_RGB_FLOAT, BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1545                         { BC_RGBA_FLOAT,BC_RGB888,      rgb_to_rgb, rgba_to_rgb_frag },
1546                         { BC_RGBA_FLOAT,BC_RGB_FLOAT,   rgb_to_rgb, rgba_to_rgb_frag },
1547                         { BC_RGBA_FLOAT,BC_YUV888,      rgb_to_yuv, rgba_to_yuv_frag },
1548                         { BC_RGBA_FLOAT,BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1549                         { BC_YUV888,    BC_RGB888,      yuv_to_rgb, yuv_to_rgb_frag  },
1550                         { BC_YUV888,    BC_RGBA8888,    yuv_to_rgb, yuv_to_rgb_frag  },
1551                         { BC_YUV888,    BC_RGB_FLOAT,   yuv_to_rgb, yuv_to_rgb_frag  },
1552                         { BC_YUV888,    BC_RGBA_FLOAT,  yuv_to_rgb, yuv_to_rgb_frag  },
1553                         { BC_YUVA8888,  BC_RGB888,      yuv_to_rgb, yuva_to_rgb_frag },
1554                         { BC_YUVA8888,  BC_RGBA8888,    yuv_to_rgb, yuv_to_rgb_frag  },
1555                         { BC_YUVA8888,  BC_RGB_FLOAT,   yuv_to_rgb, yuva_to_rgb_frag },
1556                         { BC_YUVA8888,  BC_RGBA_FLOAT,  yuv_to_rgb, yuv_to_rgb_frag  },
1557                         { BC_YUVA8888,  BC_YUV888,      yuv_to_yuv, yuva_to_yuv_frag },
1558                 };
1559
1560                 const char *shader = 0;
1561                 int table_size = sizeof(cmodel_shader_table) / sizeof(cmodel_shader_table_t);
1562                 for( int i=0; i<table_size; ++i ) {
1563                         if( cmodel_shader_table[i].src == src_cmodel &&
1564                             cmodel_shader_table[i].dst == dst_cmodel ) {
1565                                 shader = cmodel_shader_table[i].shader;
1566                                 type = cmodel_shader_table[i].typ;
1567                                 break;
1568                         }
1569                 }
1570
1571 // printf("Playback3D::convert_cmodel_sync %d %d %d shader=\n%s",
1572 // __LINE__,
1573 // command->frame->get_color_model(),
1574 // command->dst_cmodel,
1575 // shader);
1576
1577                 const char *shader_stack[9];
1578                 memset(shader_stack,0, sizeof(shader_stack));
1579                 int current_shader = 0;
1580
1581                 if( shader ) {
1582 //printf("Playback3D::convert_cmodel_sync %d\n", __LINE__);
1583                         shader_stack[current_shader++] = shader;
1584                         shader_stack[current_shader] = 0;
1585                         unsigned int shader_id = VFrame::make_shader(shader_stack);
1586
1587                         command->frame->bind_texture(0);
1588                         glUseProgram(shader_id);
1589
1590                         glUniform1i(glGetUniformLocation(shader_id, "tex"), 0);
1591                         switch( type ) {
1592                         case rgb_to_yuv:
1593                                 BC_GL_RGB_TO_YUV(shader_id);
1594                                 break;
1595                         case yuv_to_rgb:
1596                                 BC_GL_YUV_TO_RGB(shader_id);
1597                                 break;
1598                         }
1599
1600                         command->frame->draw_texture();
1601                         if(shader) glUseProgram(0);
1602                         command->frame->set_opengl_state(VFrame::SCREEN);
1603                 }
1604         }
1605
1606         command->canvas->unlock_canvas();
1607 #endif // HAVE_GL
1608 }
1609
1610 void Playback3D::do_fade(Canvas *canvas, VFrame *frame, float fade)
1611 {
1612         Playback3DCommand command;
1613         command.command = Playback3DCommand::DO_FADE;
1614         command.canvas = canvas;
1615         command.frame = frame;
1616         command.alpha = fade;
1617         send_command(&command);
1618 }
1619
1620 void Playback3D::do_fade_sync(Playback3DCommand *command)
1621 {
1622 #ifdef HAVE_GL
1623         BC_WindowBase *window =
1624                 command->canvas->lock_canvas("Playback3D::do_fade_sync");
1625         if( window ) {
1626                 window->enable_opengl();
1627                 switch( command->frame->get_opengl_state() ) {
1628                 case VFrame::RAM:
1629                         command->frame->to_texture();
1630                         break;
1631
1632                 case VFrame::SCREEN:
1633 // Read back from PBuffer
1634 // Bind context to pbuffer
1635                         command->frame->enable_opengl();
1636                         command->frame->screen_to_texture();
1637                         break;
1638                 }
1639
1640                 command->frame->enable_opengl();
1641                 command->frame->init_screen();
1642                 command->frame->bind_texture(0);
1643
1644 //              glClearColor(0.0, 0.0, 0.0, 0.0);
1645 //              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1646                 glDisable(GL_BLEND);
1647                 unsigned int frag_shader = 0;
1648                 switch(command->frame->get_color_model())
1649                 {
1650 // For the alpha colormodels, the native function seems to multiply the
1651 // components by the alpha instead of just the alpha.
1652                         case BC_RGBA8888:
1653                         case BC_RGBA_FLOAT:
1654                         case BC_YUVA8888:
1655                                 frag_shader = VFrame::make_shader(0, fade_rgba_frag, 0);
1656                                 break;
1657
1658                         case BC_RGB888:
1659                                 glEnable(GL_BLEND);
1660                                 glBlendFunc(GL_SRC_ALPHA, GL_ZERO);
1661                                 glColor4f(command->alpha, command->alpha, command->alpha, 1);
1662                                 break;
1663
1664
1665                         case BC_YUV888:
1666                                 frag_shader = VFrame::make_shader(0, fade_yuv_frag, 0);
1667                                 break;
1668                 }
1669
1670
1671                 if( frag_shader ) {
1672                         glUseProgram(frag_shader);
1673                         int variable;
1674                         if((variable = glGetUniformLocation(frag_shader, "tex")) >= 0)
1675                                 glUniform1i(variable, 0);
1676                         if((variable = glGetUniformLocation(frag_shader, "alpha")) >= 0)
1677                                 glUniform1f(variable, command->alpha);
1678                 }
1679
1680                 command->frame->draw_texture();
1681                 command->frame->set_opengl_state(VFrame::SCREEN);
1682
1683                 if(frag_shader)
1684                 {
1685                         glUseProgram(0);
1686                 }
1687
1688                 glColor4f(1, 1, 1, 1);
1689                 glDisable(GL_BLEND);
1690         }
1691         command->canvas->unlock_canvas();
1692 #endif
1693 }
1694
1695
1696 int Playback3D::run_plugin(Canvas *canvas, PluginClient *client)
1697 {
1698         Playback3DCommand command;
1699         command.command = Playback3DCommand::PLUGIN;
1700         command.canvas = canvas;
1701         command.plugin_client = client;
1702         return send_command(&command);
1703 }
1704
1705 void Playback3D::run_plugin_sync(Playback3DCommand *command)
1706 {
1707         BC_WindowBase *window =
1708                 command->canvas->lock_canvas("Playback3D::run_plugin_sync");
1709         if( window ) {
1710                 window->enable_opengl();
1711                 command->result = ((PluginVClient*)command->plugin_client)->handle_opengl();
1712         }
1713         command->canvas->unlock_canvas();
1714 }
1715
1716