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