titler fixes, auto paste bug, resize popup hang, focus policy fix, chk lang
[goodguy/history.git] / cinelerra-5.1 / plugins / titler / titler.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 1997-2014 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 // Originally developed by Heroine Virtual Ltd.
23 // Support for multiple encodings, outline (stroke) by
24 // Andraz Tori <Andraz.tori1@guest.arnes.si>
25 // Additional support for UTF-8 by
26 // Paolo Rampino aka Akirad <info at tuttoainternet.it>
27
28
29 #include "asset.h"
30 #include "bccmodels.h"
31 #include "bcsignals.h"
32 #include "cache.h"
33 #include "clip.h"
34 #include "cstrdup.h"
35 #include "edl.h"
36 #include "edlsession.h"
37 #include "file.h"
38 #include "filexml.h"
39 #include "filesystem.h"
40 #include "indexable.h"
41 #include "ft2build.h"
42 #include FT_GLYPH_H
43 #include FT_BBOX_H
44 #include FT_OUTLINE_H
45 #include FT_STROKER_H
46 #include "language.h"
47 #include "mwindow.inc"
48 #include "overlayframe.h"
49 #include "plugin.h"
50 #include "renderengine.h"
51 #include "titler.h"
52 #include "titlerwindow.h"
53 #include "transportque.h"
54 #include "vrender.h"
55
56
57 #include <errno.h>
58 #include <stdint.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <endian.h>
62 #include <byteswap.h>
63 #include <iconv.h>
64 #include <wctype.h>
65 #include <sys/stat.h>
66 #include <fontconfig/fontconfig.h>
67
68 #define FIXED_FONT "Bitstream Vera Sans Mono (Bits)"
69 #define SMALL (1.0 / 64.0)
70
71 #define MAX_FLT  3.40282347e+38
72 #define MIN_FLT -3.40282347e+38
73
74 REGISTER_PLUGIN(TitleMain)
75
76 #ifdef X_HAVE_UTF8_STRING
77 #define DEFAULT_ENCODING "UTF-8"
78 #else
79 #define DEFAULT_ENCODING "ISO8859-1"
80 #endif
81 #define DEFAULT_TIMECODEFORMAT TIME_HMS
82
83 TitleConfig::TitleConfig()
84 {
85         strcpy(font, "fixed");
86         strcpy(encoding, DEFAULT_ENCODING);
87         style = 0;
88         size = 24;
89         color = BLACK;
90         alpha = 0xff;
91         outline_size = 0.;
92         outline_color = WHITE;
93         outline_alpha = 0xff;
94         color_stroke = 0xff0000;
95         stroke_width = 1.0;
96         motion_strategy = NO_MOTION;
97         line_pitch = 0;
98         loop = 0;
99         hjustification = JUSTIFY_CENTER;
100         vjustification = JUSTIFY_MID;
101         fade_in = 0.0;  fade_out = 0.0;
102         pixels_per_second = 100.0;
103         wtext[0] = 0;  wlen = 0;
104         title_x = title_y = 0.0;
105         title_w = title_h = 0;
106         window_w = 800;
107         window_h = 460;
108         next_keyframe_position = 0;
109         prev_keyframe_position = 0;
110         timecode = 0;
111         dropshadow = 2;
112         background = 0;
113         strcpy(background_path, "");
114         timecode_format = DEFAULT_TIMECODEFORMAT;
115         drag = 0;
116         loop_playback = 0;
117 }
118
119 TitleConfig::~TitleConfig()
120 {
121 }
122
123 int TitleConfig::equivalent(TitleConfig &that)
124 {
125         return !strcasecmp(font, that.font) &&
126                 !strcasecmp(encoding, that.encoding) &&
127                 style == that.style &&
128                 size == that.size &&
129                 color == that.color &&
130                 alpha == that.alpha &&
131                 outline_size == that.outline_size &&
132                 outline_color == that.outline_color &&
133                 outline_alpha == that.outline_alpha &&
134                 color_stroke == that.color_stroke &&
135                 stroke_width == that.stroke_width &&
136 // dont require redraw for these
137 //              motion_strategy == that.motion_strategy &&
138                 line_pitch == that.line_pitch &&
139 //              loop == that.loop &&
140                 hjustification == that.hjustification &&
141                 vjustification == that.vjustification &&
142 //              fade_in == that.fade_in && fade_out == that.fade_out &&
143 //              EQUIV(pixels_per_second, that.pixels_per_second) &&
144                 wlen == that.wlen &&
145                 !memcmp(wtext, that.wtext, wlen * sizeof(wchar_t)) &&
146 //              title_x == that.title_x && title_y == that.title_y &&
147                 title_w == that.title_w && title_h == that.title_h &&
148 //              window_w == that.window_w && window_h == that.window_h &&
149                 timecode == that.timecode &&
150                 dropshadow == that.dropshadow &&
151                 background == that.background &&
152                 !strcmp(background_path, that.background_path) &&
153                 timecode_format == that.timecode_format &&
154 //              drag == that.drag &&
155                 loop_playback == that.loop_playback;
156 }
157
158 void TitleConfig::copy_from(TitleConfig &that)
159 {
160         strcpy(font, that.font);
161         strcpy(encoding, that.encoding);
162         style = that.style;
163         size = that.size;
164         color = that.color;
165         alpha = that.alpha;
166         outline_size = that.outline_size;
167         outline_color = that.outline_color;
168         outline_alpha = that.outline_alpha;
169         color_stroke = that.color_stroke;
170         stroke_width = that.stroke_width;
171         motion_strategy = that.motion_strategy;
172         line_pitch = that.line_pitch;
173         loop = that.loop;
174         hjustification = that.hjustification;
175         vjustification = that.vjustification;
176         fade_in = that.fade_in;
177         fade_out = that.fade_out;
178         pixels_per_second = that.pixels_per_second;
179         wlen = that.wlen;
180         memcpy(wtext, that.wtext, that.wlen * sizeof(wchar_t));
181         title_x = that.title_x;  title_y = that.title_y;
182         title_w = that.title_w;  title_h = that.title_h;
183         window_w = that.window_w;  window_h = that.window_h;
184         timecode = that.timecode;
185         dropshadow = that.dropshadow;
186         background = that.background;
187         strcpy(background_path, that.background_path);
188         timecode_format = that.timecode_format;
189         drag = that.drag;
190         loop_playback = that.loop_playback;
191 }
192
193 void TitleConfig::interpolate(TitleConfig &prev, TitleConfig &next,
194         int64_t prev_frame, int64_t next_frame, int64_t current_frame)
195 {
196         double next_scale = (double)(current_frame - prev_frame) / (next_frame - prev_frame);
197         double prev_scale = (double)(next_frame - current_frame) / (next_frame - prev_frame);
198         strcpy(font, prev.font);
199         strcpy(encoding, prev.encoding);
200         style = prev.style;
201         size = prev.size;
202         color = prev.color;
203         alpha = prev.alpha;
204         outline_size = prev.outline_size;
205         outline_color = prev.outline_color;
206         outline_alpha = prev.outline_alpha;
207         color_stroke = prev.color_stroke;
208         stroke_width = prev.stroke_width;
209         motion_strategy = prev.motion_strategy;
210         line_pitch = prev.line_pitch;
211         loop = prev.loop;
212         hjustification = prev.hjustification;
213         vjustification = prev.vjustification;
214         fade_in = prev.fade_in;
215         fade_out = prev.fade_out;
216         pixels_per_second = prev.pixels_per_second;
217         wlen = prev.wlen;
218         memcpy(wtext, prev.wtext, prev.wlen * sizeof(wchar_t));
219         wtext[wlen] = 0;
220         this->title_x = prev.title_x == next.title_x ? prev.title_x :
221                 prev.title_x * prev_scale + next.title_x * next_scale;
222         this->title_y = prev.title_y == next.title_y ? prev.title_y :
223                 prev.title_y * prev_scale + next.title_y * next_scale;
224         this->title_w = prev.title_w == next.title_w ? prev.title_w :
225                 prev.title_w * prev_scale + next.title_w * next_scale;
226         this->title_h = prev.title_h == next.title_h ? prev.title_h :
227                 prev.title_h * prev_scale + next.title_h * next_scale;
228         window_w = prev.window_w;
229         window_h = prev.window_h;
230         timecode = prev.timecode;
231         this->dropshadow = prev.dropshadow == next.dropshadow ? prev.dropshadow :
232                 prev.dropshadow * prev_scale + next.dropshadow * next_scale;
233         background = prev.background;
234         strcpy(background_path, prev.background_path);
235         timecode_format = prev.timecode_format;
236         drag = prev.drag;
237         loop_playback = prev.loop_playback;
238 }
239
240 void TitleConfig::to_wtext(const char *from_enc, const char *text, int tlen)
241 {
242         wlen = BC_Resources::encode(from_enc, BC_Resources::wide_encoding,
243                 (char*)text,tlen, (char *)wtext,sizeof(wtext)) / sizeof(wchar_t);
244         while( wlen > 0 && !wtext[wlen-1] ) --wlen;
245 }
246
247
248 TitleGlyph::TitleGlyph()
249 {
250         char_code = 0;
251         size = 0;
252         data = 0;
253         data_stroke = 0;
254         freetype_index = 0;
255         width = 0;
256         height = 0;
257         style = 0;
258         pitch = 0;
259         left = 0;
260         top = 0;
261         bottom = 0;
262         right = 0;
263         advance_x = 0;
264 }
265
266
267 TitleGlyph::~TitleGlyph()
268 {
269 //printf("TitleGlyph::~TitleGlyph 1\n");
270         if( data ) delete data;
271         if( data_stroke ) delete data_stroke;
272 }
273
274
275 GlyphPackage::GlyphPackage() : LoadPackage()
276 {
277         glyph = 0;
278 }
279
280 GlyphUnit::GlyphUnit(TitleMain *plugin, GlyphEngine *server)
281  : LoadClient(server)
282 {
283         this->plugin = plugin;
284         freetype_library = 0;
285         freetype_face = 0;
286 }
287
288 GlyphUnit::~GlyphUnit()
289 {
290         if( freetype_library )
291                 FT_Done_FreeType(freetype_library);
292 }
293
294 void GlyphUnit::process_package(LoadPackage *package)
295 {
296         GlyphPackage *pkg = (GlyphPackage*)package;
297         TitleGlyph *glyph = pkg->glyph;
298         int result = 0;
299         char new_path[BCTEXTLEN];
300         if( plugin->load_freetype_face(freetype_library, freetype_face, glyph->font->path) ) {
301                 printf(_("GlyphUnit::process_package FT_New_Face failed, path=%s\n"),
302                         glyph->font->path);
303                 result = 1;
304         }
305
306         if( !result ) {
307                 int gindex = FT_Get_Char_Index(freetype_face, glyph->char_code);
308
309 //printf("GlyphUnit::process_package 1 %c\n", glyph->char_code);
310 // Char not found
311                 if( gindex == 0 ) {
312                         BC_Resources *resources =  BC_WindowBase::get_resources();
313                         // Search replacement font
314                         if( resources->find_font_by_char(glyph->char_code, new_path, freetype_face) ) {
315                                 plugin->load_freetype_face(freetype_library,
316                                         freetype_face, new_path);
317                                 gindex = FT_Get_Char_Index(freetype_face, glyph->char_code);
318                         }
319                 }
320                 FT_Set_Pixel_Sizes(freetype_face, glyph->size, 0);
321
322                 if( gindex == 0 ) {
323 // carrige return
324                         if( glyph->char_code != 10 )
325                                 printf(_("GlyphUnit::process_package FT_Load_Char failed - char: %li.\n"),
326                                         glyph->char_code);
327 // Prevent a crash here
328                         glyph->width = 8;  glyph->height = 8;
329                         glyph->pitch = 8;  glyph->advance_x = 8;
330                         glyph->left = 9;   glyph->top = 9;
331                         glyph->right = 0;  glyph->bottom = 0;
332                         glyph->freetype_index = 0;
333                         glyph->data = new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
334                         glyph->data->clear_frame();
335                         glyph->data_stroke = 0;
336
337 // create outline glyph
338                         if( plugin->config.stroke_width >= SMALL &&
339                                 (plugin->config.style & BC_FONT_OUTLINE) ) {
340                                 glyph->data_stroke = new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
341                                 glyph->data_stroke->clear_frame();
342                         }
343                 }
344 // char found and no outline desired
345                 else if( plugin->config.stroke_width < SMALL ||
346                         !(plugin->config.style & BC_FONT_OUTLINE) ) {
347                         FT_Glyph glyph_image;
348                         FT_BBox bbox;
349                         FT_Bitmap bm;
350                         FT_Load_Glyph(freetype_face, gindex, FT_LOAD_DEFAULT);
351                         FT_Get_Glyph(freetype_face->glyph, &glyph_image);
352                         FT_Outline_Get_BBox(&((FT_OutlineGlyph) glyph_image)->outline, &bbox);
353 //                      printf("Stroke: Xmin: %ld, Xmax: %ld, Ymin: %ld, yMax: %ld\n",
354 //                                      bbox.xMin,bbox.xMax, bbox.yMin, bbox.yMax);
355
356                         glyph->width = bm.width = ((bbox.xMax - bbox.xMin + 63) >> 6);
357                         glyph->height = bm.rows = ((bbox.yMax - bbox.yMin + 63) >> 6);
358                         glyph->pitch = bm.pitch = bm.width;
359                         bm.pixel_mode = FT_PIXEL_MODE_GRAY;
360                         bm.num_grays = 256;
361                         glyph->left = (bbox.xMin + 31) >> 6;
362                         glyph->top = (bbox.yMax + 31) >> 6;
363                         glyph->right = (bbox.xMax + 31) >> 6;
364                         glyph->bottom = (bbox.yMin + 31) >> 6;
365                         glyph->freetype_index = gindex;
366                         glyph->advance_x = ((freetype_face->glyph->advance.x + 31) >> 6);
367 //printf("GlyphUnit::process_package 1 width=%d height=%d pitch=%d left=%d top=%d advance_x=%d freetype_index=%d\n",
368 //glyph->width, glyph->height, glyph->pitch, glyph->left, glyph->top, glyph->advance_x, glyph->freetype_index);
369
370                         glyph->data = new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
371                         glyph->data->clear_frame();
372                         bm.buffer = glyph->data->get_data();
373                         FT_Outline_Translate(&((FT_OutlineGlyph) glyph_image)->outline,
374                                 - bbox.xMin, - bbox.yMin);
375                         FT_Outline_Get_Bitmap( freetype_library,
376                                 &((FT_OutlineGlyph) glyph_image)->outline,
377                                 &bm);
378                         FT_Done_Glyph(glyph_image);
379                 }
380                 else {
381 // Outline desired and glyph found
382                         FT_Glyph glyph_image;
383                         FT_Stroker stroker;
384                         FT_Outline outline;
385                         FT_Bitmap bm;
386                         FT_BBox bbox;
387                         FT_UInt npoints, ncontours;
388
389                         FT_Load_Glyph(freetype_face, gindex, FT_LOAD_DEFAULT);
390                         FT_Get_Glyph(freetype_face->glyph, &glyph_image);
391
392 // check if the outline is ok (non-empty);
393                         FT_Outline_Get_BBox(&((FT_OutlineGlyph) glyph_image)->outline, &bbox);
394                         if( bbox.xMin == 0 && bbox.xMax == 0 &&
395                             bbox.yMin == 0 && bbox.yMax == 0 ) {
396                                 FT_Done_Glyph(glyph_image);
397                                 glyph->width = 0;   glyph->height = 0;
398                                 glyph->left = 0;    glyph->top = 0;
399                                 glyph->right = 0;   glyph->bottom = 0;
400                                 glyph->pitch = 0;
401                                 glyph->data =
402                                         new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
403                                 glyph->data_stroke =
404                                         new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
405                                 glyph->advance_x =((int)(freetype_face->glyph->advance.x +
406                                         plugin->config.stroke_width * 64)) >> 6;
407                                 return;
408                         }
409 #if FREETYPE_MAJOR > 2 || (FREETYPE_MAJOR == 2 && FREETYPE_MINOR >= 2)
410                         FT_Stroker_New(freetype_library, &stroker);
411 #else
412                         FT_Stroker_New(((FT_LibraryRec *)freetype_library)->memory, &stroker);
413 #endif
414                         FT_Stroker_Set(stroker, (int)(plugin->config.stroke_width * 64),
415                                 FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0);
416                         FT_Stroker_ParseOutline(stroker, &((FT_OutlineGlyph) glyph_image)->outline,1);
417                         FT_Stroker_GetCounts(stroker,&npoints, &ncontours);
418                         if( npoints == 0 && ncontours == 0 ) {
419 // this never happens, but FreeType has a bug regarding Linotype's Palatino font
420                                 FT_Stroker_Done(stroker);
421                                 FT_Done_Glyph(glyph_image);
422                                 glyph->width = 0;   glyph->height = 0;
423                                 glyph->left = 0;    glyph->top = 0;
424                                 glyph->right = 0;   glyph->bottom = 0;
425                                 glyph->pitch = 0;
426                                 glyph->data =
427                                         new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
428                                 glyph->data_stroke =
429                                         new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
430                                 glyph->advance_x =((int)(freetype_face->glyph->advance.x +
431                                         plugin->config.stroke_width * 64)) >> 6;
432                                 return;
433                         };
434
435                         FT_Outline_New(freetype_library, npoints, ncontours, &outline);
436                         outline.n_points=0;
437                         outline.n_contours=0;
438                         FT_Stroker_Export (stroker, &outline);
439                         FT_Outline_Get_BBox(&outline, &bbox);
440                         FT_Outline_Translate(&outline, - bbox.xMin, - bbox.yMin);
441                         FT_Outline_Translate(&((FT_OutlineGlyph) glyph_image)->outline,
442                                         - bbox.xMin,
443                                         - bbox.yMin + (int)(plugin->config.stroke_width*32));
444 //                      printf("Stroke: Xmin: %ld, Xmax: %ld, Ymin: %ld, yMax: %ld\n"
445 //                                      "Fill   Xmin: %ld, Xmax: %ld, Ymin: %ld, yMax: %ld\n",
446 //                                      bbox.xMin,bbox.xMax, bbox.yMin, bbox.yMax,
447 //                                      bbox_fill.xMin,bbox_fill.xMax, bbox_fill.yMin, bbox_fill.yMax);
448
449                         glyph->width = bm.width = ((bbox.xMax - bbox.xMin) >> 6)+1;
450                         glyph->height = bm.rows = ((bbox.yMax - bbox.yMin) >> 6) +1;
451                         glyph->pitch = bm.pitch = bm.width;
452                         bm.pixel_mode = FT_PIXEL_MODE_GRAY;
453                         bm.num_grays = 256;
454                         glyph->left = (bbox.xMin + 31) >> 6;
455                         glyph->top = (bbox.yMax + 31) >> 6;
456                         glyph->right = (bbox.xMax + 31) >> 6;
457                         glyph->bottom = (bbox.yMin + 31) >> 6;
458                         glyph->freetype_index = gindex;
459                         int real_advance = ((int)ceil((float)freetype_face->glyph->advance.x +
460                                 plugin->config.stroke_width * 64) >> 6);
461                         glyph->advance_x = glyph->width + glyph->left;
462                         if( real_advance > glyph->advance_x )
463                                 glyph->advance_x = real_advance;
464 //printf("GlyphUnit::process_package 1 width=%d height=%d "
465 // "pitch=%d left=%d top=%d advance_x=%d freetype_index=%d\n",
466 // glyph->width, glyph->height, glyph->pitch, glyph->left,
467 // glyph->top, glyph->advance_x, glyph->freetype_index);
468
469
470 //printf("GlyphUnit::process_package 1\n");
471                         glyph->data = new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
472                         glyph->data->clear_frame();
473                         glyph->data_stroke = new VFrame(glyph->width, glyph->height, BC_A8, glyph->pitch);
474                         glyph->data_stroke->clear_frame();
475 // for debugging        memset( glyph->data_stroke->get_data(), 60, glyph->pitch * glyph->height);
476                         bm.buffer=glyph->data->get_data();
477                         FT_Outline_Get_Bitmap( freetype_library,
478                                 &((FT_OutlineGlyph) glyph_image)->outline,
479                                 &bm);
480                         bm.buffer=glyph->data_stroke->get_data();
481                         FT_Outline_Get_Bitmap( freetype_library,
482                         &outline,
483                                 &bm);
484                         FT_Outline_Done(freetype_library,&outline);
485                         FT_Stroker_Done(stroker);
486                         FT_Done_Glyph(glyph_image);
487
488 //printf("GlyphUnit::process_package 2\n");
489                 }
490         }
491 }
492
493
494 GlyphEngine::GlyphEngine(TitleMain *plugin, int cpus)
495  : LoadServer(cpus, cpus)
496 {
497         this->plugin = plugin;
498 }
499
500 void GlyphEngine::init_packages()
501 {
502         int current_package = 0;
503         for( int i=0; i<plugin->title_glyphs.count(); ++i ) {
504                 if( !plugin->title_glyphs[i]->data ) {
505                         GlyphPackage *pkg = (GlyphPackage*)get_package(current_package++);
506                         pkg->glyph = plugin->title_glyphs[i];
507                 }
508         }
509 }
510
511 LoadClient* GlyphEngine::new_client()
512 {
513         return new GlyphUnit(plugin, this);
514 }
515
516 LoadPackage* GlyphEngine::new_package()
517 {
518         return new GlyphPackage;
519 }
520
521
522 // Copy a single character to the text mask
523 TitlePackage::TitlePackage()
524  : LoadPackage()
525 {
526         x = y = 0;
527         chr = 0;
528 }
529
530
531 TitleUnit::TitleUnit(TitleMain *plugin, TitleEngine *server)
532  : LoadClient(server)
533 {
534         this->plugin = plugin;
535         this->engine = server;
536         this->chr = 0;
537 }
538
539 static void get_mask_colors(int rgb, int color_model, int &rr, int &gg, int &bb)
540 {
541         int r = 0xff & (rgb>>16), g = 0xff & (rgb>>8), b = 0xff & (rgb>>0);
542         if( BC_CModels::is_yuv(color_model) ) bc_rgb2yuv(r,g,b, r,g,b);
543         rr = r;  gg = g; bb = b;
544 }
545
546 void TitleUnit::draw_frame(int mode, VFrame *dst, VFrame *src, int x, int y)
547 {
548         int inp_w = src->get_w(), inp_h = src->get_h();
549         int out_w = dst->get_w(), out_h = dst->get_h();
550         unsigned char **inp_rows = src->get_rows();
551         unsigned char **out_rows = dst->get_rows();
552
553         int x_inp = 0, y_inp = 0;
554         int x_out = x;
555         if( x_out < 0 ) { x_inp = -x_out;  x_out = 0; }
556         if( x_out+inp_w > out_w ) inp_w = out_w-x_out;
557         if( x_inp >= inp_w || x_out >= out_w ) return;
558         int y_out = y;
559         if( y_out < 0 ) { y_inp = -y_out;  y_out = 0; }
560         if( y_out+inp_h > out_h ) inp_h = out_h-y_out;
561         if( y_inp >= inp_h || y_out >= out_h ) return;
562         int color = chr->color, max = 0xff;
563         int alpha = chr->alpha * chr->fade;
564         int ofs = BC_CModels::is_yuv(dst->get_color_model()) ? 0x80 : 0x00;
565
566         switch( mode ) {
567         case DRAW_ALPHA: {
568                 while( y_inp < inp_h && y_out < out_h ) {
569                         uint8_t *inp = inp_rows[y_inp], *out = out_rows[y_out];
570                         for( int xin=x_inp,xout=x_out*4+3; xin<inp_w; ++xin,xout+=4 ) {
571                                 out[xout] = inp[xin];
572                         }
573                         ++y_inp;  ++y_out;
574                 }
575                 break; }
576         case DRAW_COLOR: {
577                 int r = 0, g = 0, b = 0;
578                 get_mask_colors(color, plugin->text_model, r, g, b);
579                 while( y_inp < inp_h && y_out < out_h ) {
580                         uint8_t *inp = inp_rows[y_inp], *out = out_rows[y_out];
581                         for( int xin=x_inp,xout=x_out*4+0; xin<inp_w; ++xin,xout+=4 ) {
582                                 int in_a = inp[xin], out_a = out[xout+3];
583                                 if( in_a + out_a == 0 ) continue;
584                                 int opacity = (in_a * alpha)/max, transp = out_a * (max - opacity)/max;
585                                 out[xout+0] = (opacity * r + transp * out[xout+0]) / max;
586                                 out[xout+1] = (opacity * (g-ofs) + transp * (out[xout+1]-ofs)) / max + ofs;
587                                 out[xout+2] = (opacity * (b-ofs) + transp * (out[xout+2]-ofs)) / max + ofs;
588                                 out[xout+3] = opacity + transp - (opacity * transp) / max;
589                         }
590                         ++y_inp;  ++y_out;
591                 }
592                 break; }
593         case DRAW_IMAGE: {
594                 while( y_inp < inp_h && y_out < out_h ) {
595                         uint8_t *inp = inp_rows[y_inp], *out = out_rows[y_out];
596                         for( int xin=x_inp,xout=x_out*4+0; xin<inp_w; ++xin,xout+=4 ) {
597                                 int xinp = xin*4, in_a = inp[xinp+3], out_a = out[xout+3];
598                                 if( in_a + out_a == 0 ) continue;
599                                 int opacity = (in_a * alpha)/max, transp = out_a * (max - opacity)/max;
600                                 out[xout+0] = (opacity * inp[xinp+0] + transp * out[xout+0]) / max;
601                                 out[xout+1] = (opacity * (inp[xinp+1]-ofs) + transp * (out[xout+1]-ofs)) / max + ofs;
602                                 out[xout+2] = (opacity * (inp[xinp+2]-ofs) + transp * (out[xout+2]-ofs)) / max + ofs;
603                                 out[xout+3] = opacity + transp - (opacity * transp) / max;
604                         }
605                         ++y_inp;  ++y_out;
606                 }
607                 break; }
608         }
609 }
610
611
612 void TitleUnit::process_package(LoadPackage *package)
613 {
614         TitlePackage *pkg = (TitlePackage*)package;
615         int x = pkg->x, y = pkg->y;
616         chr = pkg->chr;
617         switch( chr->typ ) {
618         case CHAR_IMAGE: {
619                 VFrame *vframe = (VFrame *)chr->vp;
620                 if( !vframe ) return;
621                 draw_frame(DRAW_IMAGE, plugin->text_mask, vframe, x, y);
622                 break; }
623         case CHAR_GLYPH: {
624                 if( chr->wch == 0 || chr->wch == '\n') return;
625                 TitleGlyph *glyph = (TitleGlyph *)chr->vp;
626                 if( !glyph ) return;
627                 if( engine->do_dropshadow ) {
628                         x += plugin->config.dropshadow;
629                         y += plugin->config.dropshadow;
630                 }
631                 else if( plugin->config.dropshadow < 0 ) {
632                         x -= plugin->config.dropshadow;
633                         y -= plugin->config.dropshadow;
634                 }
635                 int mode = engine->do_dropshadow ? DRAW_ALPHA : DRAW_COLOR;
636                 draw_frame(mode, plugin->text_mask, glyph->data, x, y);
637                 if( plugin->config.stroke_width >= SMALL && (plugin->config.style & BC_FONT_OUTLINE) )
638                         draw_frame(mode, plugin->stroke_mask, glyph->data_stroke, x, y);
639                 break; }
640         }
641 }
642
643 TitleEngine::TitleEngine(TitleMain *plugin, int cpus)
644  : LoadServer(cpus, cpus)
645 {
646         this->plugin = plugin;
647 }
648
649 void TitleEngine::init_packages()
650 {
651         int current_package = 0;
652         for( int i=plugin->visible_char1; i<plugin->visible_char2; ++i ) {
653                 TitlePackage *pkg = (TitlePackage*)get_package(current_package++);
654                 TitleChar *chr = plugin->title_chars[i];
655                 TitleRow *row = plugin->title_rows[chr->row];
656                 pkg->chr = chr;
657                 pkg->x = row->x0 + chr->x - plugin->mask_x1;
658                 pkg->y = row->y0 - chr->y - plugin->mask_y1;
659 //printf("draw '%c' at %d,%d\n",(int)pkg->chr->wch, pkg->x, pkg->y);
660         }
661 }
662
663 LoadClient* TitleEngine::new_client()
664 {
665         return new TitleUnit(plugin, this);
666 }
667
668 LoadPackage* TitleEngine::new_package()
669 {
670         return new TitlePackage;
671 }
672
673 void TitleTranslateUnit::translation_array_f(transfer_table_f* &table,
674         float in_x1, float in_x2, int in_total,
675         float out_x1, float out_x2, int out_total,
676         int &x1_out, int &x2_out)
677 {
678         int out_w;
679         //float offset = out_x1 - in_x1;
680
681         x1_out = (int)out_x1;
682         x2_out = MIN((int)ceil(out_x2), out_total);
683         if( x1_out >= x2_out ) return;
684
685         out_w = x2_out - x1_out;
686         table = new transfer_table_f[out_w];
687         bzero(table, sizeof(transfer_table_f) * out_w);
688
689         float in_x = in_x1;
690         for( int out_x=x1_out; out_x<x2_out; ++out_x ) {
691                 transfer_table_f *entry = &table[out_x - x1_out];
692
693                 entry->in_x1 = (int)in_x;
694                 entry->in_x2 = (int)in_x + 1;
695
696 // Get fraction of output pixel to fill
697                 entry->output_fraction = 1;
698
699                 if( out_x1 > out_x ) {
700                         entry->output_fraction -= out_x1 - out_x;
701                 }
702
703                 if( out_x2 < out_x + 1 ) {
704                         entry->output_fraction = (out_x2 - out_x);
705                 }
706
707 // Advance in_x until out_x_fraction is filled
708                 float out_x_fraction = entry->output_fraction;
709                 float in_x_fraction = floor(in_x + 1) - in_x;
710
711                 if( out_x_fraction <= in_x_fraction ) {
712                         entry->in_fraction1 = out_x_fraction;
713                         entry->in_fraction2 = 0.0;
714                         in_x += out_x_fraction;
715                 }
716                 else {
717                         entry->in_fraction1 = in_x_fraction;
718                         in_x += out_x_fraction;
719                         entry->in_fraction2 = in_x - floor(in_x);
720                 }
721
722 // Clip in_x and zero out fraction.  This doesn't work for YUV.
723                 if( entry->in_x2 >= in_total ) {
724                         entry->in_x2 = in_total - 1;
725                         entry->in_fraction2 = 0.0;
726                 }
727
728                 if( entry->in_x1 >= in_total ) {
729                         entry->in_x1 = in_total - 1;
730                         entry->in_fraction1 = 0.0;
731                 }
732         }
733 }
734
735
736
737 // Copy a single character to the text mask
738 TitleOutlinePackage::TitleOutlinePackage()
739  : LoadPackage()
740 {
741 }
742
743
744 TitleOutlineUnit::TitleOutlineUnit(TitleMain *plugin, TitleOutlineEngine *server)
745  : LoadClient(server)
746 {
747         this->plugin = plugin;
748         this->engine = server;
749 }
750
751 void TitleOutlineUnit::process_package(LoadPackage *package)
752 {
753         TitleOutlinePackage *pkg = (TitleOutlinePackage*)package;
754         int r = 0, g = 0, b = 0, outline_a = plugin->config.outline_alpha;
755         get_mask_colors(plugin->config.outline_color, plugin->mask_model, r, g, b);
756
757         unsigned char **outline_rows = plugin->outline_mask->get_rows();
758         unsigned char **text_rows = plugin->text_mask->get_rows();
759         int mask_w1 = plugin->text_mask->get_w()-1;
760         int mask_h1 = plugin->text_mask->get_h()-1;
761         int ofs = plugin->config.outline_size;
762
763         if( engine->pass == 0 ) {
764 // get max alpha under outline size macropixel
765                 for( int y=pkg->y1, my=pkg->y2; y<my; ++y ) {
766                         unsigned char *out_row = outline_rows[y];
767                         int y1 = y - ofs, y2 = y + ofs;
768                         CLAMP(y1, 0, mask_h1);  CLAMP(y2, 0, mask_h1);
769                         for( int x=0, mx=plugin->text_mask->get_w(); x<mx; ++x ) {
770                                 int x1 = x - ofs, x2 = x + ofs;
771                                 CLAMP(x1, 0, mask_w1);  CLAMP(x2, 0, mask_w1);
772                                 int max_a = 0;
773                                 for( int yy=y1; yy<=y2; ++yy ) {
774                                         unsigned char *text_row = text_rows[yy];
775                                         for( int xx = x1; xx <= x2; ++xx ) {
776                                                 unsigned char *pixel = text_row + xx*4;
777                                                 if( pixel[3] > max_a ) max_a = pixel[3];
778                                         }
779                                 }
780                                 unsigned char *out = out_row + x*4;
781                                 out[0] = r;  out[1] = g;  out[2] = b;
782                                 out[3] = (max_a * outline_a) / 0xff;
783                         }
784                 }
785                 return;
786         }
787         else {
788 // Overlay text mask on top of outline mask
789                 int ofs = BC_CModels::is_yuv(plugin->output->get_color_model()) ? 0x80 : 0;
790                 for( int y=pkg->y1, my=pkg->y2; y<my; ++y ) {
791                         unsigned char *outline_row = outline_rows[y];
792                         unsigned char *text_row = text_rows[y];
793                         for( int x=0, mx=plugin->text_mask->get_w(); x<mx; ++x ) {
794                                 unsigned char *out = text_row + x * 4;
795                                 unsigned char *inp = outline_row + x * 4;
796                                 int out_a = out[3], in_a = inp[3];
797                                 int transparency = in_a * (0xff - out_a) / 0xff;
798                                 out[0] = (out[0] * out_a + inp[0] * transparency) / 0xff;
799                                 out[1] = ((out[1]-ofs) * out_a + (inp[1]-ofs) * transparency) / 0xff + ofs;
800                                 out[2] = ((out[2]-ofs) * out_a + (inp[2]-ofs) * transparency) / 0xff + ofs;
801                                 out[3] = in_a + out_a - in_a*out_a / 0xff;
802                         }
803                 }
804         }
805 }
806
807 TitleOutlineEngine::TitleOutlineEngine(TitleMain *plugin, int cpus)
808  : LoadServer(cpus, cpus)
809 {
810         this->plugin = plugin;
811 }
812
813 void TitleOutlineEngine::init_packages()
814 {
815         int mask_h = plugin->text_mask->get_h();
816         if( !mask_h ) return;
817         int py1 = 0, py2 = 0;
818         int pkgs = get_total_packages();
819         for( int i=0; i<pkgs; py1=py2 ) {
820                 TitleOutlinePackage *pkg = (TitleOutlinePackage*)get_package(i);
821                 py2 = (++i * mask_h)/ pkgs;
822                 pkg->y1 = py1;  pkg->y2 = py2;
823         }
824 }
825
826 void TitleOutlineEngine::do_outline()
827 {
828         pass = 0;  process_packages();
829         pass = 1;  process_packages();
830 }
831
832 LoadClient* TitleOutlineEngine::new_client()
833 {
834         return new TitleOutlineUnit(plugin, this);
835 }
836
837 LoadPackage* TitleOutlineEngine::new_package()
838 {
839         return new TitleOutlinePackage;
840 }
841
842
843
844 TitleTranslatePackage::TitleTranslatePackage()
845  : LoadPackage()
846 {
847         y1 = y2 = 0;
848 }
849
850
851 TitleTranslateUnit::TitleTranslateUnit(TitleMain *plugin, TitleTranslate *server)
852  : LoadClient(server)
853 {
854         this->plugin = plugin;
855 }
856
857 void TitleTranslate::run_packages()
858 {
859 // Generate scaling tables
860         delete [] x_table;  x_table = 0;
861         delete [] y_table;  y_table = 0;
862
863         float in_w = xlat_mask->get_w();
864         float in_h = xlat_mask->get_h();
865         float ix1 = 0, ix2 = ix1 + in_w;
866         float iy1 = 0, iy2 = iy1 + in_h;
867
868         float out_w = plugin->output->get_w();
869         float out_h = plugin->output->get_h();
870         float x1 = plugin->title_x, x2 = x1 + plugin->title_w;
871         float y1 = plugin->title_y, y2 = y1 + plugin->title_h;
872         bclamp(x1, 0, out_w);  bclamp(y1, 0, out_h);
873         bclamp(x2, 0, out_w);  bclamp(y2, 0, out_h);
874
875         float ox1 = plugin->title_x + plugin->text_x - plugin->text_x1 + plugin->mask_x1, ox2 = ox1 + in_w;
876         float oy1 = plugin->title_y + plugin->text_y - plugin->text_y1 + plugin->mask_y1, oy2 = oy1 + in_h;
877         if( ox1 < x1 ) { ix1 -= (ox1-x1);  ox1 = x1; }
878         if( oy1 < y1 ) { iy1 -= (oy1-y1);  oy1 = y1; }
879         if( ox2 > x2 ) { ix2 -= (ox2-x2);  ox2 = x2; }
880         if( oy2 > y2 ) { iy2 -= (oy2-x2);  oy2 = y2; }
881 #if 0
882 printf("TitleTranslate text  txy=%7.2f,%-7.2f\n"
883   "  mxy1=%7d,%-7d mxy2=%7d,%-7d\n"
884   "   xy1=%7.2f,%-7.2f  xy2=%7.2f,%-7.2f\n"
885   "  ixy1=%7.2f,%-7.2f ixy2=%7.2f,%-7.2f\n"
886   "  oxy1=%7.2f,%-7.2f oxy2=%7.2f,%-7.2f\n",
887    plugin->text_x, plugin->text_y,
888    plugin->mask_x1, plugin->mask_y1, plugin->mask_x2, plugin->mask_y2,
889    x1,y1, x2,y2, ix1,iy1, ix2,iy2, ox1,oy1, ox2,oy2);
890 #endif
891         out_x1 = out_x2 = out_y1 = out_y2 = 0;
892         TitleTranslateUnit::translation_array_f(x_table,
893                 ix1, ix2, in_w, ox1, ox2, out_w, out_x1, out_x2);
894         TitleTranslateUnit::translation_array_f(y_table,
895                 iy1, iy2, in_h, oy1, oy2, out_h, out_y1, out_y2);
896
897         process_packages();
898 }
899
900
901
902 #define TRANSLATE(type, max, components, ofs) { \
903         unsigned char **in_rows = server->xlat_mask->get_rows(); \
904         type **out_rows = (type**)plugin->output->get_rows(); \
905  \
906         for( int y=pkg->y1; y<pkg->y2; ++y ) { \
907                 int in_y1 = server->y_table[y].in_x1; \
908                 int in_y2 = server->y_table[y].in_x2; \
909                 float y_f1 = server->y_table[y].in_fraction1; \
910                 float y_f2 = server->y_table[y].in_fraction2; \
911                 unsigned char *in_row1 = in_rows[in_y1]; \
912                 unsigned char *in_row2 = in_rows[in_y2]; \
913                 type *out_row = out_rows[y + server->out_y1]; \
914                 for( int i=0,x=server->out_x1; x<server->out_x2; ++i,++x ) { \
915                         int in_x1 = 4*server->x_table[i].in_x1; \
916                         int in_x2 = 4*server->x_table[i].in_x2; \
917                         float x_f1 = server->x_table[i].in_fraction1; \
918                         float x_f2 = server->x_table[i].in_fraction2; \
919                         float f11 = x_f1 * y_f1 / (256.f-max); \
920                         float f12 = x_f2 * y_f1 / (256.f-max); \
921                         float f21 = x_f1 * y_f2 / (256.f-max); \
922                         float f22 = x_f2 * y_f2 / (256.f-max); \
923                         type input_r = (type)( \
924                                 in_row1[in_x1 + 0] * f11 + in_row1[in_x2 + 0] * f12 +  \
925                                 in_row2[in_x1 + 0] * f21 + in_row2[in_x2 + 0] * f22 ); \
926                         type input_g = (type)( \
927                                 in_row1[in_x1 + 1] * f11 + in_row1[in_x2 + 1] * f12 +  \
928                                 in_row2[in_x1 + 1] * f21 + in_row2[in_x2 + 1] * f22 ); \
929                         type input_b = (type)( \
930                                 in_row1[in_x1 + 2] * f11 + in_row1[in_x2 + 2] * f12 +  \
931                                 in_row2[in_x1 + 2] * f21 + in_row2[in_x2 + 2] * f22 ); \
932                         type input_a = (type)( \
933                                 in_row1[in_x1 + 3] * f11 + in_row1[in_x2 + 3] * f12 +  \
934                                 in_row2[in_x1 + 3] * f21 + in_row2[in_x2 + 3] * f22 ); \
935                         input_a = input_a * plugin->fade; \
936                         if( components == 4 ) { \
937                                 type transparency = out_row[x * components + 3] * (max - input_a) / max; \
938                                 out_row[x * components + 0] =  (input_r * input_a + \
939                                         out_row[x * components + 0] * transparency) / max; \
940                                 out_row[x * components + 1] =  ((input_g-ofs) * input_a + \
941                                         (out_row[x * components + 1]-ofs) * transparency) / max + ofs; \
942                                 out_row[x * components + 2] =  ((input_b-ofs) * input_a + \
943                                         (out_row[x * components + 2]-ofs) * transparency) / max + ofs; \
944                                 out_row[x * components + 3] =  MAX(input_a, out_row[x * components + 3]); \
945                         } \
946                         else { \
947                                 type transparency = max - input_a; \
948                                 out_row[x * components + 0] = (input_r * input_a + \
949                                         out_row[x * components + 0] * transparency) / max; \
950                                 out_row[x * components + 1] =  ((input_g-ofs) * input_a + \
951                                         (out_row[x * components + 1]-ofs) * transparency) / max + ofs; \
952                                 out_row[x * components + 2] =  ((input_b-ofs) * input_a + \
953                                         (out_row[x * components + 2]-ofs) * transparency) / max + ofs; \
954                         } \
955                 } \
956         } \
957 }
958
959
960 void TitleTranslateUnit::process_package(LoadPackage *package)
961 {
962         TitleTranslatePackage *pkg = (TitleTranslatePackage*)package;
963         TitleTranslate *server = (TitleTranslate*)this->server;
964
965         switch( plugin->output->get_color_model() ) {
966         case BC_RGB888:     TRANSLATE(unsigned char, 0xff, 3, 0);    break;
967         case BC_RGB_FLOAT:  TRANSLATE(float, 1.0, 3, 0);             break;
968         case BC_YUV888:     TRANSLATE(unsigned char, 0xff, 3, 0x80); break;
969         case BC_RGBA_FLOAT: TRANSLATE(float, 1.0, 4, 0);             break;
970         case BC_RGBA8888:   TRANSLATE(unsigned char, 0xff, 4, 0);    break;
971         case BC_YUVA8888:   TRANSLATE(unsigned char, 0xff, 4, 0x80); break;
972         }
973 //printf("TitleTranslateUnit::process_package 5\n");
974 }
975
976
977 TitleTranslate::TitleTranslate(TitleMain *plugin, int cpus)
978  : LoadServer(cpus, cpus)
979 {
980         this->plugin = plugin;
981         x_table = 0;
982         y_table = 0;
983         out_x1 = out_x2 = 0;
984         out_y1 = out_y2 = 0;
985 }
986
987 TitleTranslate::~TitleTranslate()
988 {
989         delete [] x_table;
990         delete [] y_table;
991 }
992
993 void TitleTranslate::init_packages()
994 {
995         int out_h = out_y2 - out_y1;
996         int py1 = 0, py2 = 0;
997         int pkgs = get_total_packages();
998         for( int i=0; i<pkgs; py1=py2 ) {
999                 TitleTranslatePackage *pkg = (TitleTranslatePackage*)get_package(i);
1000                 py2 = (++i*out_h) / pkgs;
1001                 pkg->y1 = py1;  pkg->y2 = py2;
1002         }
1003 //printf("TitleTranslate::init_packages 2\n");
1004 }
1005
1006 LoadClient* TitleTranslate::new_client()
1007 {
1008         return new TitleTranslateUnit(plugin, this);
1009 }
1010
1011 LoadPackage* TitleTranslate::new_package()
1012 {
1013         return new TitleTranslatePackage;
1014 }
1015
1016 TitleCurNudge::TitleCurNudge(TitleParser *parser, TitleMain *plugin)
1017  : TitleStack<int>(parser, 0)
1018 {
1019 }
1020 TitleCurColor::TitleCurColor(TitleParser *parser, TitleMain *plugin)
1021  : TitleStack<int>(parser, plugin->config.color)
1022 {
1023 }
1024 TitleCurAlpha::TitleCurAlpha(TitleParser *parser, TitleMain *plugin)
1025  : TitleStack<int>(parser, plugin->config.alpha)
1026 {
1027 }
1028 TitleCurSize::TitleCurSize(TitleParser *parser, TitleMain *plugin)
1029  : TitleStack<float>(parser, plugin->config.size)
1030 {
1031 }
1032 TitleCurBold::TitleCurBold(TitleParser *parser, TitleMain *plugin)
1033  : TitleStack<int>(parser, (plugin->config.style & BC_FONT_BOLD) ? 1 : 0)
1034 {
1035 }
1036 TitleCurItalic::TitleCurItalic(TitleParser *parser, TitleMain *plugin)
1037  : TitleStack<int>(parser, (plugin->config.style & BC_FONT_ITALIC) ? 1 : 0)
1038 {
1039 }
1040 TitleCurFont::TitleCurFont(TitleParser *parser, TitleMain *plugin)
1041  : TitleStack<BC_FontEntry*>(parser, plugin->config_font())
1042 {
1043 }
1044 TitleCurCaps::TitleCurCaps(TitleParser *parser, TitleMain *plugin)
1045  : TitleStack<int>(parser, 0)
1046 {
1047 }
1048 TitleCurUnder::TitleCurUnder(TitleParser *parser, TitleMain *plugin)
1049  : TitleStack<int>(parser, 0)
1050 {
1051 }
1052 TitleCurBlink::TitleCurBlink(TitleParser *parser, TitleMain *plugin)
1053  : TitleStack<float>(parser, 0)
1054 {
1055 }
1056 TitleCurFixed::TitleCurFixed(TitleParser *parser, TitleMain *plugin)
1057  : TitleStack<int>(parser, 0)
1058 {
1059 }
1060 TitleCurSuper::TitleCurSuper(TitleParser *parser, TitleMain *plugin)
1061  : TitleStack<int>(parser, 0)
1062 {
1063 }
1064
1065 TitleParser::TitleParser(TitleMain *plugin)
1066  : plugin(plugin),
1067    cur_nudge(this, plugin),
1068    cur_color(this, plugin),
1069    cur_alpha(this, plugin),
1070    cur_size(this, plugin),
1071    cur_bold(this, plugin),
1072    cur_italic(this, plugin),
1073    cur_font(this, plugin),
1074    cur_caps(this, plugin),
1075    cur_under(this, plugin),
1076    cur_blink(this, plugin),
1077    cur_fixed(this, plugin),
1078    cur_super(this, plugin)
1079 {
1080         bfr = out = plugin->config.wtext;
1081         lmt = bfr + plugin->config.wlen;
1082 }
1083
1084 TitleMain::TitleMain(PluginServer *server)
1085  : PluginVClient(server)
1086 {
1087         text_mask = 0;
1088         stroke_mask = 0;
1089         outline_mask = 0;
1090         glyph_engine = 0;
1091         title_engine = 0;
1092         translate = 0;
1093         outline_engine = 0;
1094         freetype_library = 0;
1095         freetype_face = 0;
1096         text_font[0] = 0;
1097         window_w = window_h = 0;
1098         title_x = title_y = 0;
1099         title_w = title_h = 0;
1100         text_w = text_h = 0;
1101         text_x = text_y = 0;  mask_w = mask_h = 0;
1102         mask_x1 = mask_y1 = mask_x2 = mask_y2 = 0;
1103         text_rows = 0;
1104         visible_row1 = visible_char1 = 0;
1105         visible_row2 = visible_char2 = 0;
1106         fade = 1;
1107         input = 0; output = 0;
1108         output_model = BC_RGBA8888;
1109         mask_model = BC_RGBA8888;
1110         background = 0; bg_file = 0; bg_frame = 0;
1111         render_engine = 0;  video_cache = 0;
1112         overlay_frame = 0;
1113         cpus = PluginClient::smp + 1;
1114         if( cpus > 8 ) cpus = 8;
1115         last_position = -1;
1116         need_reconfigure = 1;
1117 }
1118
1119 TitleMain::~TitleMain()
1120 {
1121         if( background ) {
1122                 background->Garbage::remove_user();
1123                 background = 0;
1124         }
1125         delete render_engine;
1126         delete video_cache;
1127         delete overlay_frame;
1128         delete bg_file;
1129         delete bg_frame;
1130         delete text_mask;
1131         delete outline_mask;
1132         delete stroke_mask;
1133         delete glyph_engine;
1134         delete title_engine;
1135         if( freetype_face )
1136                 FT_Done_Face(freetype_face);
1137         if( freetype_library )
1138                 FT_Done_FreeType(freetype_library);
1139         delete translate;
1140         delete outline_engine;
1141 }
1142
1143 const char* TitleMain::plugin_title() { return _("Title"); }
1144 int TitleMain::is_realtime() { return 1; }
1145 int TitleMain::is_synthesis() { return 1; }
1146
1147 NEW_WINDOW_MACRO(TitleMain, TitleWindow);
1148
1149
1150 void TitleMain::build_previews(TitleWindow *gui)
1151 {
1152         ArrayList<BC_FontEntry*>&fonts = *gui->get_resources()->fontlist;
1153
1154         for( int font_number=0; font_number<fonts.size(); ++font_number ) {
1155                 BC_FontEntry *font = fonts.get(font_number);
1156 // already have examples
1157                 if( font->image ) return;
1158         }
1159
1160 // create example bitmaps
1161         FT_Library freetype_library = 0;        // Freetype library
1162         FT_Face freetype_face = 0;
1163         const char *test_string = "Aa";
1164         char new_path[BCTEXTLEN];
1165         int text_height = gui->get_text_height(LARGEFONT);
1166         int max_height = 3*text_height/2, max_width = 2 * max_height;
1167         int text_color = BC_WindowBase::get_resources()->default_text_color;
1168         int r = (text_color >> 16) & 0xff;
1169         int g = (text_color >> 8) & 0xff;
1170         int b = text_color & 0xff;
1171 // dimensions for each line
1172         int height[fonts.size()];
1173         int ascent[fonts.size()];
1174
1175 // pass 1 gets the extents for all the fonts
1176 // pass 2 draws the image
1177         int total_w = 0;
1178         int total_h = 0;
1179         for( int pass=0; pass<2; ++pass ) {
1180 //printf("TitleMain::build_previews %d %d %d\n",
1181 //__LINE__, text_height, total_h);
1182                 for( int font_number=0; font_number<fonts.size(); ++font_number ) {
1183                         BC_FontEntry *font = fonts[font_number];
1184 // test if font of same name has been processed
1185                         int skip = 0;
1186                         for( int i=0; i<font_number; ++i ) {
1187                                 if( !strcasecmp(fonts[i]->displayname, font->displayname) ) {
1188                                         if( pass == 1 ) {
1189                                                 font->image = fonts[i]->image;
1190                                         }
1191                                         skip = 1;
1192                                         break;
1193                                 }
1194                         }
1195
1196                         if( skip ) continue;
1197                         if( pass > 0 ) {
1198                                 font->image = new VFrame;
1199                                 font->image->set_use_shm(0);
1200                                 font->image->reallocate(0, -1, 0, 0, 0,
1201                                         total_w, total_h, BC_RGBA8888, -1);
1202                                 font->image->clear_frame();
1203                         }
1204
1205                         int current_w = 1, current_h = 1;
1206                         int current_x = 0, current_ascent = 0;
1207                         int len = strlen(test_string);
1208
1209                         for( int j=0; j<len; ++j ) {
1210                                 FT_ULong c = test_string[j];
1211 // memory leaks here are fatal
1212 //                              check_char_code_path(freetype_library,
1213 //                                      font->path,
1214 //                                      c,
1215 //                                      (char *)new_path);
1216                                 strcpy(new_path, font->path);
1217                                 if( load_freetype_face(freetype_library, freetype_face, new_path)) continue;
1218                                 FT_Set_Pixel_Sizes(freetype_face, text_height, 0);
1219                                 if( FT_Load_Char(freetype_face, c, FT_LOAD_RENDER) ) continue;
1220                                 int glyph_w = freetype_face->glyph->bitmap.width;
1221                                 int glyph_h = freetype_face->glyph->bitmap.rows;
1222                                 if( glyph_h > max_height ) glyph_h = max_height;
1223                                 int glyph_a = freetype_face->glyph->advance.x >> 6;
1224                                 int glyph_t = freetype_face->glyph->bitmap_top;
1225                                 if( pass == 0 ) {
1226                                         current_w = current_x + glyph_w;
1227                                         if( current_w > max_width ) current_w = max_width;
1228                                         if( total_w < current_w ) total_w = current_w;
1229                                         if( current_ascent < glyph_t ) current_ascent = glyph_t;
1230                                         if( current_h < glyph_h ) current_h = glyph_h;
1231                                         if( total_h < glyph_h ) total_h = glyph_h;
1232                                 }
1233                                 else {
1234 // copy 1 row at a time, center vertically
1235                                         int out_y = (total_h-height[font_number])/2 + ascent[font_number]-glyph_t;
1236                                         if( out_y < 0 ) out_y = 0;
1237                                         for( int in_y = 0; in_y < glyph_h && out_y < total_h; ++in_y, ++out_y ) {
1238                                                 unsigned char *in_row = freetype_face->glyph->bitmap.buffer +
1239                                                         freetype_face->glyph->bitmap.pitch * in_y;
1240                                                 int out_x = current_x;
1241                                                 unsigned char *out_row = font->image->get_rows()[out_y] +
1242                                                         out_x * 4;
1243
1244                                                 for( int in_x = 0; in_x < glyph_w && out_x < total_w; ++in_x, ++out_x ) {
1245                                                         *out_row = (*in_row * r +
1246                                                                 (0xff - *in_row) * *out_row) / 0xff; ++out_row;
1247                                                         *out_row = (*in_row * g +
1248                                                                 (0xff - *in_row) * *out_row) / 0xff; ++out_row;
1249                                                         *out_row = (*in_row * b +
1250                                                                 (0xff - *in_row) * *out_row) / 0xff; ++out_row;
1251                                                         *out_row = MAX(*in_row, *out_row);  ++out_row;
1252                                                         in_row++;
1253                                                 }
1254                                         }
1255                                 }
1256                                 current_x += glyph_a;
1257                         }
1258                         height[font_number] = current_h;
1259                         ascent[font_number] = current_ascent;
1260                 }
1261         }
1262
1263         if( freetype_library ) FT_Done_FreeType(freetype_library);
1264 }
1265
1266
1267 //This checks if char_code is on the selected font, else it changes font to the first compatible //Akirad
1268 int TitleMain::check_char_code_path(FT_Library &freetype_library,
1269         char *path_old, FT_ULong &char_code, char *path_new)
1270 {
1271         FT_Face temp_freetype_face;
1272         FcPattern *pat;
1273         FcFontSet *fs;
1274         FcObjectSet *os;
1275         FcChar8 *file, *format;
1276         FcConfig *config;
1277         FcPattern *font;
1278
1279         FcInit();
1280         config = FcConfigGetCurrent();
1281         FcConfigSetRescanInterval(config, 0);
1282
1283         pat = FcPatternCreate();
1284         os = FcObjectSetBuild ( FC_FILE, FC_FONTFORMAT, (char *) 0);
1285         fs = FcFontList(config, pat, os);
1286         int found = 0;
1287         char tmpstring[BCTEXTLEN];
1288         int limit_to_truetype = 0; //if you want to limit search to truetype put 1
1289         if( !freetype_library ) FT_Init_FreeType(&freetype_library);
1290         if( !FT_New_Face(freetype_library, path_old, 0, &temp_freetype_face) ) {
1291                 FT_Set_Pixel_Sizes(temp_freetype_face, 128, 0);
1292                 int gindex = FT_Get_Char_Index(temp_freetype_face, char_code);
1293                 if( gindex != 0 && char_code == 10 ) {
1294                         strcpy(path_new, path_old);
1295                         found = 1;
1296                 }
1297         }
1298
1299         if( !found ) {
1300                 for( int i=0; fs && i<fs->nfont; ++i ) {
1301                         font = fs->fonts[i];
1302                         FcPatternGetString(font, FC_FONTFORMAT, 0, &format);
1303                         if( strcmp((char *)format, "TrueType") && !limit_to_truetype ) continue;
1304                         if( FcPatternGetString(font, FC_FILE, 0, &file) != FcResultMatch ) continue;
1305                         sprintf(tmpstring, "%s", file);
1306                         if( !FT_New_Face(freetype_library, tmpstring, 0, &temp_freetype_face) ) continue;
1307                         FT_Set_Pixel_Sizes(temp_freetype_face, 128, 0);
1308                         int gindex = FT_Get_Char_Index(temp_freetype_face, char_code);
1309                         if( gindex != 0 && char_code == 10 ) {
1310                                 sprintf(path_new, "%s", tmpstring);
1311                                 found = 1;
1312                                 goto done;
1313                         }
1314                 }
1315         }
1316
1317 done:
1318         if( fs ) FcFontSetDestroy(fs);
1319         if( temp_freetype_face ) FT_Done_Face(temp_freetype_face);
1320         temp_freetype_face = 0;
1321
1322         if( !found ) {
1323                 strcpy(path_new, path_old);
1324                 return 1;
1325         }
1326
1327         return 0;
1328 }
1329
1330
1331 int TitleMain::load_freetype_face(FT_Library &freetype_library,
1332         FT_Face &freetype_face, const char *path)
1333 {
1334 //printf("TitleMain::load_freetype_face 1\n");
1335         if( !freetype_library )
1336                 FT_Init_FreeType(&freetype_library);
1337         if( freetype_face )
1338                 FT_Done_Face(freetype_face);
1339         freetype_face = 0;
1340 //printf("TitleMain::load_freetype_face 2\n");
1341
1342 // Use freetype's internal function for loading font
1343         if( FT_New_Face(freetype_library, path, 0, &freetype_face) ) {
1344                 fprintf(stderr, _("TitleMain::load_freetype_face %s failed.\n"), path);
1345                 freetype_face = 0;
1346                 freetype_library = 0;
1347                 return 1;
1348         }
1349         return 0;
1350 }
1351
1352 int TitleMain::load_font(BC_FontEntry *font)
1353 {
1354         if( load_freetype_face(freetype_library,freetype_face, font->path) ) return 1;
1355         strcpy(text_font, font->displayname);
1356         return 0;
1357 }
1358
1359
1360 Indexable *TitleMain::open_background(const char *filename)
1361 {
1362         delete render_engine;  render_engine = 0;
1363         delete video_cache;    video_cache = 0;
1364         delete bg_file;        bg_file = new File;
1365
1366         Asset *asset = new Asset(filename);
1367         int result = bg_file->open_file(server->preferences, asset, 1, 0);
1368         if( result == FILE_OK ) return (Indexable *)asset;
1369 // not asset
1370         asset->Garbage::remove_user();
1371         delete bg_file;   bg_file = 0;
1372         if( result != FILE_IS_XML ) return 0;
1373 // nested edl
1374         FileXML xml_file;
1375         if( xml_file.read_from_file(filename) ) return 0;
1376         EDL *nested_edl = new EDL;
1377         nested_edl->create_objects();
1378         nested_edl->set_path(filename);
1379         nested_edl->load_xml(&xml_file, LOAD_ALL);
1380         TransportCommand command;
1381         //command.command = audio_tracks ? NORMAL_FWD : CURRENT_FRAME;
1382         command.command = CURRENT_FRAME;
1383         command.get_edl()->copy_all(nested_edl);
1384         command.change_type = CHANGE_ALL;
1385         command.realtime = 0;
1386         render_engine = new RenderEngine(0, server->preferences, 0, 0);
1387         render_engine->set_vcache(video_cache = new CICache(server->preferences));
1388         render_engine->arm_command(&command);
1389         return (Indexable *)nested_edl;
1390 }
1391
1392 int TitleMain::read_background(VFrame *frame, int64_t position, int color_model)
1393 {
1394         int result = 1;
1395         VFrame *iframe = frame;
1396         int bw = background->get_w(), bh = background->get_h();
1397         if( background->is_asset ) {
1398                 Asset *asset = (Asset *)background;
1399                 if( bw != asset->width || bh != asset->height )
1400                         iframe = new_temp(asset->width, asset->height, color_model);
1401                 int64_t source_position = (int64_t)(position *
1402                         asset->frame_rate / project_frame_rate);
1403                 if( config.loop_playback ) {
1404                         int64_t loop_size = asset->get_video_frames();
1405                         source_position -= (int64_t)(source_position / loop_size) * loop_size;
1406                 }
1407                 if( bg_file ) {
1408                         bg_file->set_video_position(source_position, 0);
1409                         result = bg_file->read_frame(iframe);
1410                 }
1411         }
1412         else {
1413                 EDL *nested_edl = (EDL *)background;
1414                 if( color_model != nested_edl->session->color_model ||
1415                     bw != nested_edl->session->output_w ||
1416                     bh != nested_edl->session->output_h )
1417                         iframe = new_temp(
1418                                 nested_edl->session->output_w,
1419                                 nested_edl->session->output_h,
1420                                 nested_edl->session->color_model);
1421                 int64_t source_position = (int64_t)(position *
1422                         nested_edl->session->frame_rate / project_frame_rate);
1423                 if( config.loop_playback ) {
1424                         int64_t loop_size = nested_edl->get_video_frames();
1425                         source_position -= (int64_t)(source_position / loop_size) * loop_size;
1426                 }
1427                 if( render_engine->vrender )
1428                         result = render_engine->vrender->process_buffer(iframe, source_position, 0);
1429         }
1430         if( !result && iframe != frame )
1431                 frame->transfer_from(iframe);
1432         return result;
1433 }
1434
1435 void TitleMain::draw_background()
1436 {
1437         if( background ) {
1438                 if( strcmp(background->path, config.background_path) ) {
1439                         if( background ) {
1440                                 background->Garbage::remove_user();
1441                                 background = 0;
1442                         }
1443                         if( bg_file ) {
1444                                 delete bg_file;
1445                                 bg_file = 0;
1446                         }
1447                 }
1448         }
1449         if( !background && config.background_path[0] && !access(config.background_path,R_OK) )
1450                 background = open_background(config.background_path);
1451         if( background ) {
1452                 int bw = background->get_w(), bh = background->get_h();
1453                 if( bg_frame && (bg_frame->get_w() != bw || bg_frame->get_h() != bh ||
1454                     bg_frame->get_color_model() != output_model) ) {
1455                         delete bg_frame;  bg_frame = 0;
1456                 }
1457                 if( !bg_frame )
1458                         bg_frame = new VFrame(0, -1, bw, bh, output_model, -1);
1459                 int64_t position = get_source_position() - get_source_start();
1460                 if( !read_background(bg_frame, position, output_model) ) {
1461                         if( !overlay_frame )
1462                                 overlay_frame = new OverlayFrame(cpus);
1463                         float in_x1 = 0, in_x2 = bg_frame->get_w();
1464                         float in_y1 = 0, in_y2 = bg_frame->get_h();
1465                         float out_x1 = config.title_x, out_x2 = out_x1 + title_w;
1466                         float out_y1 = config.title_y, out_y2 = out_y1 + title_h;
1467                         overlay_frame->overlay(output, bg_frame,
1468                                 in_x1,in_y1, in_x2,in_y2,
1469                                 out_x1,out_y1, out_x2,out_y2,
1470                                 1, TRANSFER_NORMAL, CUBIC_LINEAR);
1471                 }
1472         }
1473 }
1474
1475 BC_FontEntry* TitleMain::get_font(const char *font_name, int style)
1476 {
1477         if( !strcmp("fixed", font_name) )
1478                 font_name = FIXED_FONT;
1479         int flavor =
1480             ((style & BC_FONT_ITALIC) != 0 ? FL_SLANT_ITALIC | FL_SLANT_OBLIQUE : FL_SLANT_ROMAN) |
1481             ((style & BC_FONT_BOLD) != 0 ? FL_WEIGHT_BOLD | FL_WEIGHT_DEMIBOLD |
1482                         FL_WEIGHT_EXTRABOLD| FL_WEIGHT_BLACK | FL_WEIGHT_EXTRABLACK :
1483                         FL_WEIGHT_BOOK | FL_WEIGHT_NORMAL | FL_WEIGHT_MEDIUM |
1484                         FL_WEIGHT_LIGHT | FL_WEIGHT_EXTRALIGHT | FL_WEIGHT_THIN);
1485
1486         int mask = FL_WEIGHT_MASK | FL_SLANT_MASK;
1487
1488         BC_Resources *resources =  BC_WindowBase::get_resources();
1489         BC_FontEntry *font = resources->find_fontentry(font_name, flavor, mask, style);
1490         if( font && strcmp(font_name, font->displayname) ) font = 0;
1491         return font;
1492 }
1493 BC_FontEntry* TitleMain::config_font()
1494 {
1495         BC_FontEntry *font = get_font(config.font, config.style);
1496         if( !font || load_font(font) )
1497                 load_font(font = get_font(FIXED_FONT,0));
1498         return font;
1499 }
1500
1501
1502 static inline bool is_ltr(wchar_t wch) { return (wch>='a' && wch<='z') || (wch>='A' && wch<='Z'); }
1503 static inline bool is_nbr(wchar_t wch) { return (wch>='0' && wch<='9'); }
1504 static inline bool is_ws(wchar_t wch) { return wch==' ' || wch=='\t'; }
1505 static inline bool is_idch(wchar_t wch) { return is_ltr(wch) || is_nbr(wch) || wch=='_'; }
1506
1507 // return eof=-1, chr=0, opener=1, closer=2
1508 int TitleParser::wget(wchar_t &wch)
1509 {
1510         char *ip = id, *tp = text;  *ip = 0;  *tp = 0;
1511         int ilen = sizeof(id), tlen = sizeof(text), ich;
1512         while( (ich=wnext()) >= 0 ) {
1513                 if( ich == '\\' ) {
1514                         if( (ich=wnext()) == '\n' ) continue;
1515                         wch = ich;
1516                         return 0;
1517                 }
1518                 if( ich == '<' ) break;
1519                 if( ich != '#' ) { wch = ich;  return 0; }
1520                 while( (ich=wnext()) >= 0 && ich != '\n' );
1521                 if( ich < 0 ) break;
1522         }
1523         if( ich < 0 ) return -1;
1524         int ret = 1;  long pos = tell();
1525         if( (ich=wnext()) == '/' ) { ret = 2; ich = wnext(); }
1526         if( is_ltr(ich) ) {
1527                 *ip++ = ich;
1528                 while( is_idch(ich=wnext()) )
1529                         if( --ilen > 0 ) *ip++ = ich;
1530         }
1531         *ip = 0;
1532         while( is_ws(ich) ) ich = wnext();
1533         while( ich >= 0 && ich != '>' ) {
1534                 if( ich == '\n' || ich == '<' ) { ich = -1;  break; }
1535                 if( ich == '\\' && (ich=wnext()) < 0 ) break;
1536                 if( --tlen > 0 ) *tp++ = ich;
1537                 ich = wnext();
1538         }
1539         *tp = 0;
1540         if( ich < 0 ) { ich = '<';  seek(pos);  ret = 0; }
1541         wch = ich;
1542         return ret;
1543 }
1544
1545 TitleGlyph *TitleMain::get_glyph(FT_ULong char_code, BC_FontEntry *font, int size, int style)
1546 {
1547         for( int i=0, n=title_glyphs.count(); i<n; ++i ) {
1548                 TitleGlyph *glyph = title_glyphs[i];
1549                 if( glyph->char_code == char_code && glyph->font == font &&
1550                     glyph->size == size && glyph->style == style )
1551                         return glyph;
1552         }
1553         return 0;
1554 }
1555
1556 int TitleMain::get_width(TitleGlyph *cur, TitleGlyph *nxt)
1557 {
1558         if( !cur || cur->char_code == '\n' ) return 0;
1559         int result = cur->advance_x;
1560         if( !nxt ) return result;
1561         FT_Vector kerning;
1562         if( !FT_Get_Kerning(freetype_face,
1563             cur->freetype_index, nxt->freetype_index,
1564             ft_kerning_default, &kerning) )
1565                 result += (kerning.x >> 6);
1566         return result;
1567 }
1568
1569
1570 VFrame *TitleMain::get_image(const char *path)
1571 {
1572         for( int i=0; i<title_images.count(); ++i ) {
1573                 if( !strcmp(path, title_images[i]->path) )
1574                         return title_images[i]->vframe;
1575         }
1576         return 0;
1577 }
1578
1579 VFrame *TitleMain::add_image(const char *path)
1580 {
1581         VFrame *vframe = get_image(path);
1582         if( !vframe && (vframe=VFramePng::vframe_png(path)) != 0 ) {
1583                 if( vframe->get_color_model() != text_model ) {
1584                         VFrame *frame = new VFrame(vframe->get_w(), vframe->get_h(), text_model);
1585                         frame->transfer_from(vframe);  delete vframe;
1586                         vframe = frame;
1587                 }
1588                 title_images.append(new TitleImage(path, vframe));
1589         }
1590         return vframe;
1591 }
1592
1593 int TitleCurColor::set(const char *txt)
1594 {
1595 #define BCOLOR(NM) { #NM, NM }
1596         static const struct { const char *name; int color; } colors[] = {
1597                 BCOLOR(MNBLUE),  BCOLOR(ORANGE),  BCOLOR(BLOND), 
1598                 BCOLOR(MNGREY),  BCOLOR(FGGREY),  BCOLOR(FTGREY),   BCOLOR(DKGREY),
1599                 BCOLOR(LTGREY),  BCOLOR(MEGREY),  BCOLOR(DMGREY),   BCOLOR(MDGREY),
1600                 BCOLOR(LTPURPLE),BCOLOR(MEPURPLE),BCOLOR(MDPURPLE), BCOLOR(DKPURPLE),
1601                 BCOLOR(LTCYAN),  BCOLOR(MECYAN),  BCOLOR(MDCYAN),   BCOLOR(DKCYAN),
1602                 BCOLOR(YELLOW),  BCOLOR(LTYELLOW),BCOLOR(MEYELLOW), BCOLOR(MDYELLOW),
1603                 BCOLOR(LTGREEN), BCOLOR(DKGREEN), BCOLOR(DKYELLOW), BCOLOR(LTPINK),
1604                 BCOLOR(PINK),    BCOLOR(LTBLUE),  BCOLOR(DKBLUE),
1605                 BCOLOR(RED),     BCOLOR(GREEN),   BCOLOR(BLUE),
1606                 BCOLOR(BLACK),   BCOLOR(WHITE),
1607         };
1608         int color;
1609         if( *txt ) {
1610                 if( txt[0] == '#' ) {
1611                         if( sscanf(&txt[1], "%x", &color) != 1 ) return 1;
1612                 }
1613                 else {
1614                         int i = sizeof(colors)/sizeof(colors[0]);
1615                         while( --i >= 0 && strcasecmp(txt, colors[i].name) );
1616                         if( i < 0 ) return 1;
1617                         color = colors[i].color;
1618                 }
1619         }
1620         else
1621                 color = parser->plugin->config.color;
1622         push(color);
1623         return 0;
1624 }
1625
1626 int TitleCurAlpha::set(const char *txt)
1627 {
1628         float a = !*txt ?
1629                 parser->plugin->config.alpha :
1630                 strtof(txt,(char**)&txt) * 255;
1631         int alpha = a;
1632         if( *txt || alpha < 0 || alpha > 255 ) return 1;
1633         push(alpha);
1634         return 0;
1635 }
1636
1637 int TitleCurSize::set(const char *txt)
1638 {
1639         float size = 0;
1640         if( !*txt ) {
1641                 size = parser->plugin->config.size;
1642         }
1643         else if( *txt == '+' || *txt == '-' ) {
1644                 size = *this;
1645                 for( int ch; (ch=*txt)!=0; ++txt ) {
1646                         if( ch == '+' ) { size *= 5./4.; continue; }
1647                         if( ch == '-' ) { size *= 4./5.; continue; }
1648                         return 1;
1649                 }
1650         }
1651         else {
1652                 size = strtof(txt,(char**)&txt);
1653         }
1654         if( *txt || size <= 0 || size > 2048 ) return 1;
1655         int style = parser->cur_font.style();
1656         if( !parser->cur_font.set(0,style) ) return 1;
1657         push(size);
1658         return 0;
1659 }
1660 int TitleCurSize::unset(const char *txt)
1661 {
1662         if( pop() ) return 1;
1663         int style = parser->cur_font.style();
1664         parser->cur_font.set(0,style);
1665         return 0;
1666 }
1667
1668
1669 int TitleCurBold::set(const char *txt)
1670 {
1671         int bold = !*txt ? 1 :
1672                 strtol(txt,(char**)&txt,0);
1673         if( *txt || bold < 0 || bold > 1 ) return 1;
1674         int style = parser->cur_font.style();
1675         if( bold ) style |= BC_FONT_BOLD;
1676         else style &= ~BC_FONT_BOLD;
1677         if( !parser->cur_font.set(0,style) ) return 1;
1678         push(bold);
1679         return 0;
1680 }
1681 int TitleCurBold::unset(const char *txt)
1682 {
1683         if( pop() ) return 1;
1684         int style = parser->cur_font.style();
1685         parser->cur_font.set(0,style);
1686         return 0;
1687 }
1688
1689 int TitleCurItalic::set(const char *txt)
1690 {
1691         int italic = !*txt ? 1 :
1692                 strtol(txt,(char**)&txt,0);
1693         if( *txt || italic < 0 || italic > 1 ) return 1;
1694         int style = parser->cur_font.style();
1695         if( italic ) style |= BC_FONT_ITALIC;
1696         else style &= ~BC_FONT_ITALIC;
1697         if( !parser->cur_font.set(0,style) ) return 1;
1698         push(italic);
1699         return 0;
1700 }
1701 int TitleCurItalic::unset(const char *txt)
1702 {
1703         if( pop() ) return 1;
1704         int style = parser->cur_font.style();
1705         parser->cur_font.set(0,style);
1706         return 0;
1707 }
1708
1709
1710 int TitleCurFont::style()
1711 {
1712         int style = 0;
1713         if( parser->cur_bold ) style |= BC_FONT_BOLD;
1714         if( parser->cur_italic ) style |= BC_FONT_ITALIC;
1715         return style;
1716 }
1717 BC_FontEntry* TitleCurFont::get(const char *txt, int style)
1718 {
1719         if( !txt ) txt = parser->plugin->text_font;
1720         else if( !*txt ) txt = parser->plugin->config.font;
1721         return parser->plugin->get_font(txt, style);
1722 }
1723 BC_FontEntry *TitleCurFont::set(const char *txt, int style)
1724 {
1725         BC_FontEntry *font = get(txt, style);
1726         if( !font || parser->plugin->load_font(font) ) return 0;
1727         if( !txt ) (BC_FontEntry*&)*this = font;
1728         return font;
1729 }
1730 int TitleCurFont::set(const char *txt)
1731 {
1732         BC_FontEntry *font = set(txt, style());
1733         if( !font ) return 1;
1734         push(font);
1735         return 0;
1736 }
1737 int TitleCurFont::unset(const char *txt)
1738 {
1739         if( *txt || pop() ) return 1;
1740         BC_FontEntry *font = *this;
1741         if( !font ) return 1;
1742         font = get(font->displayname, style());
1743         if( !font ) return 1;
1744         (BC_FontEntry*&)*this = font;
1745         return 0;
1746 }
1747
1748 int TitleCurCaps::set(const char *txt)
1749 {
1750         int caps = !*txt ? 1 : strtol(txt,(char **)&txt,0);
1751         if( *txt || caps < -1 || caps > 1 ) return 1;
1752         push(caps);
1753         return 0;
1754 }
1755
1756 int TitleCurBlink::set(const char *txt)
1757 {
1758         float blink = !*txt ? 1 : strtof(txt,(char **)&txt);
1759         if( *txt ) return 1;
1760         push(blink);
1761         return 0;
1762 }
1763
1764 int TitleCurFixed::set(const char *txt)
1765 {
1766         int fixed = !*txt ?
1767                 parser->cur_size*3/4 :
1768                 strtol(txt,(char **)&txt,0);
1769         if( *txt || fixed < 0 ) return 1;
1770         push(fixed);
1771         return 0;
1772 }
1773
1774 int TitleCurSuper::set(const char *txt)
1775 {
1776         int super = !*txt ? 1 : strtol(txt,(char **)&txt,0);
1777         if( *txt || super < -1 || super > 1 ) return 1;
1778         push(super);
1779         return 0;
1780 }
1781
1782 int TitleCurNudge::set(const char *txt)
1783 {
1784         if( !*txt ) return 1;
1785         short nx = strtol(txt,(char **)&txt,0);
1786         if( *txt++ != ',' ) return 1;
1787         short ny = strtol(txt,(char **)&txt,0);
1788         if( *txt ) return 1;
1789         int nudge = (nx << 16) | (ny & 0xffff);
1790         push(nudge);
1791         return 0;
1792 }
1793
1794 int TitleParser::set_attributes(int ret)
1795 {
1796         if( !strcmp(id,_("nudge")) )  return ret>1 ? cur_nudge.unset(text)  : cur_nudge.set(text);
1797         if( !strcmp(id,_("color")) )  return ret>1 ? cur_color.unset(text)  : cur_color.set(text);
1798         if( !strcmp(id,_("alpha")) )  return ret>1 ? cur_alpha.unset(text)  : cur_alpha.set(text);
1799         if( !strcmp(id,_("font")) )   return ret>1 ? cur_font.unset(text)   : cur_font.set(text);
1800         if( !strcmp(id,_("size")) )   return ret>1 ? cur_size.unset(text)   : cur_size.set(text);
1801         if( !strcmp(id,_("bold")) )   return ret>1 ? cur_bold.unset(text)   : cur_bold.set(text);
1802         if( !strcmp(id,_("italic")) ) return ret>1 ? cur_italic.unset(text) : cur_italic.set(text);
1803         if( !strcmp(id,_("caps")) )   return ret>1 ? cur_caps.unset(text)   : cur_caps.set(text);
1804         if( !strcmp(id,_("ul")) )     return ret>1 ? cur_under.unset(text)  : cur_under.set(text);
1805         if( !strcmp(id,_("blink")) )  return ret>1 ? cur_blink.unset(text)  : cur_blink.set(text);
1806         if( !strcmp(id,_("fixed")) )  return ret>1 ? cur_fixed.unset(text)  : cur_fixed.set(text);
1807         if( !strcmp(id,_("sup")) )    return ret>1 ? cur_super.unset(text)  : cur_super.set(text);
1808         return 1;
1809 }
1810
1811
1812 void TitleMain::load_glyphs()
1813 {
1814 // Build table of all glyphs needed
1815         TitleParser wchrs(this);
1816         int total_packages = 0;
1817
1818         while( !wchrs.eof() ) {
1819                 wchar_t wch1 = wchrs.wcur(), wch;
1820                 long ipos = wchrs.tell();
1821                 int ret = wchrs.wget(wch);
1822                 if( ret > 0 ) {
1823                         if( !wchrs.set_attributes(ret) ) continue;
1824                         if( !strcmp(wchrs.id,"png") && add_image(wchrs.text) ) continue;
1825                         wch = wch1;  wchrs.seek(ipos+1);
1826                         ret = 0;
1827                 }
1828                 if( !ret ) {
1829                         int cur_caps = wchrs.cur_caps;
1830                         if( cur_caps > 0 ) wch = towupper(wch);
1831                         else if( cur_caps < 0 ) wch = towlower(wch);
1832                         BC_FontEntry *cur_font = wchrs.cur_font;
1833                         int cur_size = wchrs.cur_size;
1834                         int cur_style = 0;
1835                         int cur_bold  = wchrs.cur_bold;
1836                         if( cur_bold ) cur_style |= BC_FONT_BOLD;
1837                         int cur_italic  = wchrs.cur_italic;
1838                         if( cur_italic ) cur_style |= BC_FONT_ITALIC;
1839                         int cur_super = wchrs.cur_super;
1840                         if( cur_super ) cur_size /= 2;
1841                         int exists = 0;
1842                         for( int j=0; j<title_glyphs.count(); ++j ) {
1843                                 TitleGlyph *glyph = title_glyphs[j];
1844                                 if( glyph->char_code == (FT_ULong)wch && glyph->font == cur_font &&
1845                                     glyph->size == cur_size && glyph->style == cur_style ) {
1846                                         exists = 1;   break;
1847                                 }
1848                         }
1849
1850                         if( !exists && cur_font ) {
1851                                 total_packages++;
1852                                 TitleGlyph *glyph = new TitleGlyph;
1853                                 glyph->char_code = (FT_ULong)wch;
1854                                 glyph->font = cur_font;
1855                                 glyph->size = cur_size;
1856                                 glyph->style = cur_style;
1857                                 title_glyphs.append(glyph);
1858                         }
1859                 }
1860         }
1861
1862         if( !glyph_engine )
1863                 glyph_engine = new GlyphEngine(this, cpus);
1864
1865         glyph_engine->set_package_count(total_packages);
1866         glyph_engine->process_packages();
1867 }
1868
1869
1870 TitleImage::TitleImage(const char *path, VFrame *vfrm)
1871 {
1872         this->path = cstrdup(path);
1873         this->vframe = vfrm;
1874 }
1875 TitleImage::~TitleImage()
1876 {
1877         delete [] path;
1878         delete vframe;
1879 }
1880
1881 TitleChar *TitleChar::init(int typ, void *vp)
1882 {
1883         wch = 0;
1884         flags = 0;
1885         this->typ = typ;
1886         this->vp = vp;
1887         x = y = 0;
1888         row = dx = 0;
1889         blink = 0.;
1890         size = 0.;
1891         color = BLACK;
1892         alpha = 0xff;
1893         fade = 1;
1894         return this;
1895 }
1896
1897 TitleRow *TitleRow::init()
1898 {
1899         x0 = y0 = 0;
1900         x1 = y2 = 0; //MAX_FLT;
1901         y1 = x2 = 0; //MIN_FLT;
1902         return this;
1903 }
1904
1905 int TitleMain::get_text()
1906 {
1907 // Determine extents of total text
1908         title_chars.reset();
1909         title_rows.reset();
1910         int pitch = config.line_pitch;
1911         float font_h = config.size;
1912         int descent = 0;
1913
1914         TitleParser wchrs(this);
1915
1916         TitleRow *row = 0;
1917         float row_w = 0, row_h = 0;
1918         float row_x = 0, row_y = 0;
1919         text_rows = 0;
1920
1921         for(;;) {
1922                 if( !row ) row = title_rows.add();
1923                 TitleChar *chr = 0;
1924                 long ipos = wchrs.tell();
1925                 wchar_t wch1 = wchrs.wcur(), wch;
1926                 int ret = wchrs.wget(wch);
1927                 if( ret < 0 || wch == '\n' ) {
1928                         if( row->x1 > row->x2 ) row->x1 = row->x2 = 0;
1929                         if( row->y2 > row->y1 ) row->y1 = row->y2 = 0;
1930                         int dy = row->y1 - descent;
1931                         row_y += pitch ? pitch : dy > font_h ? dy : font_h;
1932                         row->y0 = row_y;
1933                         descent = row->y2;
1934                         if( row_x > row_w ) row_w = row_x;
1935                         if( row_y > row_h ) row_h = row_y;
1936                         text_rows = title_rows.count();
1937                         row_x = 0;  row = 0;
1938                         if( ret < 0 ) break;
1939                         continue;
1940                 }
1941                 BC_FontEntry *cur_font = wchrs.cur_font;
1942                 int cur_color   = wchrs.cur_color;
1943                 int cur_alpha   = wchrs.cur_alpha;
1944                 float cur_size  = wchrs.cur_size;
1945                 int cur_caps    = wchrs.cur_caps;
1946                 int cur_under   = wchrs.cur_under;
1947                 float cur_blink = wchrs.cur_blink;
1948                 int cur_fixed   = wchrs.cur_fixed;
1949                 int cur_super   = wchrs.cur_super;
1950                 int cur_nudge   = wchrs.cur_nudge;
1951                 int cur_style = 0;
1952                 int cur_bold  = wchrs.cur_bold;
1953                 if( cur_bold ) cur_style |= BC_FONT_BOLD;
1954                 int cur_italic  = wchrs.cur_italic;
1955                 if( cur_italic ) cur_style |= BC_FONT_ITALIC;
1956                 short nx = cur_nudge >> 16, ny = cur_nudge;
1957                 int cx = nx, cy = ny, cw = 0, ch = 0, dx = 0;
1958                 if( ret > 0 ) {
1959                         if( !wchrs.set_attributes(ret) ) continue;
1960                         ret = -1;
1961                         if( !strcmp(wchrs.id,"png") ) {
1962                                 VFrame *png_image = get_image(wchrs.text);
1963                                 if( png_image ) {
1964                                         chr = title_chars.add(CHAR_IMAGE, png_image);
1965                                         cy += ch = png_image->get_h();
1966                                         cw = dx = png_image->get_w();
1967                                         wch = 0;  ret = 0;
1968                                 }
1969                         }
1970                         if( ret < 0 ) {
1971                                 wch = wch1;  wchrs.seek(ipos+1);
1972                         }
1973                 }
1974                 if( wch ) {
1975                         if( cur_caps > 0 ) wch = towupper(wch);
1976                         else if( cur_caps < 0 ) wch = towlower(wch);
1977                         int size = !cur_super ? cur_size : cur_size/2;
1978                         TitleGlyph *gp = get_glyph(wch, cur_font, size, cur_style);
1979                         if( !gp ) continue;
1980
1981                         if( cur_super > 0 ) cy += cur_size-4*size/3;
1982                         else if( cur_super < 0 ) cy -= size/3;
1983
1984                         dx =  gp->advance_x;
1985
1986                         if( cur_fixed )
1987                                 dx = cur_fixed;
1988                         else if( !wchrs.eof() ) {
1989                                 TitleGlyph *np = get_glyph(wchrs.wcur(), cur_font, cur_size, cur_style);
1990                                 dx = get_width(gp, np);
1991                         }
1992
1993                         chr = title_chars.add(CHAR_GLYPH, gp);
1994                         cx += gp->left;
1995                         cy += gp->top;
1996                         cw = gp->right - gp->left;
1997                         ch = gp->top - gp->bottom;
1998                 }
1999
2000                 if( !chr ) continue;
2001                 chr->wch = wch;
2002                 chr->size  = cur_size;
2003                 chr->blink = cur_blink;
2004                 chr->color = cur_color;
2005                 chr->alpha = cur_alpha;
2006                 chr->fade = 1;
2007                 if( cur_fixed ) chr->flags |= FLAG_FIXED;
2008                 if( cur_super > 0 ) chr->flags |= FLAG_SUPER;
2009                 if( cur_super < 0 ) chr->flags |= FLAG_SUBER;
2010                 if( cur_under ) chr->flags |= FLAG_UNDER;
2011                 if( cur_blink ) chr->flags |= FLAG_BLINK;
2012                 chr->x = (cx += row_x);
2013                 chr->y = cy;
2014                 chr->dx = dx;
2015                 row->bound(cx,cy, cx+cw,cy-ch);
2016                 chr->row = text_rows;
2017                 row_x += chr->dx;
2018         }
2019
2020         if( !row_w || !row_h ) return 1;
2021
2022 // rows boundary, note: row->xy is y up (FT), row_xy is y down (X)
2023         text_x1 = text_y1 = MAX_FLT;
2024         text_x2 = text_y2 = MIN_FLT;
2025         for( int i=0; i<text_rows; ++i ) {
2026                 row = title_rows[i];
2027                 switch( config.hjustification ) {
2028                 case JUSTIFY_LEFT:   row->x0 = 0;  break;
2029                 case JUSTIFY_CENTER: row->x0 = (row_w - (row->x2-row->x1)) / 2;  break;
2030                 case JUSTIFY_RIGHT:  row->x0 = row_w - (row->x2-row->x1);  break;
2031                 }
2032                 float v;
2033                 if( text_x1 > (v=row->x0+row->x1) ) text_x1 = v;
2034                 if( text_y1 > (v=row->y0-row->y1) ) text_y1 = v;
2035                 if( text_x2 < (v=row->x0+row->x2) ) text_x2 = v;
2036                 if( text_y2 < (v=row->y0-row->y2) ) text_y2 = v;
2037         }
2038         if( text_x1 > text_x2 || text_y1 > text_y2 ) return 1;
2039         text_x1 += fuzz1;  text_y1 += fuzz1;
2040         text_x2 += fuzz2;  text_y2 += fuzz2;
2041         text_w = text_x2 - text_x1;
2042         text_h = text_y2 - text_y1;
2043         return 0;
2044 }
2045
2046 int TitleMain::get_visible_text()
2047 {
2048 // Determine y of visible text
2049         switch( config.motion_strategy ) {
2050         case BOTTOM_TO_TOP:
2051         case TOP_TO_BOTTOM: {
2052                 float magnitude = config.pixels_per_second *
2053                         (get_source_position() - config.prev_keyframe_position) /
2054                         PluginVClient::project_frame_rate;
2055                 if( config.loop ) {
2056                         int loop_size = text_h + title_h;
2057                         magnitude -= (int)(magnitude / loop_size) * loop_size;
2058                 }
2059                 text_y = config.motion_strategy == BOTTOM_TO_TOP ?
2060                         title_h - magnitude :
2061                         magnitude - text_h;
2062                 break; }
2063         default: switch( config.vjustification ) {
2064         case JUSTIFY_TOP:    text_y =  0;  break;
2065         case JUSTIFY_MID:    text_y = (title_h - text_h) / 2;  break;
2066         case JUSTIFY_BOTTOM: text_y =  title_h - text_h;  break;
2067         default: break; }
2068         }
2069
2070 // Determine x of visible text
2071         switch( config.motion_strategy ) {
2072         case RIGHT_TO_LEFT:
2073         case LEFT_TO_RIGHT: {
2074                 float magnitude = config.pixels_per_second *
2075                         (get_source_position() - get_source_start()) /
2076                         PluginVClient::project_frame_rate;
2077                 if( config.loop ) {
2078                         int loop_size = text_w + title_w;
2079                         magnitude -= (int)(magnitude / loop_size) * loop_size;
2080                 }
2081                 text_x = config.motion_strategy == RIGHT_TO_LEFT ?
2082                         title_w - magnitude :
2083                         magnitude - text_w;
2084                 break; }
2085         default: switch ( config.hjustification ) {
2086         case JUSTIFY_LEFT:   text_x =  0;  break;
2087         case JUSTIFY_CENTER: text_x = (title_w - text_w) / 2;  break;
2088         case JUSTIFY_RIGHT:  text_x =  title_w - text_w;  break;
2089         default: break; }
2090         }
2091
2092
2093         // until bottom of this row is visible
2094         int row1 = 0;
2095         int y0 = text_y - text_y1;
2096         while( row1 < text_rows ) {
2097                 TitleRow *row = title_rows[row1];
2098                 if( y0 + row->y0-row->y2 > 0 ) break;
2099                 ++row1;
2100         }
2101         if( row1 >= text_rows ) return 0;
2102
2103         // until top of next row is not visible
2104         y0 -= title_h;
2105         int row2 = row1;
2106         while( row2 < text_rows ) {
2107                 TitleRow *row = title_rows[row2];
2108                 if( y0 + row->y0-row->y1 >= 0 ) break;
2109                 ++row2;
2110         }
2111         if( row1 >= row2 ) return 0;
2112
2113 //printf("get_visible_rows: visible_row1/2 = %d to %d\n",visible_row1,visible_row2);
2114         // Only draw visible chars
2115         double frame_rate = PluginVClient::get_project_framerate();
2116         int64_t units = get_source_position() - get_source_start();
2117         double position = units / frame_rate;
2118         int blinking = 0;
2119         int char1 = -1, char2 = -1, nchars = title_chars.count();
2120         for( int i=0; i<nchars; ++i ) {
2121                 TitleChar *chr = title_chars[i];
2122                 if( chr->row < row1 ) continue;
2123                 if( chr->row >= row2 ) break;
2124                 if( char1 < 0 ) char1 = i;
2125                 char2 = i;
2126                 if( (chr->flags & FLAG_BLINK) != 0 ) {
2127                         blinking = 1;
2128                         double rate = 1 / fabs(chr->blink), rate2 = 2 * rate;
2129                         double pos = position - ((int64_t)(position / rate2)) * rate2;
2130                         chr->fade = chr->blink > 0 ?
2131                                 (pos > rate ? 0 : 1) : fabs(rate+pos) / rate;
2132                 }
2133         }
2134         if( char1 < 0 ) char1 = 0;
2135         ++char2;
2136         if( !blinking && visible_row1 == row1 && visible_row2 == row2 ) return 0;
2137 // need redraw
2138         visible_row1  = row1;   visible_row2  = row2;
2139         visible_char1 = char1;  visible_char2 = char2;
2140         return 1;
2141 }
2142
2143
2144 int TitleMain::draw_text(int need_redraw)
2145 {
2146         // until top of next row is not visible
2147         mask_x1 = mask_y1 = INT_MAX;
2148         mask_x2 = mask_y2 = INT_MIN;
2149         for( int i=visible_row1; i<visible_row2; ++i ) {
2150                 int v;  TitleRow *row = title_rows[i];
2151                 if( mask_x1 > (v=row->x0+row->x1) ) mask_x1 = v;
2152                 if( mask_y1 > (v=row->y0-row->y1) ) mask_y1 = v;
2153                 if( mask_x2 < (v=row->x0+row->x2) ) mask_x2 = v;
2154                 if( mask_y2 < (v=row->y0-row->y2) ) mask_y2 = v;
2155         }
2156         if( mask_x1 >= mask_x2 || mask_y1 >= mask_y2 ) return 1;
2157
2158         mask_x1 += fuzz1;  mask_y1 += fuzz1;
2159         mask_x2 += fuzz2;  mask_y2 += fuzz2;
2160         mask_w = mask_x2 - mask_x1;
2161         mask_h = mask_y2 - mask_y1;
2162
2163 //printf("TitleMain::draw_text %d-%d frame %dx%d\n",
2164 //  visible_row1, visible_row2, mask_w,mask_h);
2165         if( text_mask && (text_mask->get_color_model() != text_model ||
2166             text_mask->get_w() != mask_w || text_mask->get_h() != mask_h) ) {
2167                 delete text_mask;    text_mask = 0;
2168                 delete stroke_mask;  stroke_mask = 0;
2169         }
2170
2171         if( !text_mask ) {
2172 // Always use 8 bit because the glyphs are 8 bit
2173 // Need to set YUV to get clear_frame to set the right chroma.
2174                 mask_model = text_model;
2175                 text_mask = new VFrame;
2176                 text_mask->set_use_shm(0);
2177                 text_mask->reallocate(0, -1, 0, 0, 0, mask_w, mask_h, mask_model, -1);
2178                 int drop = abs(config.dropshadow);
2179                 int drop_w = mask_w + drop;
2180                 int drop_h = mask_h + drop;
2181                 stroke_mask = new VFrame;
2182                 stroke_mask->set_use_shm(0);
2183                 stroke_mask->reallocate(0, -1, 0, 0, 0, drop_w, drop_h, mask_model, -1);
2184                 need_redraw = 1;
2185         }
2186
2187 // Draw on text mask if it has changed
2188         if( need_redraw ) {
2189 //printf("redraw %d to %d   %d,%d  %d,%d - %d,%d\n", visible_char1,visible_char2,
2190 //  ext_x0, ext_y0, ext_x1,ext_y1, ext_x2,ext_y2);
2191
2192                 text_mask->clear_frame();
2193                 stroke_mask->clear_frame();
2194 #if 0
2195                 unsigned char *data = text_mask->get_data(); // draw bbox on text
2196                 for( int x=0; x<mask_w; ++x ) data[4*x+3] = 0xff;
2197                 for( int x=0; x<mask_w; ++x ) data[4*((mask_h-1)*mask_w+x)+3] = 0xff;
2198                 for( int y=0; y<mask_h; ++y ) data[4*mask_w*y+3] = 0xff;
2199                 for( int y=0; y<mask_h; ++y ) data[4*(mask_w*y + mask_w-1)+3] = 0xff;
2200 #endif
2201                 if( !title_engine )
2202                         title_engine = new TitleEngine(this, cpus);
2203
2204 // Draw dropshadow first
2205                 if( config.dropshadow ) {
2206                         title_engine->do_dropshadow = 1;
2207                         title_engine->set_package_count(visible_char2 - visible_char1);
2208                         title_engine->process_packages();
2209                 }
2210
2211 // Then draw foreground
2212                 title_engine->do_dropshadow = 0;
2213                 title_engine->set_package_count(visible_char2 - visible_char1);
2214                 title_engine->process_packages();
2215
2216                 draw_underline(text_mask, config.alpha);
2217
2218 // Convert to text outlines
2219                 if( config.outline_size > 0 ) {
2220                         if( outline_mask &&
2221                             (text_mask->get_w() != outline_mask->get_w() ||
2222                              text_mask->get_h() != outline_mask->get_h()) ) {
2223                                 delete outline_mask;  outline_mask = 0;
2224                         }
2225
2226                         if( !outline_mask ) {
2227                                 outline_mask = new VFrame;
2228                                 outline_mask->set_use_shm(0);
2229                                 outline_mask->reallocate(0, -1, 0, 0, 0,
2230                                         text_mask->get_w(), text_mask->get_h(),
2231                                         text_mask->get_color_model(), -1);
2232                         }
2233                         if( !outline_engine ) outline_engine =
2234                                 new TitleOutlineEngine(this, cpus);
2235                         outline_engine->do_outline();
2236                 }
2237
2238         }
2239
2240         return 0;
2241 }
2242
2243 int TitleMain::draw_underline(VFrame *mask, int alpha)
2244 {
2245         int row = -1, sz = -1, color = -1, rgb = -1;
2246         int bpp = mask->get_bytes_per_pixel(), bpp1 = bpp-1;
2247         int x1 = 0, x2 = 0, y0 = 0;
2248         for( int i=visible_char1; i<visible_char2; ) {
2249                 TitleChar *chr = title_chars[i];
2250                 if( (chr->flags & FLAG_UNDER) && row < 0 ) {
2251                         sz = chr->size;
2252                         rgb = chr->color;  int rr, gg, bb;
2253                         get_mask_colors(rgb, mask_model, rr, gg, bb);
2254                         color = (rr<<16) | (gg<<8) | (bb<<0);
2255                         row = chr->row;
2256                         TitleRow *rp = title_rows[row];
2257                         x1 = rp->x0 + chr->x;
2258                         y0 = rp->y0;
2259                 }
2260                 if( (chr->flags & FLAG_UNDER) && row == chr->row && chr->color == rgb ) {
2261                         TitleRow *rp = title_rows[row];
2262                         x2 = rp->x0 + chr->x + chr->dx;
2263                         if( sz < chr->size ) sz = chr->size;
2264                         if( ++i < visible_char2 ) continue;
2265                 }
2266                 if( row < 0 ) { ++i;  continue; }
2267                 x1 -= mask_x1;  x2 -= mask_x1;  y0 -= mask_y1;
2268                 if( x1 < 0 ) x1 = 0;
2269                 if( x2 > mask_w ) x2 = mask_w;
2270                 int sz1 = sz / 32 + 1, sz2 = sz1/2;
2271                 int y1 = y0 - sz2, y2 = y1 + sz1;
2272                 if( y1 < 0 ) y1 = 0;
2273                 if( y2 > mask_h ) y2 = mask_h;
2274                 unsigned char **rows = mask->get_rows();
2275                 for( int y=y1; y<y2; ++y ) {
2276                         unsigned char *rp = rows[y];
2277                         for( int x=x1; x<x2; ++x ) {
2278                                 unsigned char *bp = rp + bpp * x;
2279                                 for( int i=bpp1; --i>=0; ) *bp++ = color>>(8*i);
2280                                 *bp = alpha;
2281                         }
2282                 }
2283                 row = -1;
2284         }
2285         return 0;
2286 }
2287
2288 void TitleMain::draw_overlay()
2289 {
2290 //printf("TitleMain::draw_overlay 1\n");
2291         fade = 1;
2292         if( !EQUIV(config.fade_in, 0) ) {
2293                 int64_t plugin_start = server->plugin->startproject;
2294                 int64_t fade_len = lroundf(config.fade_in * PluginVClient::project_frame_rate);
2295                 int64_t fade_position = get_source_position() - plugin_start;
2296
2297                 if( fade_position >= 0 && fade_position < fade_len ) {
2298                         fade = (float)fade_position / fade_len;
2299                 }
2300         }
2301         if( !EQUIV(config.fade_out, 0) ) {
2302                 int64_t plugin_end = server->plugin->startproject + server->plugin->length;
2303                 int64_t fade_len = lroundf(config.fade_out * PluginVClient::project_frame_rate);
2304                 int64_t fade_position = plugin_end - get_source_position();
2305
2306                 if( fade_position >= 0 && fade_position < fade_len ) {
2307                         fade = (float)fade_position / fade_len;
2308                 }
2309         }
2310
2311         if( !translate )
2312                 translate = new TitleTranslate(this, cpus);
2313         if( text_x+mask_w > 0 && text_x < title_w ) {
2314                 translate->xlat_mask = text_mask;
2315                 translate->run_packages();
2316                 if( config.stroke_width >= SMALL && (config.style & BC_FONT_OUTLINE) ) {
2317                         translate->xlat_mask = stroke_mask;
2318                         translate->run_packages();
2319                 }
2320         }
2321 }
2322
2323 const char* TitleMain::motion_to_text(int motion)
2324 {
2325         switch( motion ) {
2326         case NO_MOTION:     return _("No motion");
2327         case BOTTOM_TO_TOP: return _("Bottom to top");
2328         case TOP_TO_BOTTOM: return _("Top to bottom");
2329         case RIGHT_TO_LEFT: return _("Right to left");
2330         case LEFT_TO_RIGHT: return _("Left to right");
2331         }
2332         return _("Unknown");
2333 }
2334
2335 int TitleMain::text_to_motion(const char *text)
2336 {
2337         for( int i=0; i<TOTAL_PATHS; ++i ) {
2338                 if( !strcasecmp(motion_to_text(i), text) ) return i;
2339         }
2340         return 0;
2341 }
2342
2343 void TitleMain::reset_render()
2344 {
2345         delete text_mask;     text_mask = 0;
2346         delete stroke_mask;   stroke_mask = 0;
2347         delete glyph_engine;  glyph_engine = 0;
2348         visible_row1 = 0;     visible_row2 = 0;
2349         visible_char1 = 0;    visible_char2 = 0;
2350         title_rows.clear();
2351         title_glyphs.clear();
2352         title_images.clear();
2353         if( freetype_face ) {
2354                 FT_Done_Face(freetype_face);
2355                 freetype_face = 0;
2356         }
2357 }
2358
2359 int TitleMain::init_freetype()
2360 {
2361         if( !freetype_library )
2362                 FT_Init_FreeType(&freetype_library);
2363         return 0;
2364 }
2365
2366 void TitleMain::draw_boundry()
2367 {
2368         VFrame &out = *output;
2369         int iw = output->get_w(), ih = output->get_h();
2370         int mr = MIN(iw, ih)/200 + 2, rr = 2*mr;
2371         int x = title_x, y = title_y, w = title_w, h = title_h;
2372         int r2 = (rr+1)/2;
2373         int x0 = x-r2, x1 = x+(w+1)/2, x2 = x+w+r2;
2374         int y0 = y-r2, y1 = y+(h+1)/2, y2 = y+h+r2;
2375         int st = 1;
2376         for( int r=2; r<mr; r<<=1 ) st = r;
2377         out.set_stiple(st);
2378
2379         for( int r=mr/2; --r>=0; ) { // bbox
2380                 int lft = x+r, rgt = x+w-1-r;
2381                 int top = y+r, bot = y+h-1-r;
2382                 out.draw_line(lft,top, rgt,top);
2383                 out.draw_line(rgt,top, rgt,bot);
2384                 out.draw_line(rgt,bot, lft,bot);
2385                 out.draw_line(lft,bot, lft,top);
2386         }
2387
2388         for( int r=mr; r<rr; ++r ) { // center
2389                 out.draw_smooth(x1-r,y1, x1-r,y1+r, x1,y1+r);
2390                 out.draw_smooth(x1,y1+r, x1+r,y1+r, x1+r,y1);
2391                 out.draw_smooth(x1+r,y1, x1+r,y1-r, x1,y1-r);
2392                 out.draw_smooth(x1,y1-r, x1-r,y1-r, x1-r,y1);
2393         }
2394
2395         for( int r=rr; --r>=0; ) { // edge arrows
2396                 out.draw_line(x1-r,y0+r, x1+r,y0+r);
2397                 out.draw_line(x2-r,y1-r, x2-r,y1+r);
2398                 out.draw_line(x1-r,y2-r, x1+r,y2-r);
2399                 out.draw_line(x0+r,y1+r, x0+r,y1-r);
2400         }
2401         x0 += r2;  y0 += r2;  x2 -= r2;  y2 -= r2;
2402         for( int r=2*mr; --r>=0; ) { // corner arrows
2403                 out.draw_line(x0,y0+r, x0+r,y0);
2404                 out.draw_line(x2,y0+r, x2-r,y0);
2405                 out.draw_line(x2,y2-r, x2-r,y2);
2406                 out.draw_line(x0,y2-r, x0+r,y2);
2407         }
2408 }
2409
2410
2411 int TitleMain::process_realtime(VFrame *input_ptr, VFrame *output_ptr)
2412 {
2413         int result = 0;
2414         input = input_ptr;
2415         output = output_ptr;
2416         output_model = output->get_color_model();
2417         text_model = BC_CModels::is_yuv(output_model) ? BC_YUVA8888 : BC_RGBA8888;
2418
2419         if( text_model != mask_model ) need_reconfigure = 1;
2420         need_reconfigure |= load_configuration();
2421         int64_t cur_position =  get_source_position();
2422         if( last_position < 0 || last_position+1 != cur_position )
2423                 need_reconfigure = 1;
2424         last_position = cur_position;
2425
2426         title_x = config.title_x;  title_y = config.title_y;
2427         title_w = config.title_w ? config.title_w : input->get_w();
2428         title_h = config.title_h ? config.title_h : input->get_h();
2429
2430         fuzz1 = -config.outline_size;
2431         fuzz2 = config.outline_size;
2432         if( config.dropshadow < 0 )
2433                 fuzz1 += config.dropshadow;
2434         else
2435                 fuzz2 += config.dropshadow;
2436         fuzz = fuzz2 - fuzz1;
2437
2438 // Check boundaries
2439         if( config.size <= 0 || config.size >= 2048 )
2440                 config.size = 72;
2441         if( config.stroke_width < 0 || config.stroke_width >= 512 )
2442                 config.stroke_width = 0.0;
2443         if( !config.wlen && !config.timecode )
2444                 return 0;
2445         if( !strlen(config.encoding) )
2446                 strcpy(config.encoding, DEFAULT_ENCODING);
2447
2448 // Always synthesize text and redraw it for timecode
2449         if( config.timecode ) {
2450                 int64_t rendered_frame = get_source_position();
2451                 if( get_direction() == PLAY_REVERSE )
2452                         rendered_frame -= 1;
2453
2454                 char text[BCTEXTLEN];
2455                 Units::totext(text,
2456                                 (double)rendered_frame / PluginVClient::project_frame_rate,
2457                                 config.timecode_format,
2458                                 PluginVClient::get_project_samplerate(),
2459                                 PluginVClient::get_project_framerate(),
2460                                 16);
2461                 config.to_wtext(config.encoding, text, strlen(text)+1);
2462                 need_reconfigure = 1;
2463         }
2464
2465         if( config.background )
2466                 draw_background();
2467
2468 // Handle reconfiguration
2469         if( need_reconfigure ) {
2470                 need_reconfigure = 0;
2471                 reset_render();
2472                 result = init_freetype();
2473                 if( !result ) {
2474                         load_glyphs();
2475                         result = get_text();
2476                 }
2477         }
2478
2479         if( !result )
2480                 result = draw_text(get_visible_text());
2481
2482
2483 // Overlay mask on output
2484         if( !result )
2485                 draw_overlay();
2486
2487         if( config.drag )
2488                 draw_boundry();
2489
2490         return 0;
2491 }
2492
2493 void TitleMain::update_gui()
2494 {
2495         if( thread ) {
2496                 int reconfigure = load_configuration();
2497                 if( reconfigure ) {
2498                         TitleWindow *window = (TitleWindow*)thread->window;
2499                         window->lock_window("TitleMain::update_gui");
2500                         window->update();
2501                         window->unlock_window();
2502                         window->color_thread->update_gui(config.color, 0);
2503                 }
2504         }
2505 }
2506
2507 int TitleMain::load_configuration()
2508 {
2509         KeyFrame *prev_keyframe, *next_keyframe;
2510         prev_keyframe = get_prev_keyframe(get_source_position());
2511         next_keyframe = get_next_keyframe(get_source_position());
2512
2513         TitleConfig old_config, prev_config, next_config;
2514         old_config.copy_from(config);
2515         read_data(prev_keyframe);
2516         prev_config.copy_from(config);
2517         read_data(next_keyframe);
2518         next_config.copy_from(config);
2519
2520         config.prev_keyframe_position = prev_keyframe->position;
2521         config.next_keyframe_position = next_keyframe->position;
2522
2523         // if no previous keyframe exists, it should be start of the plugin, not start of the track
2524         if( config.next_keyframe_position == config.prev_keyframe_position )
2525                 config.next_keyframe_position = get_source_start() + get_total_len();
2526         if( config.prev_keyframe_position == 0 )
2527                 config.prev_keyframe_position = get_source_start();
2528 // printf("TitleMain::load_configuration 10 %d %d\n",
2529 // config.prev_keyframe_position,
2530 // config.next_keyframe_position);
2531
2532         config.interpolate(prev_config,
2533                 next_config,
2534                 (next_keyframe->position == prev_keyframe->position) ?
2535                         get_source_position() :
2536                         prev_keyframe->position,
2537                 (next_keyframe->position == prev_keyframe->position) ?
2538                         get_source_position() + 1 :
2539                         next_keyframe->position,
2540                 get_source_position());
2541
2542         if( !config.equivalent(old_config) )
2543                 return 1;
2544         return 0;
2545 }
2546
2547
2548 void TitleMain::save_data(KeyFrame *keyframe)
2549 {
2550         FileXML output;
2551
2552         output.set_shared_output(keyframe->get_data(), MESSAGESIZE);
2553         output.tag.set_title("TITLE");
2554         output.tag.set_property("FONT", config.font);
2555         output.tag.set_property("ENCODING", config.encoding);
2556         output.tag.set_property("STYLE", (int64_t)config.style);
2557         output.tag.set_property("SIZE", config.size);
2558         output.tag.set_property("COLOR", config.color);
2559         output.tag.set_property("ALPHA", config.alpha);
2560         output.tag.set_property("OUTLINE_SIZE", config.outline_size);
2561         output.tag.set_property("OUTLINE_COLOR", config.outline_color);
2562         output.tag.set_property("OUTLINE_ALPHA", config.outline_alpha);
2563         output.tag.set_property("COLOR_STROKE", config.color_stroke);
2564         output.tag.set_property("STROKE_WIDTH", config.stroke_width);
2565         output.tag.set_property("MOTION_STRATEGY", config.motion_strategy);
2566         output.tag.set_property("LOOP", config.loop);
2567         output.tag.set_property("LINE_PITCH", config.line_pitch);
2568         output.tag.set_property("PIXELS_PER_SECOND", config.pixels_per_second);
2569         output.tag.set_property("HJUSTIFICATION", config.hjustification);
2570         output.tag.set_property("VJUSTIFICATION", config.vjustification);
2571         output.tag.set_property("FADE_IN", config.fade_in);
2572         output.tag.set_property("FADE_OUT", config.fade_out);
2573         output.tag.set_property("TITLE_X", config.title_x);
2574         output.tag.set_property("TITLE_Y", config.title_y);
2575         output.tag.set_property("TITLE_W", config.title_w);
2576         output.tag.set_property("TITLE_H", config.title_h);
2577         output.tag.set_property("DROPSHADOW", config.dropshadow);
2578         output.tag.set_property("TIMECODE", config.timecode);
2579         output.tag.set_property("TIMECODEFORMAT", config.timecode_format);
2580         output.tag.set_property("WINDOW_W", config.window_w);
2581         output.tag.set_property("WINDOW_H", config.window_h);
2582         output.tag.set_property("DRAG", config.drag);
2583         output.tag.set_property("BACKGROUND", config.background);
2584         output.tag.set_property("BACKGROUND_PATH", config.background_path);
2585         output.tag.set_property("LOOP_PLAYBACK", config.loop_playback);
2586         output.append_tag();
2587         output.append_newline();
2588         char text[BCTEXTLEN];
2589         int text_len = BC_Resources::encode(
2590                 BC_Resources::wide_encoding, DEFAULT_ENCODING,
2591                 (char*)config.wtext, config.wlen*sizeof(wchar_t),
2592                 text, sizeof(text));
2593         output.append_text(text, text_len);
2594         output.tag.set_title("/TITLE");
2595         output.append_tag();
2596         output.append_newline();
2597         output.terminate_string();
2598 //printf("TitleMain::save_data 1\n%s\n", output.string);
2599 //printf("TitleMain::save_data 2\n%s\n", config.text);
2600 }
2601
2602 void TitleMain::read_data(KeyFrame *keyframe)
2603 {
2604         FileXML input;
2605
2606         input.set_shared_input(keyframe->get_data(), strlen(keyframe->get_data()));
2607
2608         int result = 0;
2609
2610         config.prev_keyframe_position = keyframe->position;
2611         while(!result)
2612         {
2613                 result = input.read_tag();
2614                 if( result ) break;
2615
2616                 if( input.tag.title_is("TITLE") ) {
2617                         input.tag.get_property("FONT", config.font);
2618                         input.tag.get_property("ENCODING", config.encoding);
2619                         config.style = input.tag.get_property("STYLE", (int64_t)config.style);
2620                         config.size = input.tag.get_property("SIZE", config.size);
2621                         config.color = input.tag.get_property("COLOR", config.color);
2622                         config.alpha = input.tag.get_property("ALPHA", config.alpha);
2623                         config.outline_size = input.tag.get_property("OUTLINE_SIZE", config.outline_size);
2624                         config.outline_color = input.tag.get_property("OUTLINE_COLOR", config.outline_color);
2625                         config.outline_alpha = input.tag.get_property("OUTLINE_ALPHA", config.outline_alpha);
2626                         config.color_stroke = input.tag.get_property("COLOR_STROKE", config.color_stroke);
2627                         config.stroke_width = input.tag.get_property("STROKE_WIDTH", config.stroke_width);
2628                         config.motion_strategy = input.tag.get_property("MOTION_STRATEGY", config.motion_strategy);
2629                         config.loop = input.tag.get_property("LOOP", config.loop);
2630                         config.line_pitch = input.tag.get_property("LINE_PITCH", config.line_pitch);
2631                         config.pixels_per_second = input.tag.get_property("PIXELS_PER_SECOND", config.pixels_per_second);
2632                         config.hjustification = input.tag.get_property("HJUSTIFICATION", config.hjustification);
2633                         config.vjustification = input.tag.get_property("VJUSTIFICATION", config.vjustification);
2634                         config.fade_in = input.tag.get_property("FADE_IN", config.fade_in);
2635                         config.fade_out = input.tag.get_property("FADE_OUT", config.fade_out);
2636                         config.title_x = input.tag.get_property("TITLE_X", config.title_x);
2637                         config.title_y = input.tag.get_property("TITLE_Y", config.title_y);
2638                         config.title_w = input.tag.get_property("TITLE_W", config.title_w);
2639                         config.title_h = input.tag.get_property("TITLE_H", config.title_h);
2640                         config.dropshadow = input.tag.get_property("DROPSHADOW", config.dropshadow);
2641                         config.timecode = input.tag.get_property("TIMECODE", config.timecode);
2642                         config.timecode_format = input.tag.get_property("TIMECODEFORMAT", config.timecode_format);
2643                         config.window_w = input.tag.get_property("WINDOW_W", config.window_w);
2644                         config.window_h = input.tag.get_property("WINDOW_H", config.window_h);
2645                         config.drag = input.tag.get_property("DRAG", config.drag);
2646                         config.background = input.tag.get_property("BACKGROUND", config.background);
2647                         input.tag.get_property("BACKGROUND_PATH", config.background_path);
2648                         config.loop_playback = input.tag.get_property("LOOP_PLAYBACK", config.loop_playback);
2649                         const char *text = input.read_text();
2650                         config.to_wtext(config.encoding, text, strlen(text)+1);
2651                 }
2652                 else if( input.tag.title_is("/TITLE") ) {
2653                         result = 1;
2654                 }
2655         }
2656 }
2657
2658 void TitleMain::insert_text(const char *txt, int pos)
2659 {
2660         int ilen = strlen(txt);
2661         wchar_t *wtext = config.wtext;
2662         int wsize = sizeof(config.wtext)-1;
2663         int wlen = config.wlen;
2664         if( pos < 0 ) pos = 0;
2665         if( pos > wlen ) pos = wlen;
2666
2667         for( int i=wlen-1, j=wlen+ilen-1; i>=pos; --i,--j ) {
2668                 if( j >= wsize ) continue;
2669                 wtext[j] = wtext[i];
2670         }
2671         for( int i=pos, j=0; j<ilen; ++i,++j ) {
2672                 if( i >= wsize ) break;
2673                 wtext[i] = txt[j];
2674         }
2675
2676         if( (wlen+=ilen) > wsize ) wlen = wsize;
2677         wtext[wlen] = 0;
2678         config.wlen = wlen;
2679 }
2680