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