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