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