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