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