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