eed42cd9f76e352825b8fb68870f745bbbfccb33
[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 *multiply_mask4_frag =
263         "uniform sampler2D tex;\n"
264         "uniform sampler2D tex1;\n"
265         "uniform float scale;\n"
266         "void main()\n"
267         "{\n"
268         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
269         "       gl_FragColor.a *= texture2D(tex1, gl_TexCoord[0].st / vec2(scale, scale)).r;\n"
270         "}\n";
271
272 static const char *multiply_mask3_frag =
273         "uniform sampler2D tex;\n"
274         "uniform sampler2D tex1;\n"
275         "uniform float scale;\n"
276         "uniform bool is_yuv;\n"
277         "void main()\n"
278         "{\n"
279         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
280         "       float a = texture2D(tex1, gl_TexCoord[0].st / vec2(scale, scale)).r;\n"
281         "       gl_FragColor.rgb *= vec3(a, a, a);\n"
282         "}\n";
283
284 static const char *multiply_yuvmask3_frag =
285         "uniform sampler2D tex;\n"
286         "uniform sampler2D tex1;\n"
287         "uniform float scale;\n"
288         "void main()\n"
289         "{\n"
290         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
291         "       float a = texture2D(tex1, gl_TexCoord[0].st / vec2(scale, scale)).r;\n"
292         "       gl_FragColor.gb -= vec2(0.5, 0.5);\n"
293         "       gl_FragColor.rgb *= vec3(a, a, a);\n"
294         "       gl_FragColor.gb += vec2(0.5, 0.5);\n"
295         "}\n";
296
297 static const char *fade_rgba_frag =
298         "uniform sampler2D tex;\n"
299         "uniform float alpha;\n"
300         "void main()\n"
301         "{\n"
302         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
303         "       gl_FragColor.a *= alpha;\n"
304         "}\n";
305
306 static const char *fade_yuv_frag =
307         "uniform sampler2D tex;\n"
308         "uniform float alpha;\n"
309         "void main()\n"
310         "{\n"
311         "       gl_FragColor = texture2D(tex, gl_TexCoord[0].st);\n"
312         "       gl_FragColor.r *= alpha;\n"
313         "       gl_FragColor.gb -= vec2(0.5, 0.5);\n"
314         "       gl_FragColor.g *= alpha;\n"
315         "       gl_FragColor.b *= alpha;\n"
316         "       gl_FragColor.gb += vec2(0.5, 0.5);\n"
317         "}\n";
318
319 #endif
320
321
322 Playback3DCommand::Playback3DCommand()
323  : BC_SynchronousCommand()
324 {
325         canvas = 0;
326         is_nested = 0;
327 }
328
329 void Playback3DCommand::copy_from(BC_SynchronousCommand *command)
330 {
331         Playback3DCommand *ptr = (Playback3DCommand*)command;
332         this->canvas = ptr->canvas;
333         this->is_cleared = ptr->is_cleared;
334
335         this->in_x1 = ptr->in_x1;
336         this->in_y1 = ptr->in_y1;
337         this->in_x2 = ptr->in_x2;
338         this->in_y2 = ptr->in_y2;
339         this->out_x1 = ptr->out_x1;
340         this->out_y1 = ptr->out_y1;
341         this->out_x2 = ptr->out_x2;
342         this->out_y2 = ptr->out_y2;
343         this->alpha = ptr->alpha;
344         this->mode = ptr->mode;
345         this->interpolation_type = ptr->interpolation_type;
346
347         this->input = ptr->input;
348         this->start_position_project = ptr->start_position_project;
349         this->keyframe_set = ptr->keyframe_set;
350         this->keyframe = ptr->keyframe;
351         this->default_auto = ptr->default_auto;
352         this->plugin_client = ptr->plugin_client;
353         this->want_texture = ptr->want_texture;
354         this->is_nested = ptr->is_nested;
355         this->dst_cmodel = ptr->dst_cmodel;
356
357         BC_SynchronousCommand::copy_from(command);
358 }
359
360
361 ///static void glDebugCallback(GLenum src, GLenum typ, GLuint id,
362 ///     GLenum svy, GLsizei len, const GLchar* msg, void* dat)
363 //static void glDebugCallback(unsigned int src, unsigned int typ, unsigned int id,
364 //      unsigned int svy, int len, const char* msg, const void* dat)
365 //{
366 //      printf("glDebug: %d:%d; %d/%d %s\n",src,typ,id,svy,msg);
367 //}
368
369
370 Playback3D::Playback3D(MWindow *mwindow)
371  : BC_Synchronous()
372 {
373         this->mwindow = mwindow;
374         temp_texture = 0;
375         //Enabling OpenGL debug output on nVidia drivers
376 //      glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
377 //      glEnable(GL_DEBUG_OUTPUT);
378 //      glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
379 //      glDebugMessageCallback(glDebugCallback, 0);
380 }
381
382 Playback3D::~Playback3D()
383 {
384 }
385
386
387
388
389 BC_SynchronousCommand* Playback3D::new_command()
390 {
391         return new Playback3DCommand;
392 }
393
394
395
396 void Playback3D::handle_command(BC_SynchronousCommand *command)
397 {
398 //printf("Playback3D::handle_command 1 %d\n", command->command);
399         switch(command->command)
400         {
401                 case Playback3DCommand::WRITE_BUFFER:
402                         write_buffer_sync((Playback3DCommand*)command);
403                         break;
404
405                 case Playback3DCommand::FINISH_OUTPUT:
406                         finish_output_sync((Playback3DCommand*)command);
407                         break;
408
409                 case Playback3DCommand::CLEAR_OUTPUT:
410                         clear_output_sync((Playback3DCommand*)command);
411                         break;
412
413                 case Playback3DCommand::CLEAR_INPUT:
414                         clear_input_sync((Playback3DCommand*)command);
415                         break;
416
417                 case Playback3DCommand::DO_CAMERA:
418                         do_camera_sync((Playback3DCommand*)command);
419                         break;
420
421                 case Playback3DCommand::OVERLAY:
422                         overlay_sync((Playback3DCommand*)command);
423                         break;
424
425                 case Playback3DCommand::DO_FADE:
426                         do_fade_sync((Playback3DCommand*)command);
427                         break;
428
429                 case Playback3DCommand::DO_MASK:
430                         do_mask_sync((Playback3DCommand*)command);
431                         break;
432
433                 case Playback3DCommand::PLUGIN:
434                         run_plugin_sync((Playback3DCommand*)command);
435                         break;
436
437                 case Playback3DCommand::COPY_FROM:
438                         copy_from_sync((Playback3DCommand*)command);
439                         break;
440
441                 case Playback3DCommand::CONVERT_CMODEL:
442                         convert_cmodel_sync((Playback3DCommand*)command);
443                         break;
444
445 //              case Playback3DCommand::DRAW_REFRESH:
446 //                      draw_refresh_sync((Playback3DCommand*)command);
447 //                      break;
448         }
449 //printf("Playback3D::handle_command 10\n");
450 }
451
452
453
454
455 void Playback3D::copy_from(Canvas *canvas,
456         VFrame *dst,
457         VFrame *src,
458         int want_texture)
459 {
460         Playback3DCommand command;
461         command.command = Playback3DCommand::COPY_FROM;
462         command.canvas = canvas;
463         command.frame = dst;
464         command.input = src;
465         command.want_texture = want_texture;
466         send_command(&command);
467 }
468
469 void Playback3D::copy_from_sync(Playback3DCommand *command)
470 {
471 #ifdef HAVE_GL
472         BC_WindowBase *window = 
473                 command->canvas->lock_canvas("Playback3D::copy_from_sync");
474         if( window ) {
475                 window->enable_opengl();
476                 int w = command->input->get_w();
477                 int h = command->input->get_h();
478
479                 if(command->input->get_opengl_state() == VFrame::SCREEN &&
480                         w == command->frame->get_w() && h == command->frame->get_h())
481                 {
482 // printf("Playback3D::copy_from_sync 1 %d %d %d %d %d\n",
483 // command->input->get_w(),
484 // command->input->get_h(),
485 // command->frame->get_w(),
486 // command->frame->get_h(),
487 // command->frame->get_color_model());
488 // With NVidia at least,
489                         if(w % 4)
490                         {
491                                 printf("Playback3D::copy_from_sync: w=%d not supported because it is not divisible by 4.\n", w);
492                         }
493                         else
494 // Copy to texture
495                         if(command->want_texture)
496                         {
497 //printf("Playback3D::copy_from_sync 1 dst=%p src=%p\n", command->frame, command->input);
498 // Screen_to_texture requires the source pbuffer enabled.
499                                 command->input->enable_opengl();
500                                 command->frame->screen_to_texture();
501                                 command->frame->set_opengl_state(VFrame::TEXTURE);
502                         }
503                         else
504 // Copy to RAM
505                         {
506                                 command->input->to_texture();
507                                 command->input->bind_texture(0);
508                                 command->frame->enable_opengl();
509                                 command->frame->init_screen();
510                                 unsigned int shader = BC_CModels::is_yuv(command->input->get_color_model()) ?
511                                         VFrame::make_shader(0, yuv_to_rgb_frag, 0) : 0;
512                                 if( shader > 0 ) {
513                                         glUseProgram(shader);
514                                         int variable = glGetUniformLocation(shader, "tex");
515                                         glUniform1i(variable, 0);
516                                         BC_GL_YUV_TO_RGB(shader);
517                                 }
518                                 else
519                                         glUseProgram(0);
520                                 command->input->draw_texture(1);
521                                 command->frame->screen_to_ram();
522                                 glUseProgram(0);
523                         }
524                 }
525                 else
526                 {
527                         printf("Playback3D::copy_from_sync: invalid formats opengl_state=%d %dx%d -> %dx%d\n",
528                                 command->input->get_opengl_state(), w, h,
529                                 command->frame->get_w(), command->frame->get_h());
530                 }
531         }
532         command->canvas->unlock_canvas();
533 #endif
534 }
535
536
537
538
539 // void Playback3D::draw_refresh(Canvas *canvas,
540 //      VFrame *frame,
541 //      float in_x1,
542 //      float in_y1,
543 //      float in_x2,
544 //      float in_y2,
545 //      float out_x1,
546 //      float out_y1,
547 //      float out_x2,
548 //      float out_y2)
549 // {
550 //      Playback3DCommand command;
551 //      command.command = Playback3DCommand::DRAW_REFRESH;
552 //      command.canvas = canvas;
553 //      command.frame = frame;
554 //      command.in_x1 = in_x1;
555 //      command.in_y1 = in_y1;
556 //      command.in_x2 = in_x2;
557 //      command.in_y2 = in_y2;
558 //      command.out_x1 = out_x1;
559 //      command.out_y1 = out_y1;
560 //      command.out_x2 = out_x2;
561 //      command.out_y2 = out_y2;
562 //      send_command(&command);
563 // }
564 //
565 // void Playback3D::draw_refresh_sync(Playback3DCommand *command)
566 // {
567 // #ifdef HAVE_GL
568 //      BC_WindowBase *window =
569 //              command->canvas->lock_canvas("Playback3D::draw_refresh_sync");
570 //      if( window ) {
571 //              window->enable_opengl();
572 //
573 // // Read output pbuffer back to RAM in project colormodel
574 // // RGB 8bit is fastest for OpenGL to read back.
575 //              command->frame->reallocate(0,
576 //                      0,
577 //                      0,
578 //                      0,
579 //                      command->frame->get_w(),
580 //                      command->frame->get_h(),
581 //                      BC_RGB888,
582 //                      -1);
583 //              command->frame->screen_to_ram();
584 //
585 //              window->clear_box(0,
586 //                                              0,
587 //                                              window->get_w(),
588 //                                              window->get_h());
589 //              window->draw_vframe(command->frame,
590 //                                                      (int)command->out_x1,
591 //                                                      (int)command->out_y1,
592 //                                                      (int)(command->out_x2 - command->out_x1),
593 //                                                      (int)(command->out_y2 - command->out_y1),
594 //                                                      (int)command->in_x1,
595 //                                                      (int)command->in_y1,
596 //                                                      (int)(command->in_x2 - command->in_x1),
597 //                                                      (int)(command->in_y2 - command->in_y1),
598 //                                                      0);
599 //
600 //      }
601 //      command->canvas->unlock_canvas();
602 // #endif
603 // }
604
605
606
607
608
609 void Playback3D::write_buffer(Canvas *canvas,
610         VFrame *frame,
611         float in_x1,
612         float in_y1,
613         float in_x2,
614         float in_y2,
615         float out_x1,
616         float out_y1,
617         float out_x2,
618         float out_y2,
619         int is_cleared)
620 {
621         Playback3DCommand command;
622         command.command = Playback3DCommand::WRITE_BUFFER;
623         command.canvas = canvas;
624         command.frame = frame;
625         command.in_x1 = in_x1;
626         command.in_y1 = in_y1;
627         command.in_x2 = in_x2;
628         command.in_y2 = in_y2;
629         command.out_x1 = out_x1;
630         command.out_y1 = out_y1;
631         command.out_x2 = out_x2;
632         command.out_y2 = out_y2;
633         command.is_cleared = is_cleared;
634         send_command(&command);
635 }
636
637
638 void Playback3D::write_buffer_sync(Playback3DCommand *command)
639 {
640 #ifdef HAVE_GL
641         BC_WindowBase *window =
642                 command->canvas->lock_canvas("Playback3D::write_buffer_sync");
643         if( window ) {
644 // Update hidden cursor
645                 window->update_video_cursor();
646 // Make sure OpenGL is enabled first.
647                 window->enable_opengl();
648
649 //printf("Playback3D::write_buffer_sync 1 %d\n", window->get_id());
650                 int flip_y = 0, frame_state = command->frame->get_opengl_state();
651                 switch( frame_state ) {
652 // Upload texture and composite to screen
653                         case VFrame::RAM:
654                                 flip_y = 1;
655                         case VFrame::SCREEN:
656                                 command->frame->to_texture();
657                                 window->enable_opengl();
658 // Composite texture to screen and swap buffer
659                         case VFrame::TEXTURE:
660                                 if( !flip_y ) {
661                                         int fh1 = command->frame->get_h()-1;
662                                         float in_y1 = fh1 - command->in_y1;
663                                         float in_y2 = fh1 - command->in_y2;
664                                         command->in_y1 = in_y2;
665                                         command->in_y2 = in_y1;
666                                 }
667                                 draw_output(command, flip_y);
668                                 break;
669                         default:
670                                 printf("Playback3D::write_buffer_sync unknown state\n");
671                                 break;
672                 }
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,
738 // command->in_y1,
739 // command->in_x2,
740 // command->in_y2,
741 // command->out_x1,
742 // command->out_y1,
743 // command->out_x2,
744 // command->out_y2);
745
746                 glUseProgram(0);
747
748                 command->canvas->get_canvas()->flip_opengl();
749
750         }
751 #endif
752 }
753
754
755 void Playback3D::init_frame(Playback3DCommand *command, int is_yuv)
756 {
757 #ifdef HAVE_GL
758         float gbuv = is_yuv ? 0.5 : 0.0;
759         glClearColor(0.0, gbuv, gbuv, 0.0);
760         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
761 #endif
762 }
763
764
765 void Playback3D::finish_output(Canvas *canvas)
766 {
767         Playback3DCommand command;
768         command.canvas = canvas;
769         command.command = Playback3DCommand::FINISH_OUTPUT;
770         send_command(&command);
771 }
772
773 void Playback3D::finish_output_sync(Playback3DCommand *command)
774 {
775 #ifdef HAVE_GL
776         BC_WindowBase *window =
777                 command->canvas->lock_canvas("Playback3D::finish_output_sync");
778         if( window ) {
779                 command->canvas->get_canvas()->enable_opengl();
780                 glFinish();
781         }
782         command->canvas->unlock_canvas();
783 #endif
784 }
785
786
787 void Playback3D::clear_output(Canvas *canvas, VFrame *output)
788 {
789         Playback3DCommand command;
790         command.command = Playback3DCommand::CLEAR_OUTPUT;
791         command.canvas = canvas;
792         command.frame = output;
793         send_command(&command);
794 }
795
796 void Playback3D::clear_output_sync(Playback3DCommand *command)
797 {
798 #ifdef HAVE_GL
799         BC_WindowBase *window =
800                 command->canvas->lock_canvas("Playback3D::clear_output_sync");
801         if( window ) {
802 // If we get here, the virtual console is being used.
803                 command->canvas->get_canvas()->enable_opengl();
804                 int is_yuv = 0;
805 // Using pbuffer for refresh frame.
806                 if( command->frame ) {
807                         command->frame->enable_opengl();
808                         int color_model = command->canvas->mwindow->edl->session->color_model;
809                         is_yuv = BC_CModels::is_yuv(color_model);
810                 }
811
812                 init_frame(command, is_yuv);
813         }
814         command->canvas->unlock_canvas();
815 #endif
816 }
817
818
819 void Playback3D::clear_input(Canvas *canvas, VFrame *frame)
820 {
821         Playback3DCommand command;
822         command.command = Playback3DCommand::CLEAR_INPUT;
823         command.canvas = canvas;
824         command.frame = frame;
825         send_command(&command);
826 }
827
828 void Playback3D::clear_input_sync(Playback3DCommand *command)
829 {
830 #ifdef HAVE_GL
831         BC_WindowBase *window =
832                 command->canvas->lock_canvas("Playback3D::clear_input_sync");
833         if( window ) {
834                 command->canvas->get_canvas()->enable_opengl();
835                 command->frame->enable_opengl();
836                 command->frame->clear_pbuffer();
837                 command->frame->set_opengl_state(VFrame::SCREEN);
838         }
839         command->canvas->unlock_canvas();
840 #endif
841 }
842
843 void Playback3D::do_camera(Canvas *canvas,
844         VFrame *output,
845         VFrame *input,
846         float in_x1,
847         float in_y1,
848         float in_x2,
849         float in_y2,
850         float out_x1,
851         float out_y1,
852         float out_x2,
853         float out_y2)
854 {
855         Playback3DCommand command;
856         command.command = Playback3DCommand::DO_CAMERA;
857         command.canvas = canvas;
858         command.input = input;
859         command.frame = output;
860         command.in_x1 = in_x1;
861         command.in_y1 = in_y1;
862         command.in_x2 = in_x2;
863         command.in_y2 = in_y2;
864         command.out_x1 = out_x1;
865         command.out_y1 = out_y1;
866         command.out_x2 = out_x2;
867         command.out_y2 = out_y2;
868         send_command(&command);
869 }
870
871 void Playback3D::do_camera_sync(Playback3DCommand *command)
872 {
873 #ifdef HAVE_GL
874         BC_WindowBase *window =
875                 command->canvas->lock_canvas("Playback3D::do_camera_sync");
876         if( window ) {
877                 command->canvas->get_canvas()->enable_opengl();
878
879                 command->input->to_texture();
880                 command->frame->enable_opengl();
881                 command->frame->init_screen();
882                 command->frame->clear_pbuffer();
883
884                 command->input->bind_texture(0);
885 // Must call draw_texture in input frame to get the texture coordinates right.
886
887 // printf("Playback3D::do_camera_sync 1 %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f\n",
888 // command->in_x1,
889 // command->in_y2,
890 // command->in_x2,
891 // command->in_y1,
892 // command->out_x1,
893 // (float)command->input->get_h() - command->out_y1,
894 // command->out_x2,
895 // (float)command->input->get_h() - command->out_y2);
896                 command->input->draw_texture(
897                         command->in_x1, command->in_y2,
898                         command->in_x2, command->in_y1,
899                         command->out_x1,
900                         (float)command->frame->get_h() - command->out_y1,
901                         command->out_x2,
902                         (float)command->frame->get_h() - command->out_y2);
903
904
905                 command->frame->set_opengl_state(VFrame::SCREEN);
906                 command->frame->screen_to_ram();
907         }
908         command->canvas->unlock_canvas();
909 #endif
910 }
911
912 void Playback3D::overlay(Canvas *canvas, VFrame *input,
913         float in_x1, float in_y1, float in_x2, float in_y2,
914         float out_x1, float out_y1, float out_x2, float out_y2,
915         float alpha, int mode, int interpolation_type,
916         VFrame *output, int is_nested)
917 {
918         Playback3DCommand command;
919         command.command = Playback3DCommand::OVERLAY;
920         command.canvas = canvas;
921         command.frame = output;
922         command.input = input;
923         command.in_x1 = in_x1;
924         command.in_y1 = in_y1;
925         command.in_x2 = in_x2;
926         command.in_y2 = in_y2;
927         command.out_x1 = out_x1;
928         command.out_y1 = out_y1;
929         command.out_x2 = out_x2;
930         command.out_y2 = out_y2;
931         command.alpha = alpha;
932         command.mode = mode;
933         command.interpolation_type = interpolation_type;
934         command.is_nested = is_nested;
935         send_command(&command);
936 }
937
938 void Playback3D::overlay_sync(Playback3DCommand *command)
939 {
940 #ifdef HAVE_GL
941 // To do these operations, we need to copy the input buffer to a texture
942 // and blend 2 textures in a shader
943         static const char * const overlay_shaders[TRANSFER_TYPES] = {
944                 blend_NORMAL_frag,      // TRANSFER_NORMAL
945                 blend_ADDITION_frag,    // TRANSFER_ADDITION
946                 blend_SUBTRACT_frag,    // TRANSFER_SUBTRACT
947                 blend_MULTIPLY_frag,    // TRANSFER_MULTIPLY
948                 blend_DIVIDE_frag,      // TRANSFER_DIVIDE
949                 blend_REPLACE_frag,     // TRANSFER_REPLACE
950                 blend_MAX_frag,         // TRANSFER_MAX
951                 blend_MIN_frag,         // TRANSFER_MIN
952                 blend_DARKEN_frag,      // TRANSFER_DARKEN
953                 blend_LIGHTEN_frag,     // TRANSFER_LIGHTEN
954                 blend_DST_frag,         // TRANSFER_DST
955                 blend_DST_ATOP_frag,    // TRANSFER_DST_ATOP
956                 blend_DST_IN_frag,      // TRANSFER_DST_IN
957                 blend_DST_OUT_frag,     // TRANSFER_DST_OUT
958                 blend_DST_OVER_frag,    // TRANSFER_DST_OVER
959                 blend_SRC_frag,         // TRANSFER_SRC
960                 blend_SRC_ATOP_frag,    // TRANSFER_SRC_ATOP
961                 blend_SRC_IN_frag,      // TRANSFER_SRC_IN
962                 blend_SRC_OUT_frag,     // TRANSFER_SRC_OUT
963                 blend_SRC_OVER_frag,    // TRANSFER_SRC_OVER
964                 blend_AND_frag,         // TRANSFER_AND
965                 blend_OR_frag,          // TRANSFER_OR
966                 blend_XOR_frag,         // TRANSFER_XOR
967                 blend_OVERLAY_frag,     // TRANSFER_OVERLAY
968                 blend_SCREEN_frag,      // TRANSFER_SCREEN
969                 blend_BURN_frag,        // TRANSFER_BURN
970                 blend_DODGE_frag,       // TRANSFER_DODGE
971                 blend_HARDLIGHT_frag,   // TRANSFER_HARDLIGHT
972                 blend_SOFTLIGHT_frag,   // TRANSFER_SOFTLIGHT
973                 blend_DIFFERENCE_frag,  // TRANSFER_DIFFERENCE
974         };
975
976         BC_WindowBase *window =
977                 command->canvas->lock_canvas("Playback3D::overlay_sync");
978         if( window ) {
979 // Make sure OpenGL is enabled first.
980                 window->enable_opengl();
981                 window->update_video_cursor();
982
983                 glColor4f(1, 1, 1, 1);
984                 glDisable(GL_BLEND);
985
986
987 //printf("Playback3D::overlay_sync 1 %d\n", command->input->get_opengl_state());
988                 switch( command->input->get_opengl_state() ) {
989 // Upload texture and composite to screen
990                 case VFrame::RAM:
991                         command->input->to_texture();
992                         break;
993 // Just composite texture to screen
994                 case VFrame::TEXTURE:
995                         break;
996 // read from PBuffer to texture, then composite texture to screen
997                 case VFrame::SCREEN:
998                         command->input->enable_opengl();
999                         command->input->screen_to_texture();
1000                         break;
1001                 default:
1002                         printf("Playback3D::overlay_sync unknown state\n");
1003                         break;
1004                 }
1005
1006                 if(command->frame) {
1007 // Render to PBuffer
1008                         command->frame->enable_opengl();
1009                         command->frame->set_opengl_state(VFrame::SCREEN);
1010                         canvas_w = command->frame->get_w();
1011                         canvas_h = command->frame->get_h();
1012                 }
1013                 else {
1014 // Render to canvas
1015                         window->enable_opengl();
1016                         canvas_w = window->get_w();
1017                         canvas_h = window->get_h();
1018                 }
1019
1020
1021                 const char *shader_stack[16];
1022                 memset(shader_stack,0, sizeof(shader_stack));
1023                 int total_shaders = 0, need_matrix = 0;
1024
1025                 VFrame::init_screen(canvas_w, canvas_h);
1026
1027 // Enable texture
1028                 command->input->bind_texture(0);
1029
1030 // Convert colormodel to RGB if not nested.
1031 // The color model setting in the output frame is ignored.
1032 //              if( command->is_nested <= 0 &&  // not nested
1033 //                  BC_CModels::is_yuv(command->input->get_color_model()) ) {
1034 //                      need_matrix = 1;
1035 //                      shader_stack[total_shaders++] = yuv_to_rgb_frag;
1036 //              }
1037
1038 // get the shaders
1039 #define add_shader(s) \
1040   if(!total_shaders) shader_stack[total_shaders++] = read_texture_frag; \
1041   shader_stack[total_shaders++] = s
1042
1043                 switch(command->mode) {
1044                 case TRANSFER_REPLACE:
1045 // This requires overlaying an alpha multiplied image on a black screen.
1046                         if( command->input->get_texture_components() != 4 ) break;
1047                         add_shader(overlay_shaders[command->mode]);
1048                         break;
1049                 default:
1050                         enable_overlay_texture(command);
1051                         add_shader(overlay_shaders[command->mode]);
1052                         break;
1053                 }
1054
1055 // if to flatten alpha
1056 //              if( command->is_nested < 0 ) {
1057 //                      switch(command->input->get_color_model()) {
1058 //// yuv has already been converted to rgb
1059 //                      case BC_YUVA8888:
1060 //                      case BC_RGBA_FLOAT:
1061 //                      case BC_RGBA8888:
1062 //                              add_shader(rgba_to_rgb_flatten);
1063 //                              break;
1064 //                      }
1065 //              }
1066
1067 // run the shaders
1068                 add_shader(0);
1069                 unsigned int shader = !shader_stack[0] ? 0 :
1070                         VFrame::make_shader(shader_stack);
1071                 if( shader > 0 ) {
1072                         glUseProgram(shader);
1073                         if( need_matrix ) BC_GL_YUV_TO_RGB(shader);
1074 // Set texture unit of the texture
1075                         glUniform1i(glGetUniformLocation(shader, "tex"), 0);
1076 // Set texture unit of the temp texture
1077                         glUniform1i(glGetUniformLocation(shader, "tex2"), 1);
1078 // Set alpha
1079                         int variable = glGetUniformLocation(shader, "alpha");
1080                         glUniform1f(variable, command->alpha);
1081 // Set dimensions of the temp texture
1082                         if(temp_texture)
1083                                 glUniform2f(glGetUniformLocation(shader, "tex2_dimensions"),
1084                                         (float)temp_texture->get_texture_w(),
1085                                         (float)temp_texture->get_texture_h());
1086                 }
1087                 else
1088                         glUseProgram(0);
1089
1090
1091 //printf("Playback3D::overlay_sync %f %f %f %f %f %f %f %f\n",
1092 // command->in_x1, command->in_y1, command->in_x2, command->in_y2,
1093 // command->out_x1, command->out_y1, command->out_x2, command->out_y2);
1094
1095                 command->input->draw_texture(
1096                         command->in_x1, command->in_y1, command->in_x2, command->in_y2,
1097                         command->out_x1, command->out_y1, command->out_x2, command->out_y2,
1098                         !command->is_nested);
1099                 glUseProgram(0);
1100
1101 // Delete temp texture
1102                 if(temp_texture) {
1103                         delete temp_texture;
1104                         temp_texture = 0;
1105                         glActiveTexture(GL_TEXTURE1);
1106                         glDisable(GL_TEXTURE_2D);
1107                 }
1108                 glActiveTexture(GL_TEXTURE0);
1109                 glDisable(GL_TEXTURE_2D);
1110         }
1111         command->canvas->unlock_canvas();
1112 #endif
1113 }
1114
1115 void Playback3D::enable_overlay_texture(Playback3DCommand *command)
1116 {
1117 #ifdef HAVE_GL
1118         glDisable(GL_BLEND);
1119
1120         glActiveTexture(GL_TEXTURE1);
1121         BC_Texture::new_texture(&temp_texture, canvas_w, canvas_h,
1122                 command->input->get_color_model());
1123         temp_texture->bind(1);
1124
1125 // Read canvas into texture
1126         glReadBuffer(GL_BACK);
1127         glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, canvas_w, canvas_h);
1128 #endif
1129 }
1130
1131
1132 void Playback3D::do_mask(Canvas *canvas,
1133         VFrame *output,
1134         int64_t start_position_project,
1135         MaskAutos *keyframe_set,
1136         MaskAuto *keyframe,
1137         MaskAuto *default_auto)
1138 {
1139         Playback3DCommand command;
1140         command.command = Playback3DCommand::DO_MASK;
1141         command.canvas = canvas;
1142         command.frame = output;
1143         command.start_position_project = start_position_project;
1144         command.keyframe_set = keyframe_set;
1145         command.keyframe = keyframe;
1146         command.default_auto = default_auto;
1147
1148         send_command(&command);
1149 }
1150
1151
1152
1153 #ifdef HAVE_GL
1154 struct Vertex : ListItem<Vertex>
1155 {
1156         GLdouble c[3];
1157 };
1158 // this list is only used from the main thread, no locking needed
1159 // this must be a list so that pointers to allocated entries remain valid
1160 // when new entries are added
1161 static List<Vertex> *vertex_cache = 0;
1162
1163 static void combine_callback(GLdouble coords[3],
1164         GLdouble *vertex_data[4],
1165         GLfloat weight[4],
1166         GLdouble **dataOut)
1167 {
1168 // can't use malloc here; GLU doesn't delete the memory for us!
1169         Vertex* vertex = vertex_cache->append();
1170         vertex->c[0] = coords[0];
1171         vertex->c[1] = coords[1];
1172         vertex->c[2] = coords[2];
1173 // we don't need to interpolate anything
1174
1175         *dataOut = &vertex->c[0];
1176 }
1177 #endif
1178
1179
1180 void Playback3D::do_mask_sync(Playback3DCommand *command)
1181 {
1182 #ifdef HAVE_GL
1183         BC_WindowBase *window =
1184                 command->canvas->lock_canvas("Playback3D::do_mask_sync");
1185         if( window ) {
1186                 window->enable_opengl();
1187
1188                 switch( command->frame->get_opengl_state() ) {
1189                 case VFrame::RAM:
1190 // Time to upload to the texture
1191                         command->frame->to_texture();
1192                         break;
1193
1194                 case VFrame::SCREEN:
1195 // Read back from PBuffer
1196 // Bind context to pbuffer
1197                         command->frame->enable_opengl();
1198                         command->frame->screen_to_texture();
1199                         break;
1200                 }
1201 // Create PBuffer and draw the mask on it
1202                 command->frame->enable_opengl();
1203
1204 // Initialize coordinate system
1205                 int w = command->frame->get_w();
1206                 int h = command->frame->get_h();
1207                 command->frame->init_screen();
1208
1209 // Clear screen
1210                 glDisable(GL_TEXTURE_2D);
1211                 float value = command->keyframe->value / 100.f;
1212                 if( value >= 0 ) {
1213                         if( command->default_auto->mode == MASK_MULTIPLY_ALPHA ) {
1214                                 glClearColor(0.f, 0.f, 0.f, 0.f);
1215                                 glColor4f(value, value, value, 1.f);
1216                         }
1217                         else {
1218                                 glClearColor(1.f, 1.f, 1.f, 1.f);
1219                                 value = 1.f - value;
1220                                 glColor4f(value, value, value, 1.f);
1221                         }
1222                 }
1223                 else {
1224                         if( command->default_auto->mode == MASK_MULTIPLY_ALPHA ) {
1225                                 value = -value;
1226                                 glClearColor(value, value, value, 1.f);
1227                                 glColor4f(0.f, 0.f, 0.f, 0.f);
1228                         }
1229                         else {
1230                                 value = 1.f + value;
1231                                 glClearColor(value, value, value, 1.f);
1232                                 glColor4f(1.f, 1.f, 1.f, 1.f);
1233                         }
1234                 }
1235                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1236
1237
1238 // Draw mask with scaling to simulate feathering
1239                 GLUtesselator *tesselator = gluNewTess();
1240                 gluTessProperty(tesselator, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD);
1241                 gluTessCallback(tesselator, GLU_TESS_VERTEX, (GLvoid (*) ( )) &glVertex3dv);
1242                 gluTessCallback(tesselator, GLU_TESS_BEGIN, (GLvoid (*) ( )) &glBegin);
1243                 gluTessCallback(tesselator, GLU_TESS_END, (GLvoid (*) ( )) &glEnd);
1244                 gluTessCallback(tesselator, GLU_TESS_COMBINE, (GLvoid (*) ( ))&combine_callback);
1245
1246                 vertex_cache = new List<Vertex>;
1247
1248
1249 // Draw every submask as a new polygon
1250                 int total_submasks = command->keyframe_set->total_submasks(
1251                         command->start_position_project,
1252                         PLAY_FORWARD);
1253                 float scale = command->keyframe->feather + 1;
1254                 int display_list = glGenLists(1);
1255                 glNewList(display_list, GL_COMPILE);
1256                 for(int k = 0; k < total_submasks; k++)
1257                 {
1258                         gluTessBeginPolygon(tesselator, NULL);
1259                         gluTessBeginContour(tesselator);
1260                         ArrayList<MaskPoint*> *points = new ArrayList<MaskPoint*>;
1261                         command->keyframe_set->get_points(points,
1262                                 k,
1263                                 command->start_position_project,
1264                                 PLAY_FORWARD);
1265
1266                         int first_point = 0;
1267 // Need to tabulate every vertex in persistent memory because
1268 // gluTessVertex doesn't copy them.
1269                         ArrayList<GLdouble*> coords;
1270                         coords.set_array_delete();
1271                         for(int i = 0; i < points->total; i++)
1272                         {
1273                                 MaskPoint *point1 = points->values[i];
1274                                 MaskPoint *point2 = (i >= points->total - 1) ?
1275                                         points->values[0] :
1276                                         points->values[i + 1];
1277
1278                                 float x, y;
1279                                 int segments = 0;
1280                                 if(point1->control_x2 == 0 &&
1281                                         point1->control_y2 == 0 &&
1282                                         point2->control_x1 == 0 &&
1283                                         point2->control_y1 == 0)
1284                                         segments = 1;
1285
1286                                 float x0 = point1->x;
1287                                 float y0 = point1->y;
1288                                 float x1 = point1->x + point1->control_x2;
1289                                 float y1 = point1->y + point1->control_y2;
1290                                 float x2 = point2->x + point2->control_x1;
1291                                 float y2 = point2->y + point2->control_y1;
1292                                 float x3 = point2->x;
1293                                 float y3 = point2->y;
1294
1295                                 // forward differencing bezier curves implementation taken from GPL code at
1296                                 // http://cvs.sourceforge.net/viewcvs.py/guliverkli/guliverkli/src/subtitles/Rasterizer.cpp?rev=1.3
1297
1298                                 float cx3, cx2, cx1, cx0, cy3, cy2, cy1, cy0;
1299
1300                                 // [-1 +3 -3 +1]
1301                                 // [+3 -6 +3  0]
1302                                 // [-3 +3  0  0]
1303                                 // [+1  0  0  0]
1304
1305                                 cx3 = -  x0 + 3*x1 - 3*x2 + x3;
1306                                 cx2 =  3*x0 - 6*x1 + 3*x2;
1307                                 cx1 = -3*x0 + 3*x1;
1308                                 cx0 =    x0;
1309
1310                                 cy3 = -  y0 + 3*y1 - 3*y2 + y3;
1311                                 cy2 =  3*y0 - 6*y1 + 3*y2;
1312                                 cy1 = -3*y0 + 3*y1;
1313                                 cy0 =    y0;
1314
1315                                 // This equation is from Graphics Gems I.
1316                                 //
1317                                 // The idea is that since we're approximating a cubic curve with lines,
1318                                 // any error we incur is due to the curvature of the line, which we can
1319                                 // estimate by calculating the maximum acceleration of the curve.  For
1320                                 // a cubic, the acceleration (second derivative) is a line, meaning that
1321                                 // the absolute maximum acceleration must occur at either the beginning
1322                                 // (|c2|) or the end (|c2+c3|).  Our bounds here are a little more
1323                                 // conservative than that, but that's okay.
1324                                 if (segments == 0)
1325                                 {
1326                                         float maxaccel1 = fabs(2*cy2) + fabs(6*cy3);
1327                                         float maxaccel2 = fabs(2*cx2) + fabs(6*cx3);
1328
1329                                         float maxaccel = maxaccel1 > maxaccel2 ? maxaccel1 : maxaccel2;
1330                                         float h = 1.0;
1331
1332                                         if(maxaccel > 8.0) h = sqrt((8.0) / maxaccel);
1333                                         segments = int(1/h);
1334                                 }
1335
1336                                 for(int j = 0; j <= segments; j++)
1337                                 {
1338                                         float t = (float)j / segments;
1339                                         x = cx0 + t*(cx1 + t*(cx2 + t*cx3));
1340                                         y = cy0 + t*(cy1 + t*(cy2 + t*cy3));
1341
1342                                         if(j > 0 || first_point)
1343                                         {
1344                                                 GLdouble *coord = new GLdouble[3];
1345                                                 coord[0] = x / scale;
1346                                                 coord[1] = -h + y / scale;
1347                                                 coord[2] = 0;
1348                                                 coords.append(coord);
1349                                                 first_point = 0;
1350                                         }
1351                                 }
1352                         }
1353
1354 // Now that we know the total vertices, send them to GLU
1355                         for(int i = 0; i < coords.total; i++)
1356                                 gluTessVertex(tesselator, coords.values[i], coords.values[i]);
1357
1358                         gluTessEndContour(tesselator);
1359                         gluTessEndPolygon(tesselator);
1360                         points->remove_all_objects();
1361                         delete points;
1362                         coords.remove_all_objects();
1363                 }
1364                 glEndList();
1365                 glCallList(display_list);
1366                 glDeleteLists(display_list, 1);
1367                 gluDeleteTess(tesselator);
1368
1369                 delete vertex_cache;
1370                 vertex_cache = 0;
1371
1372                 glColor4f(1, 1, 1, 1);
1373
1374
1375 // Read mask into temporary texture.
1376 // For feathering, just read the part of the screen after the downscaling.
1377
1378
1379                 float w_scaled = w / scale;
1380                 float h_scaled = h / scale;
1381 // Don't vary the texture size according to scaling because that
1382 // would waste memory.
1383 // This enables and binds the temporary texture.
1384                 glActiveTexture(GL_TEXTURE1);
1385                 BC_Texture::new_texture(&temp_texture,
1386                         w,
1387                         h,
1388                         command->frame->get_color_model());
1389                 temp_texture->bind(1);
1390                 glReadBuffer(GL_BACK);
1391
1392 // Need to add extra size to fill in the bottom right
1393                 glCopyTexSubImage2D(GL_TEXTURE_2D,
1394                         0,
1395                         0,
1396                         0,
1397                         0,
1398                         0,
1399                         (int)MIN(w_scaled + 2, w),
1400                         (int)MIN(h_scaled + 2, h));
1401
1402                 command->frame->bind_texture(0);
1403
1404
1405 // For feathered masks, use a shader to multiply.
1406 // For unfeathered masks, we could use a stencil buffer
1407 // for further optimization but we also need a YUV algorithm.
1408                 unsigned int frag_shader = 0;
1409                 switch(temp_texture->get_texture_components()) {
1410                 case 3:
1411                         frag_shader = VFrame::make_shader(0,
1412                                 command->frame->get_color_model() == BC_YUV888 ?
1413                                         multiply_yuvmask3_frag : multiply_mask3_frag,
1414                                 0);
1415                         break;
1416                 case 4:
1417                         frag_shader = VFrame::make_shader(0, multiply_mask4_frag, 0);
1418                         break;
1419                 }
1420
1421                 if( frag_shader ) {
1422                         int variable;
1423                         glUseProgram(frag_shader);
1424                         if((variable = glGetUniformLocation(frag_shader, "tex")) >= 0)
1425                                 glUniform1i(variable, 0);
1426                         if((variable = glGetUniformLocation(frag_shader, "tex1")) >= 0)
1427                                 glUniform1i(variable, 1);
1428                         if((variable = glGetUniformLocation(frag_shader, "scale")) >= 0)
1429                                 glUniform1f(variable, scale);
1430                 }
1431
1432
1433
1434 // Write texture to PBuffer with multiply and scaling for feather.
1435
1436
1437                 command->frame->draw_texture(0, 0, w, h, 0, 0, w, h);
1438                 command->frame->set_opengl_state(VFrame::SCREEN);
1439
1440
1441 // Disable temp texture
1442                 glUseProgram(0);
1443
1444                 glActiveTexture(GL_TEXTURE1);
1445                 glDisable(GL_TEXTURE_2D);
1446                 delete temp_texture;
1447                 temp_texture = 0;
1448
1449                 glActiveTexture(GL_TEXTURE0);
1450                 glDisable(GL_TEXTURE_2D);
1451
1452 // Default drawable
1453                 window->enable_opengl();
1454         }
1455         command->canvas->unlock_canvas();
1456 #endif
1457 }
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468 void Playback3D::convert_cmodel(Canvas *canvas,
1469         VFrame *output,
1470         int dst_cmodel)
1471 {
1472 // Do nothing if colormodels are equivalent in OpenGL & the image is in hardware.
1473         int src_cmodel = output->get_color_model();
1474         if(
1475                 (output->get_opengl_state() == VFrame::TEXTURE ||
1476                 output->get_opengl_state() == VFrame::SCREEN) &&
1477 // OpenGL has no floating point.
1478                 ( (src_cmodel == BC_RGB888 && dst_cmodel == BC_RGB_FLOAT) ||
1479                   (src_cmodel == BC_RGBA8888 && dst_cmodel == BC_RGBA_FLOAT) ||
1480                   (src_cmodel == BC_RGB_FLOAT && dst_cmodel == BC_RGB888) ||
1481                   (src_cmodel == BC_RGBA_FLOAT && dst_cmodel == BC_RGBA8888) ||
1482 // OpenGL sets alpha to 1 on import
1483                   (src_cmodel == BC_RGB888 && dst_cmodel == BC_RGBA8888) ||
1484                   (src_cmodel == BC_YUV888 && dst_cmodel == BC_YUVA8888) ||
1485                   (src_cmodel == BC_RGB_FLOAT && dst_cmodel == BC_RGBA_FLOAT) )
1486                 ) return;
1487
1488
1489
1490         Playback3DCommand command;
1491         command.command = Playback3DCommand::CONVERT_CMODEL;
1492         command.canvas = canvas;
1493         command.frame = output;
1494         command.dst_cmodel = dst_cmodel;
1495         send_command(&command);
1496 }
1497
1498 void Playback3D::convert_cmodel_sync(Playback3DCommand *command)
1499 {
1500 #ifdef HAVE_GL
1501         BC_WindowBase *window = 
1502                 command->canvas->lock_canvas("Playback3D::convert_cmodel_sync");
1503         if( window ) {
1504                 window->enable_opengl();
1505
1506 // Import into hardware
1507                 command->frame->enable_opengl();
1508                 command->frame->init_screen();
1509                 command->frame->to_texture();
1510
1511 // Colormodel permutation
1512                 int src_cmodel = command->frame->get_color_model();
1513                 int dst_cmodel = command->dst_cmodel;
1514                 typedef struct {
1515                         int src, dst, typ;
1516                         const char *shader;
1517                 } cmodel_shader_table_t;
1518                 enum { rgb_to_rgb, rgb_to_yuv, yuv_to_rgb, yuv_to_yuv, };
1519                 int type = -1;
1520                 static cmodel_shader_table_t cmodel_shader_table[]  = {
1521                         { BC_RGB888,    BC_YUV888,      rgb_to_yuv, rgb_to_yuv_frag  },
1522                         { BC_RGB888,    BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1523                         { BC_RGBA8888,  BC_RGB888,      rgb_to_rgb, rgba_to_rgb_frag },
1524                         { BC_RGBA8888,  BC_RGB_FLOAT,   rgb_to_rgb, rgba_to_rgb_frag },
1525                         { BC_RGBA8888,  BC_YUV888,      rgb_to_yuv, rgba_to_yuv_frag },
1526                         { BC_RGBA8888,  BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1527                         { BC_RGB_FLOAT, BC_YUV888,      rgb_to_yuv, rgb_to_yuv_frag  },
1528                         { BC_RGB_FLOAT, BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1529                         { BC_RGBA_FLOAT,BC_RGB888,      rgb_to_rgb, rgba_to_rgb_frag },
1530                         { BC_RGBA_FLOAT,BC_RGB_FLOAT,   rgb_to_rgb, rgba_to_rgb_frag },
1531                         { BC_RGBA_FLOAT,BC_YUV888,      rgb_to_yuv, rgba_to_yuv_frag },
1532                         { BC_RGBA_FLOAT,BC_YUVA8888,    rgb_to_yuv, rgb_to_yuv_frag  },
1533                         { BC_YUV888,    BC_RGB888,      yuv_to_rgb, yuv_to_rgb_frag  },
1534                         { BC_YUV888,    BC_RGBA8888,    yuv_to_rgb, yuv_to_rgb_frag  },
1535                         { BC_YUV888,    BC_RGB_FLOAT,   yuv_to_rgb, yuv_to_rgb_frag  },
1536                         { BC_YUV888,    BC_RGBA_FLOAT,  yuv_to_rgb, yuv_to_rgb_frag  },
1537                         { BC_YUVA8888,  BC_RGB888,      yuv_to_rgb, yuva_to_rgb_frag },
1538                         { BC_YUVA8888,  BC_RGBA8888,    yuv_to_rgb, yuv_to_rgb_frag  },
1539                         { BC_YUVA8888,  BC_RGB_FLOAT,   yuv_to_rgb, yuva_to_rgb_frag },
1540                         { BC_YUVA8888,  BC_RGBA_FLOAT,  yuv_to_rgb, yuv_to_rgb_frag  },
1541                         { BC_YUVA8888,  BC_YUV888,      yuv_to_yuv, yuva_to_yuv_frag },
1542                 };
1543
1544                 const char *shader = 0;
1545                 int table_size = sizeof(cmodel_shader_table) / sizeof(cmodel_shader_table_t);
1546                 for( int i=0; i<table_size; ++i ) {
1547                         if( cmodel_shader_table[i].src == src_cmodel &&
1548                             cmodel_shader_table[i].dst == dst_cmodel ) {
1549                                 shader = cmodel_shader_table[i].shader;
1550                                 type = cmodel_shader_table[i].typ;
1551                                 break;
1552                         }
1553                 }
1554
1555 // printf("Playback3D::convert_cmodel_sync %d %d %d shader=\n%s",
1556 // __LINE__,
1557 // command->frame->get_color_model(),
1558 // command->dst_cmodel,
1559 // shader);
1560
1561                 const char *shader_stack[9];
1562                 memset(shader_stack,0, sizeof(shader_stack));
1563                 int current_shader = 0;
1564
1565                 if( shader ) {
1566 //printf("Playback3D::convert_cmodel_sync %d\n", __LINE__);
1567                         shader_stack[current_shader++] = shader;
1568                         shader_stack[current_shader] = 0;
1569                         unsigned int shader_id = VFrame::make_shader(shader_stack);
1570
1571                         command->frame->bind_texture(0);
1572                         glUseProgram(shader_id);
1573
1574                         glUniform1i(glGetUniformLocation(shader_id, "tex"), 0);
1575                         switch( type ) {
1576                         case rgb_to_yuv:
1577                                 BC_GL_RGB_TO_YUV(shader_id);
1578                                 break;
1579                         case yuv_to_rgb:
1580                                 BC_GL_YUV_TO_RGB(shader_id);
1581                                 break;
1582                         }
1583
1584                         command->frame->draw_texture();
1585                         if(shader) glUseProgram(0);
1586                         command->frame->set_opengl_state(VFrame::SCREEN);
1587                 }
1588         }
1589
1590         command->canvas->unlock_canvas();
1591 #endif // HAVE_GL
1592 }
1593
1594 void Playback3D::do_fade(Canvas *canvas, VFrame *frame, float fade)
1595 {
1596         Playback3DCommand command;
1597         command.command = Playback3DCommand::DO_FADE;
1598         command.canvas = canvas;
1599         command.frame = frame;
1600         command.alpha = fade;
1601         send_command(&command);
1602 }
1603
1604 void Playback3D::do_fade_sync(Playback3DCommand *command)
1605 {
1606 #ifdef HAVE_GL
1607         BC_WindowBase *window =
1608                 command->canvas->lock_canvas("Playback3D::do_fade_sync");
1609         if( window ) {
1610                 window->enable_opengl();
1611                 switch( command->frame->get_opengl_state() ) {
1612                 case VFrame::RAM:
1613                         command->frame->to_texture();
1614                         break;
1615
1616                 case VFrame::SCREEN:
1617 // Read back from PBuffer
1618 // Bind context to pbuffer
1619                         command->frame->enable_opengl();
1620                         command->frame->screen_to_texture();
1621                         break;
1622                 }
1623
1624                 command->frame->enable_opengl();
1625                 command->frame->init_screen();
1626                 command->frame->bind_texture(0);
1627
1628 //              glClearColor(0.0, 0.0, 0.0, 0.0);
1629 //              glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1630                 glDisable(GL_BLEND);
1631                 unsigned int frag_shader = 0;
1632                 switch(command->frame->get_color_model())
1633                 {
1634 // For the alpha colormodels, the native function seems to multiply the
1635 // components by the alpha instead of just the alpha.
1636                         case BC_RGBA8888:
1637                         case BC_RGBA_FLOAT:
1638                         case BC_YUVA8888:
1639                                 frag_shader = VFrame::make_shader(0, fade_rgba_frag, 0);
1640                                 break;
1641
1642                         case BC_RGB888:
1643                                 glEnable(GL_BLEND);
1644                                 glBlendFunc(GL_SRC_ALPHA, GL_ZERO);
1645                                 glColor4f(command->alpha, command->alpha, command->alpha, 1);
1646                                 break;
1647
1648
1649                         case BC_YUV888:
1650                                 frag_shader = VFrame::make_shader(0, fade_yuv_frag, 0);
1651                                 break;
1652                 }
1653
1654
1655                 if( frag_shader ) {
1656                         glUseProgram(frag_shader);
1657                         int variable;
1658                         if((variable = glGetUniformLocation(frag_shader, "tex")) >= 0)
1659                                 glUniform1i(variable, 0);
1660                         if((variable = glGetUniformLocation(frag_shader, "alpha")) >= 0)
1661                                 glUniform1f(variable, command->alpha);
1662                 }
1663
1664                 command->frame->draw_texture();
1665                 command->frame->set_opengl_state(VFrame::SCREEN);
1666
1667                 if(frag_shader)
1668                 {
1669                         glUseProgram(0);
1670                 }
1671
1672                 glColor4f(1, 1, 1, 1);
1673                 glDisable(GL_BLEND);
1674         }
1675         command->canvas->unlock_canvas();
1676 #endif
1677 }
1678
1679
1680 int Playback3D::run_plugin(Canvas *canvas, PluginClient *client)
1681 {
1682         Playback3DCommand command;
1683         command.command = Playback3DCommand::PLUGIN;
1684         command.canvas = canvas;
1685         command.plugin_client = client;
1686         return send_command(&command);
1687 }
1688
1689 void Playback3D::run_plugin_sync(Playback3DCommand *command)
1690 {
1691         BC_WindowBase *window = 
1692                 command->canvas->lock_canvas("Playback3D::run_plugin_sync");
1693         if( window ) {
1694                 window->enable_opengl();
1695                 command->result = ((PluginVClient*)command->plugin_client)->handle_opengl();
1696         }
1697         command->canvas->unlock_canvas();
1698 }
1699
1700