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