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