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