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