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