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