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