comparison libass/ass_render.c @ 18937:9e95ac641e77

Initial libass release (without mencoder support).
author eugeni
date Fri, 07 Jul 2006 18:26:51 +0000
parents
children da05237044c2
comparison
equal deleted inserted replaced
18936:b80b0c115a24 18937:9e95ac641e77
1 #include "config.h"
2
3 #include <assert.h>
4 #include <math.h>
5 #include <stdint.h>
6 #include <ft2build.h>
7 #include FT_FREETYPE_H
8 #include FT_STROKER_H
9 #include FT_GLYPH_H
10 #include FT_SYNTHESIS_H
11
12 #include "mp_msg.h"
13
14 #include "ass.h"
15 #include "ass_cache.h"
16 #include "ass_utils.h"
17 #include "ass_fontconfig.h"
18
19 #include "libvo/sub.h" // for utf8_get_char
20
21 #define MAX_GLYPHS 1000
22 #define MAX_LINES 100
23
24 char *get_path(char *);
25
26 extern char *font_name;
27 #ifdef HAVE_FONTCONFIG
28 extern int font_fontconfig;
29 #else
30 static int font_fontconfig = 0;
31 #endif
32
33 struct ass_instance_s {
34 FT_Library library;
35 fc_instance_t* fontconfig_priv;
36 ass_settings_t settings;
37
38 ass_image_t* images_root; // rendering result is stored here
39 int n_images;
40 int max_images;
41 };
42
43 int no_more_font_messages = 0; // don't print font warnings
44
45 typedef enum {EF_NONE = 0, EF_KARAOKE, EF_KARAOKE_KF, EF_KARAOKE_KO} effect_t;
46
47 // describes a glyph
48 // glyph_info_t and text_info_t are used for text centering and word-wrapping operations
49 typedef struct glyph_info_s {
50 unsigned symbol;
51 FT_Glyph glyph;
52 FT_Glyph outline_glyph;
53 FT_BBox bbox;
54 FT_Vector pos;
55 char linebreak; // the first (leading) glyph of some line ?
56 uint32_t c1, c2, c3, c4; // colors
57 char bitmap; // bool
58 FT_Vector advance; // 26.6
59 effect_t effect_type;
60 int effect_timing;
61 int asc, desc; // font max ascender and descender
62 // int height;
63
64 glyph_hash_key_t hash_key;
65 } glyph_info_t;
66
67 typedef struct line_info_s {
68 int asc, desc;
69 } line_info_t;
70
71 typedef struct text_info_s {
72 glyph_info_t* glyphs;
73 int length;
74 line_info_t lines[MAX_LINES];
75 int n_lines;
76 int height;
77 } text_info_t;
78
79
80 // Renderer state.
81 // Values like current font face, color, screen position, clipping and so on are stored here.
82 typedef struct render_context_s {
83 ass_event_t* event;
84 ass_style_t* style;
85
86 FT_Face face;
87 char* font_path;
88 int font_size;
89
90 FT_Stroker stroker;
91 int alignment; // alignment overrides go here; if zero, style value will be used
92 double rotation;
93 enum { EVENT_NORMAL, // "normal" top-, sub- or mid- title
94 EVENT_POSITIONED // happens after pos(,), margins are ignored
95 } evt_type;
96 int pos_x, pos_y; // position
97 int org_x, org_y; // origin
98 double scale_x, scale_y;
99 int hspacing; // distance between letters, in pixels
100 double border; // outline width
101 uint32_t c1, c2, c3, c4; // colors(Primary, Secondary, so on) in RGBA
102 int clip_x0, clip_y0, clip_x1, clip_y1;
103 char detect_collisions;
104
105 effect_t effect_type;
106 int effect_timing;
107
108 // face properties
109 char* family;
110 unsigned bold;
111 unsigned italic;
112
113 } render_context_t;
114
115 // frame-global data
116 typedef struct frame_context_s {
117 ass_instance_t* ass_priv;
118 int width, height; // screen dimensions
119 int orig_height; // frame height ( = screen height - margins )
120 ass_track_t* track;
121 int add_bottom_margin; // additional margin, used to shift subtitles in case of collision
122 int add_top_margin;
123 long long time; // frame's timestamp, ms
124 double font_scale_x; // x scale applied to all glyphs to preserve text aspect ratio
125 } frame_context_t;
126
127 static ass_instance_t* ass_instance;
128 static ass_settings_t* global_settings;
129 static text_info_t text_info;
130 static render_context_t render_context;
131 static frame_context_t frame_context;
132
133 static void ass_lazy_track_init(void)
134 {
135 ass_track_t* track = frame_context.track;
136 if (track->PlayResX && track->PlayResY)
137 return;
138 if (!track->PlayResX && !track->PlayResY) {
139 mp_msg(MSGT_GLOBAL, MSGL_WARN, "Neither PlayResX nor PlayResY defined. Assuming 384x288. \n");
140 track->PlayResX = 384;
141 track->PlayResY = 288;
142 } else {
143 double orig_aspect = (global_settings->aspect * frame_context.height) / frame_context.orig_height;
144 if (!track->PlayResY) {
145 track->PlayResY = track->PlayResX / orig_aspect + .5;
146 mp_msg(MSGT_GLOBAL, MSGL_WARN, "PlayResY undefined, setting %d \n", track->PlayResY);
147 } else if (!track->PlayResX) {
148 track->PlayResX = track->PlayResY * orig_aspect + .5;
149 mp_msg(MSGT_GLOBAL, MSGL_WARN, "PlayResX undefined, setting %d \n", track->PlayResX);
150 }
151 }
152 }
153
154 ass_instance_t* ass_init(void)
155 {
156 char* family = 0;
157 char* path = 0;
158 char* fonts_path = 0;
159 int error;
160 fc_instance_t* fc_priv;
161 FT_Library ft;
162 ass_instance_t* priv;
163
164 if (font_fontconfig && font_name)
165 family = strdup(font_name);
166
167 if (!font_fontconfig && font_name)
168 path = strdup(font_name);
169 else
170 path = get_path("subfont.ttf");
171
172 fonts_path = get_path("fonts");
173
174 fc_priv = fontconfig_init(fonts_path, family, path);
175
176 free(fonts_path);
177 if (path) free(path);
178 if (family) free(family);
179
180 if (!fc_priv)
181 return 0;
182
183 error = FT_Init_FreeType( &ft );
184 if ( error ) {
185 mp_msg(MSGT_GLOBAL, MSGL_FATAL, "FT_Init_FreeType failed\n");
186 fontconfig_done(fc_priv);
187 return 0;
188 }
189
190 priv = calloc(1, sizeof(ass_instance_t));
191 if (!priv) {
192 FT_Done_FreeType(ft);
193 fontconfig_done(fc_priv);
194 return 0;
195 }
196 priv->library = ft;
197 priv->fontconfig_priv = fc_priv;
198 // images_root and related stuff is zero-filled in calloc
199
200 ass_face_cache_init();
201 ass_glyph_cache_init();
202
203 text_info.glyphs = calloc(MAX_GLYPHS, sizeof(glyph_info_t));
204
205 return priv;
206 }
207
208 void ass_done(ass_instance_t* priv)
209 {
210 ass_face_cache_done();
211 ass_glyph_cache_done();
212 if (priv && priv->library) FT_Done_FreeType(priv->library);
213 if (priv && priv->fontconfig_priv) fontconfig_done(priv->fontconfig_priv);
214 if (priv) free(priv);
215 if (text_info.glyphs) free(text_info.glyphs);
216 }
217
218 /**
219 * \brief Create a new ass_image_t and append it to images_root
220 * Parameters are the same as ass_image_t fields.
221 */
222 static void my_draw_bitmap(unsigned char* bitmap, int bitmap_w, int bitmap_h, int stride, int dst_x, int dst_y, uint32_t color)
223 {
224 ass_instance_t* priv = ass_instance;
225 ass_image_t* img;
226
227 assert(priv->n_images <= priv->max_images);
228 if (priv->n_images == priv->max_images) {
229 if (!priv->max_images) priv->max_images = 100;
230 else priv->max_images *= 2;
231 priv->images_root = (ass_image_t*)realloc(priv->images_root, priv->max_images * sizeof(ass_image_t));
232 }
233 assert(priv->images_root);
234 img = priv->images_root + priv->n_images;
235
236 img->w = bitmap_w;
237 img->h = bitmap_h;
238 img->stride = stride;
239 img->bitmap = bitmap;
240 img->color = color;
241 img->dst_x = dst_x;
242 img->dst_y = dst_y;
243
244 priv->n_images++;
245 }
246
247 /**
248 * \brief convert bitmap glyph into ass_image_t struct(s)
249 * \param bit freetype bitmap glyph, FT_PIXEL_MODE_GRAY
250 * \param dst_x bitmap x coordinate in video frame
251 * \param dst_y bitmap y coordinate in video frame
252 * \param color first color, RGBA
253 * \param color2 second color, RGBA
254 * \param brk x coordinate relative to glyph origin, color is used to the left of brk, color2 - to the right
255 * Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
256 */
257 static int render_glyph(FT_BitmapGlyph bit, int dst_x, int dst_y, uint32_t color, uint32_t color2, int brk)
258 {
259 // brk is relative to dst_x
260 // color = color left of brk
261 // color2 = color right of brk
262 int b_x0, b_y0, b_x1, b_y1; // visible part of the bitmap
263 int clip_x0, clip_y0, clip_x1, clip_y1;
264 int tmp;
265 FT_Bitmap* bitmap;
266
267 bitmap = &(bit->bitmap);
268 dst_x += bit->left;
269 dst_y -= bit->top;
270 brk -= bit->left;
271
272 if (bitmap->pixel_mode != FT_PIXEL_MODE_GRAY) {
273 mp_msg(MSGT_GLOBAL, MSGL_WARN, "Unsupported pixel mode: %d\n", (int)(bitmap->pixel_mode));
274 return 1;
275 }
276
277 // clipping
278 clip_x0 = render_context.clip_x0;
279 clip_y0 = render_context.clip_y0;
280 clip_x1 = render_context.clip_x1;
281 clip_y1 = render_context.clip_y1;
282 b_x0 = 0;
283 b_y0 = 0;
284 b_x1 = bitmap->width;
285 b_y1 = bitmap->rows;
286
287 tmp = dst_x - clip_x0;
288 if (tmp < 0) {
289 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip left\n");
290 b_x0 = - tmp;
291 }
292 tmp = dst_y - clip_y0;
293 if (tmp < 0) {
294 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip top\n");
295 b_y0 = - tmp;
296 }
297 tmp = clip_x1 - dst_x - bitmap->width;
298 if (tmp < 0) {
299 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip right\n");
300 b_x1 = bitmap->width + tmp;
301 }
302 tmp = clip_y1 - dst_y - bitmap->rows;
303 if (tmp < 0) {
304 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip bottom\n");
305 b_y1 = bitmap->rows + tmp;
306 }
307
308 if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
309 return 0;
310
311 if (brk > b_x0) { // draw left part
312 if (brk > b_x1) brk = b_x1;
313 my_draw_bitmap(bitmap->buffer + bitmap->pitch * b_y0 + b_x0,
314 brk - b_x0, b_y1 - b_y0, bitmap->pitch,
315 dst_x + b_x0, dst_y + b_y0, color);
316 }
317 if (brk < b_x1) { // draw right part
318 if (brk < b_x0) brk = b_x0;
319 my_draw_bitmap(bitmap->buffer + bitmap->pitch * b_y0 + brk,
320 b_x1 - brk, b_y1 - b_y0, bitmap->pitch,
321 dst_x + brk, dst_y + b_y0, color2);
322
323 }
324 return 0;
325 }
326
327 /**
328 * \brief Render text_info_t struct into ass_images_t list
329 * Rasterize glyphs and put them in glyph cache.
330 */
331 static int render_text(text_info_t* text_info, int dst_x, int dst_y)
332 {
333 int pen_x, pen_y;
334 int error, error2;
335 int i;
336 FT_Glyph image;
337 FT_BitmapGlyph bit;
338 glyph_hash_val_t hash_val;
339
340 for (i = 0; i < text_info->length; ++i) {
341 if (text_info->glyphs[i].bitmap != 1) {
342 if ((text_info->glyphs[i].symbol == '\n') || (text_info->glyphs[i].symbol == 0))
343 continue;
344 error = FT_Glyph_To_Bitmap( &(text_info->glyphs[i].outline_glyph), FT_RENDER_MODE_NORMAL, 0, 1);
345 error2 = FT_Glyph_To_Bitmap( &(text_info->glyphs[i].glyph), FT_RENDER_MODE_NORMAL, 0, 1);
346
347 if (error || error2) {
348 FT_Done_Glyph(text_info->glyphs[i].outline_glyph);
349 FT_Done_Glyph(text_info->glyphs[i].glyph);
350 mp_msg(MSGT_GLOBAL, MSGL_WARN, "FT_Glyph_To_Bitmap error %d %d, symbol %d, index %d\n",
351 error, error2, text_info->glyphs[i].symbol, text_info->glyphs[i].hash_key.index);
352 text_info->glyphs[i].symbol = 0; // do not render
353 continue;
354 }
355 // cache
356 text_info->glyphs[i].hash_key.bitmap = 1; // other hash_key fields were set in get_glyph()
357 hash_val.bbox_scaled = text_info->glyphs[i].bbox;
358 hash_val.outline_glyph = text_info->glyphs[i].outline_glyph;
359 hash_val.glyph = text_info->glyphs[i].glyph;
360 hash_val.advance.x = text_info->glyphs[i].advance.x;
361 hash_val.advance.y = text_info->glyphs[i].advance.y;
362 cache_add_glyph(&(text_info->glyphs[i].hash_key), &hash_val);
363 }
364 }
365
366 for (i = 0; i < text_info->length; ++i) {
367 glyph_info_t* info = text_info->glyphs + i;
368 if ((info->symbol == 0) || (info->symbol == '\n'))
369 continue;
370
371 pen_x = dst_x + info->pos.x;
372 pen_y = dst_y + info->pos.y;
373 image = info->outline_glyph;
374 bit = (FT_BitmapGlyph)image;
375
376 if ((info->effect_type == EF_KARAOKE_KO) && (info->effect_timing <= info->bbox.xMax)) {
377 // do nothing
378 } else
379 render_glyph(bit, pen_x, pen_y, info->c3, 0, 1000000);
380 }
381 for (i = 0; i < text_info->length; ++i) {
382 glyph_info_t* info = text_info->glyphs + i;
383 if ((info->symbol == 0) || (info->symbol == '\n'))
384 continue;
385
386 pen_x = dst_x + info->pos.x;
387 pen_y = dst_y + info->pos.y;
388 image = info->glyph;
389 bit = (FT_BitmapGlyph)image;
390
391 if ((info->effect_type == EF_KARAOKE) || (info->effect_type == EF_KARAOKE_KO)) {
392 if (info->effect_timing > info->bbox.xMax)
393 render_glyph(bit, pen_x, pen_y, info->c1, 0, 1000000);
394 else
395 render_glyph(bit, pen_x, pen_y, info->c2, 0, 1000000);
396 } else if (info->effect_type == EF_KARAOKE_KF) {
397 render_glyph(bit, pen_x, pen_y, info->c1, info->c2, info->effect_timing);
398 } else
399 render_glyph(bit, pen_x, pen_y, info->c1, 0, 1000000);
400 }
401
402 return 0;
403 }
404
405 /**
406 * \brief Mapping between script and screen coordinates
407 */
408 static int x2scr(int x) {
409 return x*frame_context.width / frame_context.track->PlayResX;
410 }
411 /**
412 * \brief Mapping between script and screen coordinates
413 */
414 static int y2scr(int y) {
415 return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_margin;
416 }
417 // the same for toptitles
418 static int y2scr_top(int y) {
419 return y * frame_context.orig_height / frame_context.track->PlayResY;
420 }
421 // the same for subtitles
422 static int y2scr_sub(int y) {
423 return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_margin + global_settings->bottom_margin;
424 }
425
426 static void vmirror_bbox(FT_BBox* orig, FT_BBox* pbbox) {
427 pbbox->xMin = orig->xMin;
428 pbbox->xMax = orig->xMax;
429 pbbox->yMin = - orig->yMax;
430 pbbox->yMax = - orig->yMin;
431 }
432
433 static void compute_string_bbox( text_info_t* info, FT_BBox *abbox ) {
434 FT_BBox bbox;
435 int n;
436
437 /* initialize string bbox to "empty" values */
438 bbox.xMin = bbox.yMin = 32000;
439 bbox.xMax = bbox.yMax = -32000;
440
441 /* for each glyph image, compute its bounding box, */
442 /* translate it, and grow the string bbox */
443 for ( n = 0; n < info->length; n++ ) {
444 FT_BBox glyph_bbox;
445 vmirror_bbox( &(info->glyphs[n].bbox), &glyph_bbox );
446 glyph_bbox.xMin += info->glyphs[n].pos.x;
447 glyph_bbox.xMax += info->glyphs[n].pos.x;
448 glyph_bbox.yMin += info->glyphs[n].pos.y;
449 glyph_bbox.yMax += info->glyphs[n].pos.y;
450 if ( glyph_bbox.xMin < bbox.xMin ) bbox.xMin = glyph_bbox.xMin;
451 if ( glyph_bbox.yMin < bbox.yMin ) bbox.yMin = glyph_bbox.yMin;
452 if ( glyph_bbox.xMax > bbox.xMax ) bbox.xMax = glyph_bbox.xMax;
453 if ( glyph_bbox.yMax > bbox.yMax ) bbox.yMax = glyph_bbox.yMax;
454 }
455
456 /* check that we really grew the string bbox */
457 if ( bbox.xMin > bbox.xMax ) {
458 bbox.xMin = 0;
459 bbox.yMin = 0;
460 bbox.xMax = 0;
461 bbox.yMax = 0;
462 }
463
464 /* return string bbox */
465 *abbox = bbox;
466 }
467
468
469 /**
470 * \brief Check if starting part of (*p) matches sample. If true, shift p to the first symbol after the matching part.
471 */
472 static inline int mystrcmp(char** p, char* sample) {
473 int len = strlen(sample);
474 if (strncmp(*p, sample, len) == 0) {
475 (*p) += len;
476 return 1;
477 } else
478 return 0;
479 }
480
481 static void change_font_size(int sz)
482 {
483 double size = (double)sz * global_settings->font_size_coeff * 0.8;
484 size *= frame_context.height;
485 size /= frame_context.track->PlayResY;
486
487 if (size < 1)
488 size = 1;
489 else if (size > frame_context.height * 2)
490 size = frame_context.height * 2;
491
492 FT_Set_Pixel_Sizes(render_context.face, 0, size);
493
494 render_context.font_size = sz;
495 }
496
497 /**
498 * \brief Change current font, using setting from render_context.
499 */
500 static void update_font(void)
501 {
502 int error;
503 unsigned val;
504 ass_instance_t* priv = frame_context.ass_priv;
505 face_desc_t desc;
506 desc.family = strdup(render_context.family);
507
508 val = render_context.bold;
509 // 0 = normal, 1 = bold, >1 = exact weight
510 if (val == 0) val = 80; // normal
511 else if (val == 1) val = 200; // bold
512 desc.bold = val;
513
514 val = render_context.italic;
515 if (val == 0) val = 0; // normal
516 else if (val == 1) val = 110; //italic
517 desc.italic = val;
518
519 error = ass_new_face(priv->library, priv->fontconfig_priv, &desc, &(render_context.face));
520 if (error) {
521 render_context.face = 0;
522 }
523
524 if (render_context.face)
525 {
526 change_font_size(render_context.font_size);
527 }
528 }
529
530 /**
531 * \brief Change border width
532 */
533 static void change_border(double border)
534 {
535 if (!render_context.stroker) {
536 if (!no_more_font_messages)
537 mp_msg(MSGT_GLOBAL, MSGL_WARN, "No stroker!\n");
538 } else {
539 render_context.border = border;
540 FT_Stroker_Set( render_context.stroker,
541 (int)(64 * border),
542 FT_STROKER_LINECAP_ROUND,
543 FT_STROKER_LINEJOIN_ROUND,
544 0 );
545 }
546 }
547
548 #define _r(c) ((c)>>24)
549 #define _g(c) (((c)>>16)&0xFF)
550 #define _b(c) (((c)>>8)&0xFF)
551 #define _a(c) ((c)&0xFF)
552
553 /**
554 * \brief Calculate a weighted average of two colors
555 * calculates c1*(1-a) + c2*a, but separately for each component except alpha
556 */
557 static void change_color(uint32_t* var, uint32_t new, double pwr)
558 {
559 (*var)= ((uint32_t)(_r(*var) * (1 - pwr) + _r(new) * pwr) << 24) +
560 ((uint32_t)(_g(*var) * (1 - pwr) + _g(new) * pwr) << 16) +
561 ((uint32_t)(_b(*var) * (1 - pwr) + _b(new) * pwr) << 8) +
562 _a(*var);
563 }
564
565 // like change_color, but for alpha component only
566 static void change_alpha(uint32_t* var, uint32_t new, double pwr)
567 {
568 *var = (_r(*var) << 24) + (_g(*var) << 16) + (_b(*var) << 8) + (_a(*var) * (1 - pwr) + _a(new) * pwr);
569 }
570
571
572 /**
573 * \brief Calculate alpha value by piecewise linear function
574 * Used for \fad, \fade implementation.
575 */
576 static void interpolate_alpha(long long now,
577 long long t1, long long t2, long long t3, long long t4,
578 unsigned a1, unsigned a2, unsigned a3)
579 {
580 unsigned a;
581 double cf;
582 if (now <= t1) {
583 a = a1;
584 } else if (now >= t4) {
585 a = a3;
586 } else if (now < t2) { // and > t1
587 cf = ((double)(now - t1)) / (t2 - t1);
588 a = a1 * (1 - cf) + a2 * cf;
589 } else if (now > t3) {
590 cf = ((double)(now - t3)) / (t4 - t3);
591 a = a2 * (1 - cf) + a3 * cf;
592 } else { // t2 <= now <= t3
593 a = a2;
594 }
595
596
597 change_alpha(&render_context.c1, a, 1.);
598 change_alpha(&render_context.c2, a, 1.);
599 change_alpha(&render_context.c3, a, 1.);
600 change_alpha(&render_context.c4, a, 1.);
601 }
602
603 /**
604 * \brief Parse style override tag.
605 * \param p string to parse
606 * \param pwr multiplier for some tag effects (comes from \t tags)
607 */
608 static char* parse_tag(char* p, double pwr) {
609 #define skip_all(x) if (*p == (x)) ++p; else { \
610 while ((*p != (x)) && (*p != '}') && (*p != 0)) {++p;} }
611 #define skip(x) if (*p == (x)) ++p; else { return p; }
612
613 skip_all('\\');
614 if ((*p == '}') || (*p == 0))
615 return p;
616
617 if (mystrcmp(&p, "fsc")) {
618 char tp = *p++;
619 double val;
620 if (tp == 'x') {
621 if (mystrtod(&p, &val)) {
622 val /= 100;
623 render_context.scale_x = (val - 1.) * pwr + 1.;
624 } else
625 render_context.scale_x = render_context.style->ScaleX;
626 } else if (tp == 'y') {
627 if (mystrtod(&p, &val)) {
628 val /= 100;
629 render_context.scale_y = (val - 1.) * pwr + 1.;
630 } else
631 render_context.scale_y = render_context.style->ScaleY;
632 }
633 } else if (mystrcmp(&p, "fsp")) {
634 int val;
635 if (mystrtoi(&p, 10, &val))
636 render_context.hspacing = val * pwr;
637 else
638 render_context.hspacing = 0;
639 } else if (mystrcmp(&p, "fs")) {
640 int val;
641 if (mystrtoi(&p, 10, &val))
642 val = render_context.font_size * ( 1 - pwr ) + val * pwr;
643 else
644 val = render_context.style->FontSize;
645 if (render_context.face)
646 change_font_size(val);
647 } else if (mystrcmp(&p, "bord")) {
648 double val;
649 if (mystrtod(&p, &val))
650 val = render_context.border * ( 1 - pwr ) + val * pwr;
651 else
652 val = (render_context.style->BorderStyle == 1) ? render_context.style->Outline : 1.;
653 change_border(val);
654 } else if (mystrcmp(&p, "move")) {
655 int x1, x2, y1, y2;
656 long long t1, delta_t, t;
657 int x, y;
658 double k;
659 skip('(');
660 x1 = strtol(p, &p, 10);
661 skip(',');
662 y1 = strtol(p, &p, 10);
663 skip(',');
664 x2 = strtol(p, &p, 10);
665 skip(',');
666 y2 = strtol(p, &p, 10);
667 skip(')'); // FIXME: 2 more optional args
668 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "movement: (%d, %d) -> (%d, %d)\n", x1, y1, x2, y2);
669 t1 = render_context.event->Start;
670 delta_t = render_context.event->Duration;
671 t = frame_context.time; // FIXME: move to render_context
672 k = ((double)(t - t1)) / delta_t;
673 x = k * (x2 - x1) + x1;
674 y = k * (y2 - y1) + y1;
675 render_context.pos_x = x;
676 render_context.pos_y = y;
677 render_context.detect_collisions = 0;
678 render_context.evt_type = EVENT_POSITIONED;
679 } else if (mystrcmp(&p, "frx") || mystrcmp(&p, "fry")) {
680 int val;
681 mystrtoi(&p, 10, &val);
682 mp_msg(MSGT_GLOBAL, MSGL_V, "frx/fry unimplemented \n");
683 } else if (mystrcmp(&p, "frz") || mystrcmp(&p, "fr")) {
684 double angle;
685 int val;
686 val = strtol(p, &p, 10);
687 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "setting rotation to %.2f\n", val * pwr);
688 angle = M_PI * val / 180;
689 render_context.rotation = angle * pwr;
690 } else if (mystrcmp(&p, "fn")) {
691 char* start = p;
692 char* family;
693 skip_all('\\');
694 family = malloc(p - start + 1);
695 strncpy(family, start, p - start);
696 family[p - start] = '\0';
697 if (render_context.family)
698 free(render_context.family);
699 render_context.family = family;
700 update_font();
701 } else if (mystrcmp(&p, "alpha")) {
702 uint32_t val;
703 if (strtocolor(&p, &val)) {
704 unsigned char a = val >> 24;
705 change_alpha(&render_context.c1, a, pwr);
706 change_alpha(&render_context.c2, a, pwr);
707 change_alpha(&render_context.c3, a, pwr);
708 change_alpha(&render_context.c4, a, pwr);
709 } else {
710 change_alpha(&render_context.c1, render_context.style->PrimaryColour, pwr);
711 change_alpha(&render_context.c2, render_context.style->SecondaryColour, pwr);
712 change_alpha(&render_context.c3, render_context.style->OutlineColour, pwr);
713 change_alpha(&render_context.c4, render_context.style->BackColour, pwr);
714 }
715 // FIXME: simplify
716 } else if (mystrcmp(&p, "an")) {
717 int val = strtol(p, &p, 10);
718 int v = (val - 1) / 3; // 0, 1 or 2 for vertical alignment
719 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "an %d\n", val);
720 if (v != 0) v = 3 - v;
721 val = ((val - 1) % 3) + 1; // horizontal alignment
722 val += v*4;
723 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "align %d\n", val);
724 render_context.alignment = val;
725 } else if (mystrcmp(&p, "a")) {
726 int val = strtol(p, &p, 10);
727 render_context.alignment = val;
728 } else if (mystrcmp(&p, "pos")) {
729 int v1, v2;
730 skip('(');
731 v1 = strtol(p, &p, 10);
732 skip(',');
733 v2 = strtol(p, &p, 10);
734 skip(')');
735 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "pos(%d, %d)\n", v1, v2);
736 render_context.evt_type = EVENT_POSITIONED;
737 render_context.detect_collisions = 0;
738 render_context.pos_x = v1;
739 render_context.pos_y = v2;
740 } else if (mystrcmp(&p, "fade")) {
741 int a1, a2, a3, v1, v2, v3, v4;
742 skip('(');
743 a1 = strtol(p, &p, 10);
744 skip(',');
745 a2 = strtol(p, &p, 10);
746 skip(',');
747 a3 = strtol(p, &p, 10);
748 skip(',');
749 v1 = strtol(p, &p, 10);
750 skip(',');
751 v2 = strtol(p, &p, 10);
752 skip(',');
753 v3 = strtol(p, &p, 10);
754 skip(',');
755 v4 = strtol(p, &p, 10);
756 skip(')');
757 interpolate_alpha(frame_context.time - render_context.event->Start, v1, v2, v3, v4, a1, a2, a3);
758 } else if (mystrcmp(&p, "fad")) {
759 int v1, v2;
760 long long now, t1, t2, t3, t4;
761 skip('(');
762 v1 = strtol(p, &p, 10);
763 skip(',');
764 v2 = strtol(p, &p, 10);
765 skip(')');
766 now = frame_context.time;
767 t1 = render_context.event->Start;
768 t2 = t1 + v1;
769 t4 = render_context.event->Start + render_context.event->Duration;
770 t3 = t4 - v2;
771 interpolate_alpha(now, t1, t2, t3, t4, 0xFF, 0, 0xFF);
772 } else if (mystrcmp(&p, "org")) {
773 int v1, v2;
774 skip('(');
775 v1 = strtol(p, &p, 10);
776 skip(',');
777 v2 = strtol(p, &p, 10);
778 skip(')');
779 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "org(%d, %d)\n", v1, v2);
780 // render_context.evt_type = EVENT_POSITIONED;
781 render_context.org_x = v1;
782 render_context.org_y = v2;
783 } else if (mystrcmp(&p, "t")) {
784 double v[3];
785 int v1, v2;
786 double v3;
787 int cnt;
788 long long t1, t2, t, delta_t;
789 double k;
790 skip('(');
791 for (cnt = 0; cnt < 3; ++cnt) {
792 if (*p == '\\')
793 break;
794 v[cnt] = strtod(p, &p);
795 skip(',');
796 }
797 if (cnt == 3) {
798 v1 = v[0]; v2 = v[1]; v3 = v[2];
799 } else if (cnt == 2) {
800 v1 = v[0]; v2 = v[1]; v3 = 1.;
801 } else if (cnt == 1) {
802 v1 = 0; v2 = render_context.event->Duration; v3 = v[0];
803 } else { // cnt == 0
804 v1 = 0; v2 = render_context.event->Duration; v3 = 1.;
805 }
806 render_context.detect_collisions = 0;
807 t1 = v1;
808 t2 = v2;
809 delta_t = v2 - v1;
810 t = frame_context.time - render_context.event->Start; // FIXME: move to render_context
811 if (t < t1)
812 k = 0.;
813 else if (t > t2)
814 k = 1.;
815 else k = ((double)(t - t1)) / delta_t;
816 while (*p == '\\')
817 p = parse_tag(p, k); // maybe k*pwr ? no, specs forbid nested \t's
818 skip_all(')'); // FIXME: better skip(')'), but much more tags support required
819 } else if (mystrcmp(&p, "clip")) {
820 int x0, y0, x1, y1;
821 int res = 1;
822 skip('(');
823 res &= mystrtoi(&p, 10, &x0);
824 skip(',');
825 res &= mystrtoi(&p, 10, &y0);
826 skip(',');
827 res &= mystrtoi(&p, 10, &x1);
828 skip(',');
829 res &= mystrtoi(&p, 10, &y1);
830 skip(')');
831 if (res) {
832 render_context.clip_x0 = render_context.clip_x0 * (1-pwr) + x0 * pwr;
833 render_context.clip_x1 = render_context.clip_x1 * (1-pwr) + x1 * pwr;
834 render_context.clip_y0 = render_context.clip_y0 * (1-pwr) + y0 * pwr;
835 render_context.clip_y1 = render_context.clip_y1 * (1-pwr) + y1 * pwr;
836 } else {
837 render_context.clip_x0 = 0;
838 render_context.clip_y0 = 0;
839 render_context.clip_x1 = frame_context.track->PlayResX;
840 render_context.clip_y1 = frame_context.track->PlayResY;
841 }
842 } else if (mystrcmp(&p, "c")) {
843 uint32_t val;
844 if (!strtocolor(&p, &val))
845 val = render_context.style->PrimaryColour;
846 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "color: %X\n", val);
847 change_color(&render_context.c1, val, pwr);
848 } else if ((*p >= '1') && (*p <= '4') && (++p) && (mystrcmp(&p, "c") || mystrcmp(&p, "a"))) {
849 char n = *(p-2);
850 char cmd = *(p-1);
851 uint32_t* pcolor;
852 uint32_t val;
853 assert((n >= '1') && (n <= '4'));
854 if (!strtocolor(&p, &val))
855 switch(n) {
856 case '1': val = render_context.style->PrimaryColour; break;
857 case '2': val = render_context.style->SecondaryColour; break;
858 case '3': val = render_context.style->OutlineColour; break;
859 case '4': val = render_context.style->BackColour; break;
860 default : val = 0; break; // impossible due to assert; avoid compilation warning
861 }
862 switch (n) {
863 case '1': pcolor = &render_context.c1; break;
864 case '2': pcolor = &render_context.c2; break;
865 case '3': pcolor = &render_context.c3; break;
866 case '4': pcolor = &render_context.c4; break;
867 default : pcolor = 0; break;
868 }
869 switch (cmd) {
870 case 'c': change_color(pcolor, val, pwr); break;
871 case 'a': change_alpha(pcolor, val >> 24, pwr); break;
872 default: mp_msg(MSGT_GLOBAL, MSGL_WARN, "Bad command: %c%c\n", n, cmd); break;
873 }
874 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "single c/a at %f: %c%c = %X \n", pwr, n, cmd, *pcolor);
875 } else if (mystrcmp(&p, "r")) {
876 render_context.c1 = render_context.style->PrimaryColour;
877 render_context.c2 = render_context.style->SecondaryColour;
878 render_context.c3 = render_context.style->OutlineColour;
879 render_context.c4 = render_context.style->BackColour;
880 render_context.font_size = render_context.style->FontSize;
881
882 if (render_context.family)
883 free(render_context.family);
884 render_context.family = strdup(render_context.style->FontName);
885 render_context.bold = - render_context.style->Bold;
886 render_context.italic = - render_context.style->Italic;
887 update_font();
888
889 if (render_context.stroker) {
890 double border = (render_context.style->BorderStyle == 1) ? render_context.style->Outline : 1.;
891 change_border(border);
892 }
893 render_context.scale_x = render_context.style->ScaleX;
894 render_context.scale_y = render_context.style->ScaleY;
895 render_context.hspacing = 0; // FIXME
896
897 // FIXME: does not reset unsupported attributes.
898 } else if (mystrcmp(&p, "be")) {
899 int val;
900 mystrtoi(&p, 10, &val);
901 mp_msg(MSGT_GLOBAL, MSGL_V, "be unimplemented \n");
902 } else if (mystrcmp(&p, "b")) {
903 int b;
904 if (mystrtoi(&p, 10, &b))
905 render_context.bold = b;
906 else
907 render_context.bold = - render_context.style->Bold;
908 update_font();
909 } else if (mystrcmp(&p, "i")) {
910 int i;
911 if (mystrtoi(&p, 10, &i))
912 render_context.italic = i;
913 else
914 render_context.italic = - render_context.style->Italic;
915 update_font();
916 } else if (mystrcmp(&p, "kf") || mystrcmp(&p, "K")) {
917 int val = strtol(p, &p, 10);
918 render_context.effect_type = EF_KARAOKE_KF;
919 render_context.effect_timing = val * 10;
920 } else if (mystrcmp(&p, "ko")) {
921 int val = strtol(p, &p, 10);
922 render_context.effect_type = EF_KARAOKE_KO;
923 render_context.effect_timing = val * 10;
924 } else if (mystrcmp(&p, "k")) {
925 int val = strtol(p, &p, 10);
926 render_context.effect_type = EF_KARAOKE;
927 render_context.effect_timing = val * 10;
928 }
929
930 return p;
931
932 #undef skip
933 #undef skip_all
934 }
935
936 /**
937 * \brief Get next ucs4 char from string, parsing and executing style overrides
938 * \param str string pointer
939 * \return ucs4 code of the next char
940 * On return str points to the unparsed part of the string
941 */
942 static unsigned get_next_char(char** str)
943 {
944 char* p = *str;
945 unsigned chr;
946 if (*p == '{') { // '\0' goes here
947 p++;
948 while (1) {
949 p = parse_tag(p, 1.);
950 if (*p == '}') { // end of tag
951 p++;
952 if (*p == '{') {
953 p++;
954 continue;
955 } else
956 break;
957 } else if (*p != '\\')
958 mp_msg(MSGT_GLOBAL, MSGL_V, "Unable to parse: \"%s\" \n", p);
959 if (*p == 0)
960 break;
961 }
962 }
963 if (*p == '\t') {
964 ++p;
965 *str = p;
966 return ' ';
967 }
968 if (*p == '\\') {
969 if ((*(p+1) == 'N') || ((*(p+1) == 'n') && (frame_context.track->WrapStyle == 2))) {
970 p += 2;
971 *str = p;
972 return '\n';
973 } else if (*(p+1) == 'n') {
974 p += 2;
975 *str = p;
976 return ' ';
977 }
978 }
979 chr = utf8_get_char(&p);
980 *str = p;
981 return chr;
982 }
983
984 /**
985 * \brief Start new event. Reset render_context.
986 */
987 static int init_render_context(ass_event_t* event)
988 {
989 int error;
990
991 // init render_context
992 render_context.event = event;
993 render_context.style = frame_context.track->styles + event->Style;
994
995 render_context.font_size = render_context.style->FontSize;
996 render_context.evt_type = EVENT_NORMAL;
997 render_context.alignment = 0;
998 render_context.rotation = 0.;
999 render_context.pos_x = 0;
1000 render_context.pos_y = 0;
1001 render_context.org_x = 0;
1002 render_context.org_y = 0;
1003 render_context.scale_x = render_context.style->ScaleX;
1004 render_context.scale_y = render_context.style->ScaleY;
1005 render_context.hspacing = 0;
1006 render_context.c1 = render_context.style->PrimaryColour;
1007 render_context.c2 = render_context.style->SecondaryColour;
1008 render_context.c3 = render_context.style->OutlineColour;
1009 render_context.c4 = render_context.style->BackColour;
1010 render_context.clip_x0 = 0;
1011 render_context.clip_y0 = 0;
1012 render_context.clip_x1 = frame_context.track->PlayResX;
1013 render_context.clip_y1 = frame_context.track->PlayResY;
1014 render_context.detect_collisions = 1;
1015
1016 if (render_context.family)
1017 free(render_context.family);
1018 render_context.family = strdup(render_context.style->FontName);
1019 render_context.bold = - render_context.style->Bold; // style value for bold text is -1
1020 render_context.italic = - render_context.style->Italic;
1021
1022 update_font();
1023
1024 if (render_context.face) {
1025 #if (FREETYPE_MAJOR > 2) || ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR > 1))
1026 error = FT_Stroker_New( ass_instance->library, &render_context.stroker );
1027 #else // < 2.2
1028 error = FT_Stroker_New( render_context.face->memory, &render_context.stroker );
1029 #endif
1030 if ( error ) {
1031 mp_msg(MSGT_GLOBAL, MSGL_V, "failed to get stroker\n");
1032 render_context.stroker = 0;
1033 } else {
1034 // FIXME: probably wrong when render_context.Border == 3
1035 double border = (render_context.style->BorderStyle == 1) ? render_context.style->Outline : 1.;
1036 change_border(border);
1037 }
1038 }
1039
1040 return 0;
1041 }
1042
1043 static int free_render_context(void)
1044 {
1045 if (render_context.stroker != 0) {
1046 FT_Stroker_Done(render_context.stroker);
1047 render_context.stroker = 0;
1048 }
1049 return 0;
1050 }
1051
1052 /**
1053 * \brief Get normal and outline glyphs from cache (if possible) or font face
1054 * \param index face glyph index
1055 * \param symbol ucs4 char
1056 * \param info out: struct filled with extracted data
1057 * \param advance advance vector of the extracted glyph
1058 * \return 0 on success
1059 */
1060 static int get_glyph(int index, int symbol, glyph_info_t* info, FT_Vector* advance)
1061 {
1062 int error;
1063 glyph_hash_val_t* val;
1064 glyph_hash_key_t* key = &(info->hash_key);
1065
1066 key->face = render_context.face;
1067 key->size = render_context.font_size;
1068 key->index = index;
1069 key->outline = (render_context.border * 0xFFFF); // convert to 16.16
1070 key->scale_x = (render_context.scale_x * 0xFFFF);
1071 key->scale_y = (render_context.scale_y * 0xFFFF);
1072 key->angle = (render_context.rotation * 0xFFFF);
1073 key->advance = *advance;
1074 key->bold = render_context.bold;
1075 key->italic = render_context.italic;
1076
1077 key->bitmap = 1; // looking for bitmap glyph
1078
1079
1080 val = cache_find_glyph(key);
1081 // val = 0;
1082
1083 if (val) {
1084 // bitmap glyph found, no need for FT_Glyph_Copy
1085 info->glyph = val->glyph;
1086 info->outline_glyph = val->outline_glyph;
1087 info->bbox = val->bbox_scaled;
1088 info->advance.x = val->advance.x;
1089 info->advance.y = val->advance.y;
1090 info->bitmap = 1; // bitmap glyph
1091
1092 return 0;
1093 }
1094
1095 // not found, get a new outline glyph from face
1096 // mp_msg(MSGT_GLOBAL, MSGL_INFO, "miss, index = %d, symbol = %c, adv = (%d, %d)\n", index, symbol, advance->x, advance->y);
1097
1098 error = FT_Load_Glyph(render_context.face, index, FT_LOAD_NO_BITMAP );
1099 if (error) {
1100 mp_msg(MSGT_GLOBAL, MSGL_WARN, "Error loading glyph\n");
1101 return error;
1102 }
1103
1104 #if (FREETYPE_MAJOR > 2) || \
1105 ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR >= 2)) || \
1106 ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 1) && (FREETYPE_PATCH >= 10))
1107 // FreeType >= 2.1.10 required
1108 if (!(render_context.face->style_flags & FT_STYLE_FLAG_ITALIC) &&
1109 ((render_context.italic == 1) || (render_context.italic > 55))) {
1110 FT_GlyphSlot_Oblique(render_context.face->glyph);
1111 }
1112 #endif
1113 error = FT_Get_Glyph(render_context.face->glyph, &(info->glyph));
1114 if (error) {
1115 mp_msg(MSGT_GLOBAL, MSGL_WARN, "Error getting glyph\n");
1116 return error;
1117 }
1118
1119 info->advance.x = info->glyph->advance.x >> 10;
1120 info->advance.y = info->glyph->advance.y >> 10;
1121
1122 info->outline_glyph = info->glyph;
1123 FT_Glyph_Stroke( &(info->outline_glyph), render_context.stroker, 0 ); // don't destroy original
1124
1125 info->bitmap = 0; // outline glyph
1126
1127 return 0;
1128 }
1129
1130 /**
1131 * \brief rearrange text between lines
1132 * \param max_text_width maximal text line width in pixels
1133 * The algo is similar to the one in libvo/sub.c:
1134 * 1. Place text, wrapping it when current line is full
1135 * 2. Try moving words from the end of a line to the beginning of the next one while it reduces
1136 * the difference in lengths between this two lines.
1137 * The result may not be optimal, but usually is good enough.
1138 */
1139 static void wrap_lines_smart(int max_text_width)
1140 {
1141 int i, j;
1142 glyph_info_t *cur, *s1, *e1, *s2, *s3, *w;
1143 int last_space;
1144 int break_type;
1145 int exit;
1146 int pen_shift_x;
1147 int pen_shift_y;
1148 int max_asc, max_desc;
1149 int cur_line;
1150
1151 last_space = -1;
1152 text_info.n_lines = 1;
1153 break_type = 0;
1154 s1 = text_info.glyphs; // current line start
1155 for (i = 0; i < text_info.length; ++i) {
1156 cur = text_info.glyphs + i;
1157 int break_at = -1;
1158 int s_offset = s1->bbox.xMin + s1->pos.x;
1159 int len = (cur->bbox.xMax + cur->pos.x) - s_offset;
1160
1161 if (cur->symbol == '\n') {
1162 break_type = 2;
1163 break_at = i;
1164 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "forced line break at %d\n", break_at);
1165 }
1166
1167 if (len >= max_text_width) {
1168 break_type = 1;
1169 break_at = last_space;
1170 if (break_at == -1)
1171 break_at = i - 1;
1172 if (break_at == -1)
1173 break_at = 0;
1174 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "overfill at %d\n", i);
1175 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "line break at %d\n", break_at);
1176 }
1177
1178 if (break_at != -1) {
1179 // need to use one more line
1180 // marking break_at+1 as start of a new line
1181 int lead = break_at + 1; // the first symbol of the new line
1182 if (text_info.n_lines >= MAX_LINES) {
1183 // to many lines !
1184 // no more linebreaks
1185 for (j = lead; j < text_info.length; ++j)
1186 text_info.glyphs[j].linebreak = 0;
1187 break;
1188 }
1189 if (lead < text_info.length)
1190 text_info.glyphs[lead].linebreak = break_type;
1191 last_space = -1;
1192 s1 = text_info.glyphs + lead;
1193 s_offset = s1->bbox.xMin + s1->pos.x;
1194 text_info.n_lines ++;
1195 }
1196
1197 if (cur->symbol == ' ')
1198 last_space = i;
1199 }
1200 #define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
1201 exit = 0;
1202 while (!exit) {
1203 exit = 1;
1204 w = s3 = text_info.glyphs;
1205 s1 = s2 = 0;
1206 for (i = 0; i <= text_info.length; ++i) {
1207 cur = text_info.glyphs + i;
1208 if ((i == text_info.length) || cur->linebreak) {
1209 s1 = s2;
1210 s2 = s3;
1211 s3 = cur;
1212 // printf("line: %d, %d, %d \n", s1 - text_info.glyphs, s2 - text_info.glyphs, s3 - text_info.glyphs);
1213 if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
1214 int l1, l2, l1_new, l2_new;
1215
1216 w = s2;
1217 do { --w; } while ((w > s1) && (w->symbol == ' '));
1218 do { --w; } while ((w > s1) && (w->symbol != ' '));
1219 e1 = w;
1220 do { --e1; } while ((e1 > s1) && (e1->symbol == ' '));
1221 if (w->symbol == ' ') ++w;
1222
1223 // printf("check: %d, %d, %d, w: %d, e: %d \n", s1 - text_info.glyphs, s2 - text_info.glyphs, s3 - text_info.glyphs,
1224 // w - text_info.glyphs, e1 - text_info.glyphs);
1225
1226 l1 = ((s2-1)->bbox.xMax + (s2-1)->pos.x) - (s1->bbox.xMin + s1->pos.x);
1227 l2 = ((s3-1)->bbox.xMax + (s3-1)->pos.x) - (s2->bbox.xMin + s2->pos.x);
1228 l1_new = (e1->bbox.xMax + e1->pos.x) - (s1->bbox.xMin + s1->pos.x);
1229 l2_new = ((s3-1)->bbox.xMax + (s3-1)->pos.x) - (w->bbox.xMin + w->pos.x);
1230
1231 if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {
1232 w->linebreak = 1;
1233 s2->linebreak = 0;
1234 exit = 0;
1235 }
1236 }
1237 }
1238 if (i == text_info.length)
1239 break;
1240 }
1241
1242 }
1243 assert(text_info.n_lines >= 1);
1244 #undef DIFF
1245
1246 text_info.height = 0;
1247 max_asc = max_desc = 0;
1248 cur_line = 0;
1249 for (i = 0; i < text_info.length + 1; ++i) {
1250 if ((i == text_info.length) || text_info.glyphs[i].linebreak) {
1251 text_info.lines[cur_line].asc = max_asc;
1252 text_info.lines[cur_line].desc = max_desc;
1253 text_info.height += max_asc + max_desc;
1254 cur_line ++;
1255 max_asc = max_desc = 0;
1256 }
1257 if (i < text_info.length) {
1258 cur = text_info.glyphs + i;
1259 if (cur->asc > max_asc)
1260 max_asc = cur->asc * render_context.scale_y;
1261 if (cur->desc > max_desc)
1262 max_desc = cur->desc * render_context.scale_y;
1263 }
1264 }
1265
1266 pen_shift_x = 0;
1267 pen_shift_y = 0;
1268 cur_line = 1;
1269 for (i = 0; i < text_info.length; ++i) {
1270 cur = text_info.glyphs + i;
1271 if (cur->linebreak) {
1272 int height = text_info.lines[cur_line - 1].desc + text_info.lines[cur_line].asc;
1273 cur_line ++;
1274 pen_shift_x = - cur->pos.x;
1275 pen_shift_y += (height >> 6) + global_settings->line_spacing;
1276 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "shifting from %d to %d by (%d, %d)\n", i, text_info.length - 1, pen_shift_x, pen_shift_y);
1277 }
1278 cur->pos.x += pen_shift_x;
1279 cur->pos.y += pen_shift_y;
1280 }
1281 // printf("============= \n");
1282 }
1283
1284 /**
1285 * \brief determine karaoke effects
1286 * Karaoke effects cannot be calculated during parse stage (get_next_char()),
1287 * so they are done in a separate step.
1288 * Parse stage: when karaoke style override is found, its parameters are stored in the next glyph's
1289 * (the first glyph of the karaoke word)'s effect_type and effect_timing.
1290 * This function:
1291 * 1. sets effect_type for all glyphs in the word (_karaoke_ word)
1292 * 2. sets effect_timing for all glyphs to x coordinate of the border line between the left and right karaoke parts
1293 * (left part is filled with PrimaryColour, right one - with SecondaryColour).
1294 */
1295 static void process_karaoke_effects(void)
1296 {
1297 glyph_info_t *cur, *cur2;
1298 glyph_info_t *s1, *e1; // start and end of the current word
1299 glyph_info_t *s2; // start of the next word
1300 int i;
1301 int timing; // current timing
1302 int tm_start, tm_end; // timings at start and end of the current word
1303 int tm_current;
1304 double dt;
1305 int x;
1306 int x_start, x_end;
1307
1308 tm_current = frame_context.time - render_context.event->Start;
1309 timing = 0;
1310 s1 = s2 = 0;
1311 for (i = 0; i <= text_info.length; ++i) {
1312 cur = text_info.glyphs + i;
1313 if ((i == text_info.length) || (cur->effect_type != EF_NONE)) {
1314 s1 = s2;
1315 s2 = cur;
1316 if (s1) {
1317 e1 = s2 - 1;
1318 tm_start = timing;
1319 tm_end = timing + s1->effect_timing;
1320 timing = tm_end;
1321 x_start = s1->bbox.xMin + s1->pos.x;
1322 x_end = e1->bbox.xMax + e1->pos.x;
1323
1324 dt = (tm_current - tm_start);
1325 if ((s1->effect_type == EF_KARAOKE) || (s1->effect_type == EF_KARAOKE_KO)) {
1326 if (dt > 0)
1327 x = x_end + 1;
1328 else
1329 x = x_start;
1330 } else if (s1->effect_type == EF_KARAOKE_KF) {
1331 dt /= (tm_end - tm_start);
1332 x = x_start + (x_end - x_start) * dt;
1333 } else {
1334 mp_msg(MSGT_GLOBAL, MSGL_ERR, "Unknown effect type (internal error) \n");
1335 continue;
1336 }
1337
1338 for (cur2 = s1; cur2 <= e1; ++cur2) {
1339 cur2->effect_type = s1->effect_type;
1340 cur2->effect_timing = x - cur2->pos.x;
1341 }
1342 }
1343 }
1344 }
1345 }
1346
1347 int get_face_ascender(FT_Face face)
1348 {
1349 int v = face->size->metrics.ascender;
1350 if (!v)
1351 v = FT_MulFix(face->bbox.yMax, face->size->metrics.y_scale);
1352 return v;
1353 }
1354
1355 int get_face_descender(FT_Face face)
1356 {
1357 int v = face->size->metrics.descender;
1358 if (!v)
1359 v = FT_MulFix(face->bbox.yMin, face->size->metrics.y_scale);
1360 return -v;
1361 }
1362
1363 /**
1364 * \brief Main ass rendering function, glues everything together
1365 * \param event event to render
1366 * Process event, appending resulting ass_image_t's to images_root.
1367 */
1368 int ass_render_event(ass_event_t* event)
1369 {
1370 char* p;
1371 FT_UInt glyph_index;
1372 FT_Bool use_kerning;
1373 FT_UInt previous;
1374 FT_UInt num_glyphs;
1375 FT_Vector pen;
1376 int error;
1377 unsigned code;
1378 FT_BBox bbox;
1379 int i, j;
1380 FT_Vector shift;
1381 int MarginL, MarginR, MarginV;
1382 int max_text_width;
1383 ass_style_t* style = frame_context.track->styles + event->Style;
1384 int last_break;
1385 int alignment, halign, valign;
1386 int device_x, device_y;
1387
1388 init_render_context(event);
1389
1390 text_info.length = 0;
1391 pen.x = 0;
1392 pen.y = 0;
1393 previous = 0;
1394 num_glyphs = 0;
1395
1396
1397 p = event->Text;
1398 if (!p) {
1399 mp_msg(MSGT_GLOBAL, MSGL_WARN, "Empty event!\n");
1400 return 0;
1401 }
1402
1403 // Event parsing.
1404 while (1) {
1405 render_context.effect_type = EF_NONE;
1406
1407 // get next char, executing style override
1408 // this affects render_context
1409 code = get_next_char(&p);
1410
1411 // face could have been changed in get_next_char
1412 if (!render_context.face) {
1413 free_render_context();
1414 return 0;
1415 }
1416
1417 if (code == 0)
1418 break;
1419
1420 use_kerning = FT_HAS_KERNING(render_context.face);
1421
1422 if (text_info.length >= MAX_GLYPHS) {
1423 mp_msg(MSGT_GLOBAL, MSGL_WARN, "\nMAX_GLYPHS reached: event %d, start = %llu, duration = %llu\n Text = %s\n",
1424 (int)(event - frame_context.track->events), event->Start, event->Duration, event->Text);
1425 break;
1426 }
1427
1428 glyph_index = FT_Get_Char_Index( render_context.face, code);
1429
1430 if ( use_kerning && previous && glyph_index ) {
1431 FT_Vector delta;
1432 FT_Get_Kerning( render_context.face, previous, glyph_index, FT_KERNING_DEFAULT, &delta );
1433 pen.x += delta.x;
1434 pen.y += delta.y;
1435 }
1436
1437 shift.x = pen.x & 63;
1438 shift.y = pen.y & 63;
1439
1440 if ((render_context.scale_x != 1.) || (render_context.scale_y != 1.) ||
1441 (frame_context.font_scale_x != 1.)) {
1442 FT_Matrix matrix;
1443 matrix.xx = (FT_Fixed)( render_context.scale_x * frame_context.font_scale_x * 0x10000L );
1444 matrix.xy = (FT_Fixed)( 0 * 0x10000L );
1445 matrix.yx = (FT_Fixed)( 0 * 0x10000L );
1446 matrix.yy = (FT_Fixed)( render_context.scale_y * 0x10000L );
1447
1448 FT_Set_Transform( render_context.face, &matrix, &shift );
1449 } else {
1450 FT_Set_Transform(render_context.face, 0, &shift);
1451 }
1452
1453 error = get_glyph(glyph_index, code, text_info.glyphs + text_info.length, &shift);
1454
1455 if (error) {
1456 continue;
1457 }
1458
1459 text_info.glyphs[text_info.length].pos.x = pen.x >> 6;
1460 text_info.glyphs[text_info.length].pos.y = pen.y >> 6;
1461
1462 pen.x += text_info.glyphs[text_info.length].advance.x;
1463 pen.x += render_context.hspacing;
1464 pen.y += text_info.glyphs[text_info.length].advance.y;
1465
1466 // if it's an outline glyph, we still need to fill the bbox
1467 if (text_info.glyphs[text_info.length].bitmap != 1) {
1468 FT_Glyph_Get_CBox( text_info.glyphs[text_info.length].glyph, FT_GLYPH_BBOX_PIXELS, &(text_info.glyphs[text_info.length].bbox) );
1469 }
1470
1471
1472 previous = glyph_index;
1473
1474 text_info.glyphs[text_info.length].symbol = code;
1475 text_info.glyphs[text_info.length].linebreak = 0;
1476 text_info.glyphs[text_info.length].c1 = render_context.c1;
1477 text_info.glyphs[text_info.length].c2 = render_context.c2;
1478 text_info.glyphs[text_info.length].c3 = render_context.c3;
1479 text_info.glyphs[text_info.length].c4 = render_context.c4;
1480 text_info.glyphs[text_info.length].effect_type = render_context.effect_type;
1481 text_info.glyphs[text_info.length].effect_timing = render_context.effect_timing;
1482 text_info.glyphs[text_info.length].asc = get_face_ascender(render_context.face);
1483 text_info.glyphs[text_info.length].desc = get_face_descender(render_context.face);
1484
1485 text_info.length++;
1486 }
1487
1488 if (text_info.length == 0) {
1489 // no valid symbols in the event; this can be smth like {comment}
1490 free_render_context();
1491 return 0;
1492 }
1493
1494 // depends on glyph x coordinates being monotonous, so it should be done before line wrap
1495 process_karaoke_effects();
1496
1497 // calculate max length of a line
1498 MarginL = (event->MarginL) ? event->MarginL : style->MarginL;
1499 MarginR = (event->MarginR) ? event->MarginR : style->MarginR;
1500 MarginV = (event->MarginV) ? event->MarginV : style->MarginV;
1501
1502 max_text_width = x2scr(frame_context.track->PlayResX - MarginR) - x2scr(MarginL);
1503 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "normal text width: %d\n", max_text_width);
1504
1505 // rearrange text in several lines
1506 wrap_lines_smart(max_text_width);
1507
1508 // alignments
1509 alignment = render_context.alignment;
1510 if (!alignment)
1511 alignment = render_context.style->Alignment;
1512 halign = alignment & 3;
1513 valign = alignment & 12;
1514
1515 // align text
1516 last_break = -1;
1517 for (i = 1; i < text_info.length + 1; ++i) { // (text_info.length + 1) is the end of the last line
1518 if ((i == text_info.length) || text_info.glyphs[i].linebreak) {
1519
1520 glyph_info_t* first_glyph = text_info.glyphs + last_break + 1;
1521 glyph_info_t* last_glyph = text_info.glyphs + i - 1;
1522
1523 while ((last_glyph >= first_glyph) && ((last_glyph->symbol == '\n') || (last_glyph->symbol == 0)))
1524 last_glyph --;
1525
1526 int width = last_glyph->pos.x + last_glyph->bbox.xMax - first_glyph->pos.x - first_glyph->bbox.xMin;
1527 int shift = - first_glyph->bbox.xMin; // now text line starts exactly at 0 (left margin)
1528 if (halign == HALIGN_LEFT) { // left aligned, no action
1529 } else if (halign == HALIGN_RIGHT) { // right aligned
1530 shift = max_text_width - width;
1531 } else if (halign == HALIGN_CENTER) { // centered
1532 shift = (max_text_width - width) / 2;
1533 }
1534 for (j = last_break + 1; j < i; ++j) {
1535 text_info.glyphs[j].pos.x += shift;
1536 }
1537 last_break = i - 1;
1538 }
1539 }
1540
1541 // determing text bounding box
1542 compute_string_bbox(&text_info, &bbox);
1543
1544 // determine device coordinates for text
1545
1546 // FIXME: using current font descender, ascender and height here is wrong.
1547 // correct way is using max(descender) over all the fonts used in a line
1548 // the same for height and ascender
1549 if (render_context.evt_type == EVENT_NORMAL) {
1550 device_x = x2scr(MarginL);
1551 if (valign == VALIGN_TOP) { // toptitle
1552 device_y = y2scr_top(MarginV) + (text_info.lines[0].asc >> 6);
1553 if (render_context.detect_collisions) {
1554 device_y += frame_context.add_top_margin;
1555 frame_context.add_top_margin += (text_info.height >> 6);
1556 }
1557 } else if (valign == VALIGN_CENTER) { // midtitle
1558 int scr_y = y2scr(frame_context.track->PlayResY / 2);
1559 device_y = scr_y - (bbox.yMax - bbox.yMin) / 2;
1560 } else { // subtitle
1561 int scr_y;
1562 if (valign != VALIGN_SUB)
1563 mp_msg(MSGT_GLOBAL, MSGL_V, "Invalid valign, supposing 0 (subtitle)\n");
1564 scr_y = y2scr_sub(frame_context.track->PlayResY - MarginV);
1565 device_y = scr_y;
1566 device_y -= (text_info.height >> 6);
1567 device_y += (text_info.lines[0].asc >> 6);
1568 if (render_context.detect_collisions) {
1569 device_y -= frame_context.add_bottom_margin;
1570 frame_context.add_bottom_margin += (text_info.height >> 6);
1571 }
1572 }
1573 } else if (render_context.evt_type == EVENT_POSITIONED) {
1574 int align_shift_x = 0;
1575 int align_shift_y = 0;
1576 mp_msg(MSGT_GLOBAL, MSGL_DBG2, "positioned event at %d, %d\n", render_context.pos_x, render_context.pos_y);
1577 switch(halign) {
1578 case HALIGN_LEFT:
1579 align_shift_x = - bbox.xMin;
1580 break;
1581 case HALIGN_CENTER:
1582 align_shift_x = - (bbox.xMax + bbox.xMin) /2;
1583 break;
1584 case HALIGN_RIGHT:
1585 align_shift_x = - bbox.xMax;
1586 break;
1587 }
1588 switch(valign) {
1589 case VALIGN_TOP:
1590 align_shift_y = - bbox.yMin;
1591 break;
1592 case VALIGN_CENTER:
1593 align_shift_y = - (bbox.yMax + bbox.yMin) /2;
1594 break;
1595 case VALIGN_SUB:
1596 align_shift_y = - bbox.yMax;
1597 break;
1598 }
1599 device_x = x2scr(render_context.pos_x) + align_shift_x;
1600 device_y = y2scr(render_context.pos_y) + align_shift_y;
1601 } else {
1602 mp_msg(MSGT_GLOBAL, MSGL_V, "unknown evt_type\n");
1603 device_x = 10;
1604 device_y = 10;
1605 }
1606
1607 // fix clip coordinates (they depend on alignment)
1608 render_context.clip_x0 = x2scr(render_context.clip_x0);
1609 render_context.clip_x1 = x2scr(render_context.clip_x1);
1610 if (render_context.evt_type == EVENT_NORMAL) {
1611 if (valign == VALIGN_TOP) {
1612 render_context.clip_y0 = y2scr_top(render_context.clip_y0);
1613 render_context.clip_y1 = y2scr_top(render_context.clip_y1);
1614 } else if (valign == VALIGN_CENTER) {
1615 render_context.clip_y0 = y2scr(render_context.clip_y0);
1616 render_context.clip_y1 = y2scr(render_context.clip_y1);
1617 } else if (valign == VALIGN_SUB) {
1618 render_context.clip_y0 = y2scr_sub(render_context.clip_y0);
1619 render_context.clip_y1 = y2scr_sub(render_context.clip_y1);
1620 }
1621 } else if (render_context.evt_type == EVENT_POSITIONED) {
1622 render_context.clip_y0 = y2scr(render_context.clip_y0);
1623 render_context.clip_y1 = y2scr(render_context.clip_y1);
1624 }
1625
1626 // rotate glyphs if needed
1627 if (render_context.rotation != 0.) {
1628 double angle = render_context.rotation;
1629 FT_Vector center;
1630 FT_Matrix matrix_rotate;
1631
1632 matrix_rotate.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
1633 matrix_rotate.xy = (FT_Fixed)( -sin( angle ) * 0x10000L );
1634 matrix_rotate.yx = (FT_Fixed)( sin( angle ) * 0x10000L );
1635 matrix_rotate.yy = (FT_Fixed)( cos( angle ) * 0x10000L );
1636
1637 if (((render_context.org_x != 0) || (render_context.org_y != 0)) && (render_context.evt_type == EVENT_POSITIONED)) {
1638 center.x = render_context.org_x;
1639 center.y = render_context.org_y;
1640 } else {
1641 FT_BBox str_bbox;
1642
1643 center.x = text_info.glyphs[0].pos.x + device_x;
1644 center.y = text_info.glyphs[0].pos.y + device_y;
1645
1646 compute_string_bbox(&text_info, &str_bbox);
1647 center.x += (str_bbox.xMax - str_bbox.xMin) / 2;
1648 center.y += (str_bbox.yMax - str_bbox.yMin) / 2;
1649 }
1650 // mp_msg(MSGT_GLOBAL, MSGL_DBG2, "\ncenter: %d, %d\n", center.x, center.y);
1651
1652 for (i = 0; i < text_info.length; ++i) {
1653 glyph_info_t* info = text_info.glyphs + i;
1654
1655 // calculating shift vector
1656 // shift = (position - center)*M - (position - center)
1657 FT_Vector start;
1658 FT_Vector start_old;
1659 // mp_msg(MSGT_GLOBAL, MSGL_INFO, "start: (%d, %d) + (%d, %d) - (%d, %d) = (%d, %d)\n", info->pos.x, info->pos.y, device_x, device_y, center.x, center.y,
1660 // info->pos.x + device_x - center.x, info->pos.y + device_y - center.y);
1661 start.x = (info->pos.x + device_x - center.x) << 6;
1662 start.y = - (info->pos.y + device_y - center.y) << 6;
1663 start_old.x = start.x;
1664 start_old.y = start.y;
1665 // mp_msg(MSGT_GLOBAL, MSGL_INFO, "start: %d, %d\n", start.x / 64, start.y / 64);
1666
1667 FT_Vector_Transform(&start, &matrix_rotate);
1668
1669 start.x -= start_old.x;
1670 start.y -= start_old.y;
1671
1672 info->pos.x += start.x >> 6;
1673 info->pos.y -= start.y >> 6;
1674
1675 // mp_msg(MSGT_GLOBAL, MSGL_DBG2, "shift: %d, %d\n", start.x / 64, start.y / 64);
1676 if (info->bitmap != 1) {
1677 FT_Glyph_Transform( info->glyph, &matrix_rotate, 0 );
1678 FT_Glyph_Transform( info->outline_glyph, &matrix_rotate, 0 );
1679 }
1680 }
1681 }
1682
1683 // render
1684 render_text(&text_info, device_x, device_y);
1685
1686 free_render_context();
1687
1688 return 0;
1689 }
1690
1691 void ass_configure(ass_instance_t* priv, const ass_settings_t* config)
1692 {
1693 memcpy(&priv->settings, config, sizeof(ass_settings_t));
1694 }
1695
1696 /**
1697 * \brief Start a new frame
1698 */
1699 int ass_start_frame(ass_instance_t *priv, ass_track_t* track, long long now)
1700 {
1701 ass_instance = priv;
1702 global_settings = &priv->settings;
1703
1704 if (!priv->settings.frame_width && !priv->settings.frame_height)
1705 return 1; // library not initialized
1706
1707 frame_context.ass_priv = priv;
1708 frame_context.width = global_settings->frame_width;
1709 frame_context.height = global_settings->frame_height;
1710 frame_context.orig_height = global_settings->frame_height - global_settings->top_margin - global_settings->bottom_margin;
1711 frame_context.track = track;
1712 frame_context.add_bottom_margin = 0;
1713 frame_context.add_top_margin = 0;
1714 frame_context.time = now;
1715
1716 ass_lazy_track_init();
1717
1718 if (frame_context.width * track->PlayResY == frame_context.height * track->PlayResX)
1719 frame_context.font_scale_x = 1.;
1720 else
1721 frame_context.font_scale_x = ((double)(frame_context.width * track->PlayResY)) / (frame_context.height * track->PlayResX);
1722
1723 priv->n_images = 0;
1724
1725 return 0;
1726 }
1727
1728 /**
1729 * \brief End a frame, give out rendering results
1730 * \return list of ass_image_t
1731 */
1732 ass_image_t* ass_end_frame(void)
1733 {
1734 ass_instance_t* priv = ass_instance;
1735 if (priv->n_images) {
1736 int i;
1737 for (i = 0; i < priv->n_images - 1; ++i)
1738 priv->images_root[i].next = priv->images_root + i + 1;
1739 priv->images_root[priv->n_images - 1].next = 0;
1740 return priv->images_root;
1741 } else {
1742 return 0;
1743 }
1744 }
1745 /**
1746 * \brief render a frame
1747 * \param priv library handle
1748 * \param track track
1749 * \param now current video timestamp (ms)
1750 */
1751 ass_image_t* ass_render_frame(ass_instance_t *priv, ass_track_t* track, long long now)
1752 {
1753 int i, rc;
1754
1755 rc = ass_start_frame(priv, track, now);
1756 if (rc != 0) // some error
1757 return 0;
1758 for (i = 0; i < track->n_events; ++i) {
1759 ass_event_t* event = track->events + i;
1760 if ( (event->Start <= now) && (now < (event->Start + event->Duration)) ) {
1761 ass_render_event(event);
1762 }
1763 }
1764 return ass_end_frame();
1765 }
1766