Only word wrap on spaces
[libass.git] / libass / ass_render.c
blob2fade830b1211f3a0569df7bcc02271f7e55e8af
1 /*
2 * Copyright (C) 2006 Evgeniy Stepanov <eugeni.stepanov@gmail.com>
4 * This file is part of libass.
6 * libass 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.
11 * libass 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.
16 * You should have received a copy of the GNU General Public License along
17 * with libass; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "config.h"
23 #include <assert.h>
24 #include <math.h>
26 #include "ass_render.h"
27 #include "ass_parse.h"
29 #define MAX_GLYPHS_INITIAL 1024
30 #define MAX_LINES_INITIAL 64
31 #define SUBPIXEL_MASK 63
32 #define SUBPIXEL_ACCURACY 7
34 static void ass_lazy_track_init(ASS_Renderer *render_priv)
36 ASS_Track *track = render_priv->track;
38 if (track->PlayResX && track->PlayResY)
39 return;
40 if (!track->PlayResX && !track->PlayResY) {
41 ass_msg(render_priv->library, MSGL_WARN,
42 "Neither PlayResX nor PlayResY defined. Assuming 384x288");
43 track->PlayResX = 384;
44 track->PlayResY = 288;
45 } else {
46 if (!track->PlayResY && track->PlayResX == 1280) {
47 track->PlayResY = 1024;
48 ass_msg(render_priv->library, MSGL_WARN,
49 "PlayResY undefined, setting to %d", track->PlayResY);
50 } else if (!track->PlayResY) {
51 track->PlayResY = track->PlayResX * 3 / 4;
52 ass_msg(render_priv->library, MSGL_WARN,
53 "PlayResY undefined, setting to %d", track->PlayResY);
54 } else if (!track->PlayResX && track->PlayResY == 1024) {
55 track->PlayResX = 1280;
56 ass_msg(render_priv->library, MSGL_WARN,
57 "PlayResX undefined, setting to %d", track->PlayResX);
58 } else if (!track->PlayResX) {
59 track->PlayResX = track->PlayResY * 4 / 3;
60 ass_msg(render_priv->library, MSGL_WARN,
61 "PlayResX undefined, setting to %d", track->PlayResX);
66 ASS_Renderer *ass_renderer_init(ASS_Library *library)
68 int error;
69 FT_Library ft;
70 ASS_Renderer *priv = 0;
71 int vmajor, vminor, vpatch;
73 error = FT_Init_FreeType(&ft);
74 if (error) {
75 ass_msg(library, MSGL_FATAL, "%s failed", "FT_Init_FreeType");
76 goto ass_init_exit;
79 FT_Library_Version(ft, &vmajor, &vminor, &vpatch);
80 ass_msg(library, MSGL_V, "FreeType library version: %d.%d.%d",
81 vmajor, vminor, vpatch);
82 ass_msg(library, MSGL_V, "FreeType headers version: %d.%d.%d",
83 FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH);
85 priv = calloc(1, sizeof(ASS_Renderer));
86 if (!priv) {
87 FT_Done_FreeType(ft);
88 goto ass_init_exit;
91 priv->synth_priv = ass_synth_init(BLUR_MAX_RADIUS);
93 priv->library = library;
94 priv->ftlibrary = ft;
95 // images_root and related stuff is zero-filled in calloc
97 priv->cache.font_cache = ass_font_cache_init(library);
98 priv->cache.bitmap_cache = ass_bitmap_cache_init(library);
99 priv->cache.composite_cache = ass_composite_cache_init(library);
100 priv->cache.glyph_cache = ass_glyph_cache_init(library);
101 priv->cache.glyph_max = GLYPH_CACHE_MAX;
102 priv->cache.bitmap_max_size = BITMAP_CACHE_MAX_SIZE;
104 priv->text_info.max_glyphs = MAX_GLYPHS_INITIAL;
105 priv->text_info.max_lines = MAX_LINES_INITIAL;
106 priv->text_info.glyphs = calloc(MAX_GLYPHS_INITIAL, sizeof(GlyphInfo));
107 priv->text_info.lines = calloc(MAX_LINES_INITIAL, sizeof(LineInfo));
109 priv->settings.font_size_coeff = 1.;
111 ass_init_exit:
112 if (priv)
113 ass_msg(library, MSGL_V, "Init");
114 else
115 ass_msg(library, MSGL_ERR, "Init failed");
117 return priv;
120 static void free_list_clear(ASS_Renderer *render_priv)
122 if (render_priv->free_head) {
123 FreeList *item = render_priv->free_head;
124 while(item) {
125 FreeList *oi = item;
126 free(item->object);
127 item = item->next;
128 free(oi);
130 render_priv->free_head = NULL;
134 void ass_renderer_done(ASS_Renderer *render_priv)
136 ass_font_cache_done(render_priv->cache.font_cache);
137 ass_bitmap_cache_done(render_priv->cache.bitmap_cache);
138 ass_composite_cache_done(render_priv->cache.composite_cache);
139 ass_glyph_cache_done(render_priv->cache.glyph_cache);
141 ass_free_images(render_priv->images_root);
142 ass_free_images(render_priv->prev_images_root);
144 if (render_priv->state.stroker) {
145 FT_Stroker_Done(render_priv->state.stroker);
146 render_priv->state.stroker = 0;
148 if (render_priv->ftlibrary)
149 FT_Done_FreeType(render_priv->ftlibrary);
150 if (render_priv->fontconfig_priv)
151 fontconfig_done(render_priv->fontconfig_priv);
152 if (render_priv->synth_priv)
153 ass_synth_done(render_priv->synth_priv);
154 free(render_priv->eimg);
155 free(render_priv->text_info.glyphs);
156 free(render_priv->text_info.lines);
158 free(render_priv->settings.default_font);
159 free(render_priv->settings.default_family);
161 free_list_clear(render_priv);
162 free(render_priv);
166 * \brief Create a new ASS_Image
167 * Parameters are the same as ASS_Image fields.
169 static ASS_Image *my_draw_bitmap(unsigned char *bitmap, int bitmap_w,
170 int bitmap_h, int stride, int dst_x,
171 int dst_y, uint32_t color)
173 ASS_Image *img = malloc(sizeof(ASS_Image));
175 if (img) {
176 img->w = bitmap_w;
177 img->h = bitmap_h;
178 img->stride = stride;
179 img->bitmap = bitmap;
180 img->color = color;
181 img->dst_x = dst_x;
182 img->dst_y = dst_y;
185 return img;
189 * \brief Mapping between script and screen coordinates
191 static double x2scr(ASS_Renderer *render_priv, double x)
193 return x * render_priv->orig_width_nocrop / render_priv->font_scale_x /
194 render_priv->track->PlayResX +
195 FFMAX(render_priv->settings.left_margin, 0);
197 static double x2scr_pos(ASS_Renderer *render_priv, double x)
199 return x * render_priv->orig_width / render_priv->font_scale_x / render_priv->track->PlayResX +
200 render_priv->settings.left_margin;
202 static double x2scr_scaled(ASS_Renderer *render_priv, double x)
204 return x * render_priv->orig_width_nocrop /
205 render_priv->track->PlayResX +
206 FFMAX(render_priv->settings.left_margin, 0);
208 static double x2scr_pos_scaled(ASS_Renderer *render_priv, double x)
210 return x * render_priv->orig_width / render_priv->track->PlayResX +
211 render_priv->settings.left_margin;
214 * \brief Mapping between script and screen coordinates
216 static double y2scr(ASS_Renderer *render_priv, double y)
218 return y * render_priv->orig_height_nocrop /
219 render_priv->track->PlayResY +
220 FFMAX(render_priv->settings.top_margin, 0);
222 static double y2scr_pos(ASS_Renderer *render_priv, double y)
224 return y * render_priv->orig_height / render_priv->track->PlayResY +
225 render_priv->settings.top_margin;
228 // the same for toptitles
229 static double y2scr_top(ASS_Renderer *render_priv, double y)
231 if (render_priv->settings.use_margins)
232 return y * render_priv->orig_height_nocrop /
233 render_priv->track->PlayResY;
234 else
235 return y * render_priv->orig_height_nocrop /
236 render_priv->track->PlayResY +
237 FFMAX(render_priv->settings.top_margin, 0);
239 // the same for subtitles
240 static double y2scr_sub(ASS_Renderer *render_priv, double y)
242 if (render_priv->settings.use_margins)
243 return y * render_priv->orig_height_nocrop /
244 render_priv->track->PlayResY +
245 FFMAX(render_priv->settings.top_margin, 0)
246 + FFMAX(render_priv->settings.bottom_margin, 0);
247 else
248 return y * render_priv->orig_height_nocrop /
249 render_priv->track->PlayResY +
250 FFMAX(render_priv->settings.top_margin, 0);
254 * \brief Convert bitmap glyphs into ASS_Image list with inverse clipping
256 * Inverse clipping with the following strategy:
257 * - find rectangle from (x0, y0) to (cx0, y1)
258 * - find rectangle from (cx0, y0) to (cx1, cy0)
259 * - find rectangle from (cx0, cy1) to (cx1, y1)
260 * - find rectangle from (cx1, y0) to (x1, y1)
261 * These rectangles can be invalid and in this case are discarded.
262 * Afterwards, they are clipped against the screen coordinates.
263 * In an additional pass, the rectangles need to be split up left/right for
264 * karaoke effects. This can result in a lot of bitmaps (6 to be exact).
266 static ASS_Image **render_glyph_i(ASS_Renderer *render_priv,
267 Bitmap *bm, int dst_x, int dst_y,
268 uint32_t color, uint32_t color2, int brk,
269 ASS_Image **tail)
271 int i, j, x0, y0, x1, y1, cx0, cy0, cx1, cy1, sx, sy, zx, zy;
272 Rect r[4];
273 ASS_Image *img;
275 dst_x += bm->left;
276 dst_y += bm->top;
278 // we still need to clip against screen boundaries
279 zx = x2scr_pos_scaled(render_priv, 0);
280 zy = y2scr_pos(render_priv, 0);
281 sx = x2scr_pos_scaled(render_priv, render_priv->track->PlayResX);
282 sy = y2scr_pos(render_priv, render_priv->track->PlayResY);
284 x0 = 0;
285 y0 = 0;
286 x1 = bm->w;
287 y1 = bm->h;
288 cx0 = render_priv->state.clip_x0 - dst_x;
289 cy0 = render_priv->state.clip_y0 - dst_y;
290 cx1 = render_priv->state.clip_x1 - dst_x;
291 cy1 = render_priv->state.clip_y1 - dst_y;
293 // calculate rectangles and discard invalid ones while we're at it.
294 i = 0;
295 r[i].x0 = x0;
296 r[i].y0 = y0;
297 r[i].x1 = (cx0 > x1) ? x1 : cx0;
298 r[i].y1 = y1;
299 if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
300 r[i].x0 = (cx0 < 0) ? x0 : cx0;
301 r[i].y0 = y0;
302 r[i].x1 = (cx1 > x1) ? x1 : cx1;
303 r[i].y1 = (cy0 > y1) ? y1 : cy0;
304 if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
305 r[i].x0 = (cx0 < 0) ? x0 : cx0;
306 r[i].y0 = (cy1 < 0) ? y0 : cy1;
307 r[i].x1 = (cx1 > x1) ? x1 : cx1;
308 r[i].y1 = y1;
309 if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
310 r[i].x0 = (cx1 < 0) ? x0 : cx1;
311 r[i].y0 = y0;
312 r[i].x1 = x1;
313 r[i].y1 = y1;
314 if (r[i].x1 > r[i].x0 && r[i].y1 > r[i].y0) i++;
316 // clip each rectangle to screen coordinates
317 for (j = 0; j < i; j++) {
318 r[j].x0 = (r[j].x0 + dst_x < zx) ? zx - dst_x : r[j].x0;
319 r[j].y0 = (r[j].y0 + dst_y < zy) ? zy - dst_y : r[j].y0;
320 r[j].x1 = (r[j].x1 + dst_x > sx) ? sx - dst_x : r[j].x1;
321 r[j].y1 = (r[j].y1 + dst_y > sy) ? sy - dst_y : r[j].y1;
324 // draw the rectangles
325 for (j = 0; j < i; j++) {
326 int lbrk = brk;
327 // kick out rectangles that are invalid now
328 if (r[j].x1 <= r[j].x0 || r[j].y1 <= r[j].y0)
329 continue;
330 // split up into left and right for karaoke, if needed
331 if (lbrk > r[j].x0) {
332 if (lbrk > r[j].x1) lbrk = r[j].x1;
333 img = my_draw_bitmap(bm->buffer + r[j].y0 * bm->w + r[j].x0,
334 lbrk - r[j].x0, r[j].y1 - r[j].y0,
335 bm->w, dst_x + r[j].x0, dst_y + r[j].y0, color);
336 if (!img) break;
337 *tail = img;
338 tail = &img->next;
340 if (lbrk < r[j].x1) {
341 if (lbrk < r[j].x0) lbrk = r[j].x0;
342 img = my_draw_bitmap(bm->buffer + r[j].y0 * bm->w + lbrk,
343 r[j].x1 - lbrk, r[j].y1 - r[j].y0,
344 bm->w, dst_x + lbrk, dst_y + r[j].y0, color2);
345 if (!img) break;
346 *tail = img;
347 tail = &img->next;
351 return tail;
355 * \brief convert bitmap glyph into ASS_Image struct(s)
356 * \param bit freetype bitmap glyph, FT_PIXEL_MODE_GRAY
357 * \param dst_x bitmap x coordinate in video frame
358 * \param dst_y bitmap y coordinate in video frame
359 * \param color first color, RGBA
360 * \param color2 second color, RGBA
361 * \param brk x coordinate relative to glyph origin, color is used to the left of brk, color2 - to the right
362 * \param tail pointer to the last image's next field, head of the generated list should be stored here
363 * \return pointer to the new list tail
364 * Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
366 static ASS_Image **
367 render_glyph(ASS_Renderer *render_priv, Bitmap *bm, int dst_x, int dst_y,
368 uint32_t color, uint32_t color2, int brk, ASS_Image **tail)
370 // Inverse clipping in use?
371 if (render_priv->state.clip_mode)
372 return render_glyph_i(render_priv, bm, dst_x, dst_y, color, color2,
373 brk, tail);
375 // brk is relative to dst_x
376 // color = color left of brk
377 // color2 = color right of brk
378 int b_x0, b_y0, b_x1, b_y1; // visible part of the bitmap
379 int clip_x0, clip_y0, clip_x1, clip_y1;
380 int tmp;
381 ASS_Image *img;
383 dst_x += bm->left;
384 dst_y += bm->top;
385 brk -= bm->left;
387 // clipping
388 clip_x0 = FFMINMAX(render_priv->state.clip_x0, 0, render_priv->width);
389 clip_y0 = FFMINMAX(render_priv->state.clip_y0, 0, render_priv->height);
390 clip_x1 = FFMINMAX(render_priv->state.clip_x1, 0, render_priv->width);
391 clip_y1 = FFMINMAX(render_priv->state.clip_y1, 0, render_priv->height);
392 b_x0 = 0;
393 b_y0 = 0;
394 b_x1 = bm->w;
395 b_y1 = bm->h;
397 tmp = dst_x - clip_x0;
398 if (tmp < 0) {
399 ass_msg(render_priv->library, MSGL_DBG2, "clip left");
400 b_x0 = -tmp;
402 tmp = dst_y - clip_y0;
403 if (tmp < 0) {
404 ass_msg(render_priv->library, MSGL_DBG2, "clip top");
405 b_y0 = -tmp;
407 tmp = clip_x1 - dst_x - bm->w;
408 if (tmp < 0) {
409 ass_msg(render_priv->library, MSGL_DBG2, "clip right");
410 b_x1 = bm->w + tmp;
412 tmp = clip_y1 - dst_y - bm->h;
413 if (tmp < 0) {
414 ass_msg(render_priv->library, MSGL_DBG2, "clip bottom");
415 b_y1 = bm->h + tmp;
418 if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
419 return tail;
421 if (brk > b_x0) { // draw left part
422 if (brk > b_x1)
423 brk = b_x1;
424 img = my_draw_bitmap(bm->buffer + bm->w * b_y0 + b_x0,
425 brk - b_x0, b_y1 - b_y0, bm->w,
426 dst_x + b_x0, dst_y + b_y0, color);
427 if (!img) return tail;
428 *tail = img;
429 tail = &img->next;
431 if (brk < b_x1) { // draw right part
432 if (brk < b_x0)
433 brk = b_x0;
434 img = my_draw_bitmap(bm->buffer + bm->w * b_y0 + brk,
435 b_x1 - brk, b_y1 - b_y0, bm->w,
436 dst_x + brk, dst_y + b_y0, color2);
437 if (!img) return tail;
438 *tail = img;
439 tail = &img->next;
441 return tail;
445 * \brief Replace the bitmap buffer in ASS_Image with a copy
446 * \param img ASS_Image to operate on
447 * \return pointer to old bitmap buffer
449 static unsigned char *clone_bitmap_buffer(ASS_Image *img)
451 unsigned char *old_bitmap = img->bitmap;
452 int size = img->stride * (img->h - 1) + img->w;
453 img->bitmap = malloc(size);
454 memcpy(img->bitmap, old_bitmap, size);
455 return old_bitmap;
459 * \brief Calculate overlapping area of two consecutive bitmaps and in case they
460 * overlap, blend them together
461 * Mainly useful for translucent glyphs and especially borders, to avoid the
462 * luminance adding up where they overlap (which looks ugly)
464 static void
465 render_overlap(ASS_Renderer *render_priv, ASS_Image **last_tail,
466 ASS_Image **tail)
468 int left, top, bottom, right;
469 int old_left, old_top, w, h, cur_left, cur_top;
470 int x, y, opos, cpos;
471 char m;
472 CompositeHashKey hk;
473 CompositeHashValue *hv;
474 CompositeHashValue chv;
475 int ax = (*last_tail)->dst_x;
476 int ay = (*last_tail)->dst_y;
477 int aw = (*last_tail)->w;
478 int as = (*last_tail)->stride;
479 int ah = (*last_tail)->h;
480 int bx = (*tail)->dst_x;
481 int by = (*tail)->dst_y;
482 int bw = (*tail)->w;
483 int bs = (*tail)->stride;
484 int bh = (*tail)->h;
485 unsigned char *a;
486 unsigned char *b;
488 if ((*last_tail)->bitmap == (*tail)->bitmap)
489 return;
491 if ((*last_tail)->color != (*tail)->color)
492 return;
494 // Calculate overlap coordinates
495 left = (ax > bx) ? ax : bx;
496 top = (ay > by) ? ay : by;
497 right = ((ax + aw) < (bx + bw)) ? (ax + aw) : (bx + bw);
498 bottom = ((ay + ah) < (by + bh)) ? (ay + ah) : (by + bh);
499 if ((right <= left) || (bottom <= top))
500 return;
501 old_left = left - ax;
502 old_top = top - ay;
503 w = right - left;
504 h = bottom - top;
505 cur_left = left - bx;
506 cur_top = top - by;
508 // Query cache
509 hk.a = (*last_tail)->bitmap;
510 hk.b = (*tail)->bitmap;
511 hk.aw = aw;
512 hk.ah = ah;
513 hk.bw = bw;
514 hk.bh = bh;
515 hk.ax = ax;
516 hk.ay = ay;
517 hk.bx = bx;
518 hk.by = by;
519 hk.as = as;
520 hk.bs = bs;
521 hv = cache_find_composite(render_priv->cache.composite_cache, &hk);
522 if (hv) {
523 (*last_tail)->bitmap = hv->a;
524 (*tail)->bitmap = hv->b;
525 return;
527 // Allocate new bitmaps and copy over data
528 a = clone_bitmap_buffer(*last_tail);
529 b = clone_bitmap_buffer(*tail);
531 // Blend overlapping area
532 for (y = 0; y < h; y++)
533 for (x = 0; x < w; x++) {
534 opos = (old_top + y) * (as) + (old_left + x);
535 cpos = (cur_top + y) * (bs) + (cur_left + x);
536 m = FFMIN(a[opos] + b[cpos], 0xff);
537 (*last_tail)->bitmap[opos] = 0;
538 (*tail)->bitmap[cpos] = m;
541 // Insert bitmaps into the cache
542 chv.a = (*last_tail)->bitmap;
543 chv.b = (*tail)->bitmap;
544 cache_add_composite(render_priv->cache.composite_cache, &hk, &chv);
547 static void free_list_add(ASS_Renderer *render_priv, void *object)
549 if (!render_priv->free_head) {
550 render_priv->free_head = calloc(1, sizeof(FreeList));
551 render_priv->free_head->object = object;
552 render_priv->free_tail = render_priv->free_head;
553 } else {
554 FreeList *l = calloc(1, sizeof(FreeList));
555 l->object = object;
556 render_priv->free_tail->next = l;
557 render_priv->free_tail = render_priv->free_tail->next;
562 * Iterate through a list of bitmaps and blend with clip vector, if
563 * applicable. The blended bitmaps are added to a free list which is freed
564 * at the start of a new frame.
566 static void blend_vector_clip(ASS_Renderer *render_priv,
567 ASS_Image *head)
569 FT_Glyph glyph;
570 FT_BitmapGlyph clip_bm;
571 ASS_Image *cur;
572 ASS_Drawing *drawing = render_priv->state.clip_drawing;
573 GlyphHashKey key;
574 GlyphHashValue *val;
575 int error;
577 if (!drawing)
578 return;
580 // Try to get mask from cache
581 ass_drawing_hash(drawing);
582 memset(&key, 0, sizeof(key));
583 key.ch = -2;
584 key.drawing_hash = drawing->hash;
585 val = cache_find_glyph(render_priv->cache.glyph_cache, &key);
587 if (val) {
588 clip_bm = (FT_BitmapGlyph) val->glyph;
589 } else {
590 GlyphHashValue v;
592 // Not found in cache, parse and rasterize it
593 glyph = (FT_Glyph) *ass_drawing_parse(drawing, 1);
594 if (!glyph) {
595 ass_msg(render_priv->library, MSGL_WARN,
596 "Clip vector parsing failed. Skipping.");
597 goto blend_vector_error;
600 // We need to translate the clip according to screen borders
601 if (render_priv->settings.left_margin != 0 ||
602 render_priv->settings.top_margin != 0) {
603 FT_Vector trans = {
604 .x = int_to_d6(render_priv->settings.left_margin),
605 .y = -int_to_d6(render_priv->settings.top_margin),
607 FT_Outline_Translate(&drawing->glyph->outline,
608 trans.x, trans.y);
611 // Check glyph bounding box size
612 if (check_glyph_area(render_priv->library, glyph)) {
613 FT_Done_Glyph(glyph);
614 glyph = 0;
615 goto blend_vector_error;
618 ass_msg(render_priv->library, MSGL_DBG2,
619 "Parsed vector clip: scales (%f, %f) string [%s]\n",
620 drawing->scale_x, drawing->scale_y, drawing->text);
622 error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
623 if (error) {
624 ass_msg(render_priv->library, MSGL_WARN,
625 "Clip vector rasterization failed: %d. Skipping.", error);
626 FT_Done_Glyph(glyph);
627 glyph = 0;
630 blend_vector_error:
631 clip_bm = (FT_BitmapGlyph) glyph;
633 // Add to cache
634 memset(&v, 0, sizeof(v));
635 v.glyph = glyph;
636 cache_add_glyph(render_priv->cache.glyph_cache, &key, &v);
639 if (!clip_bm) goto blend_vector_exit;
641 // Iterate through bitmaps and blend/clip them
642 for (cur = head; cur; cur = cur->next) {
643 int left, top, right, bottom, apos, bpos, y, x, w, h;
644 int ax, ay, aw, ah, as;
645 int bx, by, bw, bh, bs;
646 int aleft, atop, bleft, btop;
647 unsigned char *abuffer, *bbuffer, *nbuffer;
649 abuffer = cur->bitmap;
650 bbuffer = clip_bm->bitmap.buffer;
651 ax = cur->dst_x;
652 ay = cur->dst_y;
653 aw = cur->w;
654 ah = cur->h;
655 as = cur->stride;
656 bx = clip_bm->left;
657 by = -clip_bm->top;
658 bw = clip_bm->bitmap.width;
659 bh = clip_bm->bitmap.rows;
660 bs = clip_bm->bitmap.pitch;
662 // Calculate overlap coordinates
663 left = (ax > bx) ? ax : bx;
664 top = (ay > by) ? ay : by;
665 right = ((ax + aw) < (bx + bw)) ? (ax + aw) : (bx + bw);
666 bottom = ((ay + ah) < (by + bh)) ? (ay + ah) : (by + bh);
667 aleft = left - ax;
668 atop = top - ay;
669 w = right - left;
670 h = bottom - top;
671 bleft = left - bx;
672 btop = top - by;
674 if (render_priv->state.clip_drawing_mode) {
675 // Inverse clip
676 if (ax + aw < bx || ay + ah < by || ax > bx + bw ||
677 ay > by + bh) {
678 continue;
681 // Allocate new buffer and add to free list
682 nbuffer = malloc(as * ah);
683 if (!nbuffer) goto blend_vector_exit;
684 free_list_add(render_priv, nbuffer);
686 // Blend together
687 memcpy(nbuffer, abuffer, as * (ah - 1) + aw);
688 for (y = 0; y < h; y++)
689 for (x = 0; x < w; x++) {
690 apos = (atop + y) * as + aleft + x;
691 bpos = (btop + y) * bs + bleft + x;
692 nbuffer[apos] = FFMAX(0, abuffer[apos] - bbuffer[bpos]);
694 } else {
695 // Regular clip
696 if (ax + aw < bx || ay + ah < by || ax > bx + bw ||
697 ay > by + bh) {
698 cur->w = cur->h = 0;
699 continue;
702 // Allocate new buffer and add to free list
703 nbuffer = calloc(as, ah);
704 if (!nbuffer) goto blend_vector_exit;
705 free_list_add(render_priv, nbuffer);
707 // Blend together
708 for (y = 0; y < h; y++)
709 for (x = 0; x < w; x++) {
710 apos = (atop + y) * as + aleft + x;
711 bpos = (btop + y) * bs + bleft + x;
712 nbuffer[apos] = (abuffer[apos] * bbuffer[bpos] + 255) >> 8;
715 cur->bitmap = nbuffer;
718 blend_vector_exit:
719 ass_drawing_free(render_priv->state.clip_drawing);
720 render_priv->state.clip_drawing = 0;
724 * \brief Convert TextInfo struct to ASS_Image list
725 * Splits glyphs in halves when needed (for \kf karaoke).
727 static ASS_Image *render_text(ASS_Renderer *render_priv, int dst_x, int dst_y)
729 int pen_x, pen_y;
730 int i;
731 Bitmap *bm;
732 ASS_Image *head;
733 ASS_Image **tail = &head;
734 ASS_Image **last_tail = 0;
735 ASS_Image **here_tail = 0;
736 TextInfo *text_info = &render_priv->text_info;
738 for (i = 0; i < text_info->length; ++i) {
739 GlyphInfo *info = text_info->glyphs + i;
740 if ((info->symbol == 0) || (info->symbol == '\n') || !info->bm_s
741 || (info->shadow_x == 0 && info->shadow_y == 0) || info->skip)
742 continue;
744 pen_x =
745 dst_x + (info->pos.x >> 6) +
746 (int) (info->shadow_x * render_priv->border_scale);
747 pen_y =
748 dst_y + (info->pos.y >> 6) +
749 (int) (info->shadow_y * render_priv->border_scale);
750 bm = info->bm_s;
752 here_tail = tail;
753 tail =
754 render_glyph(render_priv, bm, pen_x, pen_y, info->c[3], 0,
755 1000000, tail);
756 if (last_tail && tail != here_tail && ((info->c[3] & 0xff) > 0))
757 render_overlap(render_priv, last_tail, here_tail);
759 last_tail = here_tail;
762 last_tail = 0;
763 for (i = 0; i < text_info->length; ++i) {
764 GlyphInfo *info = text_info->glyphs + i;
765 if ((info->symbol == 0) || (info->symbol == '\n') || !info->bm_o
766 || info->skip)
767 continue;
769 pen_x = dst_x + (info->pos.x >> 6);
770 pen_y = dst_y + (info->pos.y >> 6);
771 bm = info->bm_o;
773 if ((info->effect_type == EF_KARAOKE_KO)
774 && (info->effect_timing <= (info->bbox.xMax >> 6))) {
775 // do nothing
776 } else {
777 here_tail = tail;
778 tail =
779 render_glyph(render_priv, bm, pen_x, pen_y, info->c[2],
780 0, 1000000, tail);
781 if (last_tail && tail != here_tail && ((info->c[2] & 0xff) > 0))
782 render_overlap(render_priv, last_tail, here_tail);
784 last_tail = here_tail;
788 for (i = 0; i < text_info->length; ++i) {
789 GlyphInfo *info = text_info->glyphs + i;
790 if ((info->symbol == 0) || (info->symbol == '\n') || !info->bm
791 || info->skip)
792 continue;
794 pen_x = dst_x + (info->pos.x >> 6);
795 pen_y = dst_y + (info->pos.y >> 6);
796 bm = info->bm;
798 if ((info->effect_type == EF_KARAOKE)
799 || (info->effect_type == EF_KARAOKE_KO)) {
800 if (info->effect_timing > (info->bbox.xMax >> 6))
801 tail =
802 render_glyph(render_priv, bm, pen_x, pen_y,
803 info->c[0], 0, 1000000, tail);
804 else
805 tail =
806 render_glyph(render_priv, bm, pen_x, pen_y,
807 info->c[1], 0, 1000000, tail);
808 } else if (info->effect_type == EF_KARAOKE_KF) {
809 tail =
810 render_glyph(render_priv, bm, pen_x, pen_y, info->c[0],
811 info->c[1], info->effect_timing, tail);
812 } else
813 tail =
814 render_glyph(render_priv, bm, pen_x, pen_y, info->c[0],
815 0, 1000000, tail);
818 *tail = 0;
819 blend_vector_clip(render_priv, head);
821 return head;
824 static void compute_string_bbox(TextInfo *info, DBBox *bbox)
826 int i;
828 if (info->length > 0) {
829 bbox->xMin = 32000;
830 bbox->xMax = -32000;
831 bbox->yMin = -1 * info->lines[0].asc + d6_to_double(info->glyphs[0].pos.y);
832 bbox->yMax = info->height - info->lines[0].asc +
833 d6_to_double(info->glyphs[0].pos.y);
835 for (i = 0; i < info->length; ++i) {
836 if (info->glyphs[i].skip) continue;
837 double s = d6_to_double(info->glyphs[i].pos.x);
838 double e = s + d6_to_double(info->glyphs[i].advance.x);
839 bbox->xMin = FFMIN(bbox->xMin, s);
840 bbox->xMax = FFMAX(bbox->xMax, e);
842 } else
843 bbox->xMin = bbox->xMax = bbox->yMin = bbox->yMax = 0.;
847 * \brief partially reset render_context to style values
848 * Works like {\r}: resets some style overrides
850 void reset_render_context(ASS_Renderer *render_priv)
852 render_priv->state.c[0] = render_priv->state.style->PrimaryColour;
853 render_priv->state.c[1] = render_priv->state.style->SecondaryColour;
854 render_priv->state.c[2] = render_priv->state.style->OutlineColour;
855 render_priv->state.c[3] = render_priv->state.style->BackColour;
856 render_priv->state.flags =
857 (render_priv->state.style->Underline ? DECO_UNDERLINE : 0) |
858 (render_priv->state.style->StrikeOut ? DECO_STRIKETHROUGH : 0);
859 render_priv->state.font_size = render_priv->state.style->FontSize;
861 free(render_priv->state.family);
862 render_priv->state.family = NULL;
863 render_priv->state.family = strdup(render_priv->state.style->FontName);
864 render_priv->state.treat_family_as_pattern =
865 render_priv->state.style->treat_fontname_as_pattern;
866 render_priv->state.bold = render_priv->state.style->Bold;
867 render_priv->state.italic = render_priv->state.style->Italic;
868 update_font(render_priv);
870 change_border(render_priv, -1., -1.);
871 render_priv->state.scale_x = render_priv->state.style->ScaleX;
872 render_priv->state.scale_y = render_priv->state.style->ScaleY;
873 render_priv->state.hspacing = render_priv->state.style->Spacing;
874 render_priv->state.be = 0;
875 render_priv->state.blur = 0.0;
876 render_priv->state.shadow_x = render_priv->state.style->Shadow;
877 render_priv->state.shadow_y = render_priv->state.style->Shadow;
878 render_priv->state.frx = render_priv->state.fry = 0.;
879 render_priv->state.frz = M_PI * render_priv->state.style->Angle / 180.;
880 render_priv->state.fax = render_priv->state.fay = 0.;
881 render_priv->state.wrap_style = render_priv->track->WrapStyle;
885 * \brief Start new event. Reset render_priv->state.
887 static void
888 init_render_context(ASS_Renderer *render_priv, ASS_Event *event)
890 render_priv->state.event = event;
891 render_priv->state.style = render_priv->track->styles + event->Style;
893 reset_render_context(render_priv);
895 render_priv->state.evt_type = EVENT_NORMAL;
896 render_priv->state.alignment = render_priv->state.style->Alignment;
897 render_priv->state.pos_x = 0;
898 render_priv->state.pos_y = 0;
899 render_priv->state.org_x = 0;
900 render_priv->state.org_y = 0;
901 render_priv->state.have_origin = 0;
902 render_priv->state.clip_x0 = 0;
903 render_priv->state.clip_y0 = 0;
904 render_priv->state.clip_x1 = render_priv->track->PlayResX;
905 render_priv->state.clip_y1 = render_priv->track->PlayResY;
906 render_priv->state.clip_mode = 0;
907 render_priv->state.detect_collisions = 1;
908 render_priv->state.fade = 0;
909 render_priv->state.drawing_mode = 0;
910 render_priv->state.effect_type = EF_NONE;
911 render_priv->state.effect_timing = 0;
912 render_priv->state.effect_skip_timing = 0;
913 ass_drawing_free(render_priv->state.drawing);
914 render_priv->state.drawing = ass_drawing_new(render_priv->fontconfig_priv,
915 render_priv->state.font,
916 render_priv->ftlibrary);
918 apply_transition_effects(render_priv, event);
921 static void free_render_context(ASS_Renderer *render_priv)
923 free(render_priv->state.family);
924 ass_drawing_free(render_priv->state.drawing);
926 render_priv->state.family = NULL;
927 render_priv->state.drawing = NULL;
931 * Replace the outline of a glyph by a contour which makes up a simple
932 * opaque rectangle.
934 static void draw_opaque_box(ASS_Renderer *render_priv, uint32_t ch,
935 FT_Glyph glyph, int sx, int sy)
937 int asc = 0, desc = 0;
938 int i;
939 int adv = d16_to_d6(glyph->advance.x);
940 double scale_y = render_priv->state.scale_y;
941 double scale_x = render_priv->state.scale_x;
942 FT_OutlineGlyph og = (FT_OutlineGlyph) glyph;
943 FT_Outline *ol;
945 // to avoid gaps
946 sx = FFMAX(64, sx);
947 sy = FFMAX(64, sy);
949 if (ch == -1) {
950 asc = render_priv->state.drawing->asc;
951 desc = render_priv->state.drawing->desc;
952 } else {
953 ass_font_get_asc_desc(render_priv->state.font, ch, &asc, &desc);
954 asc *= scale_y;
955 desc *= scale_y;
958 // Emulate the WTFish behavior of VSFilter, i.e. double-scale
959 // the sizes of the opaque box.
960 adv += double_to_d6(render_priv->state.hspacing * render_priv->font_scale
961 * scale_x);
962 adv *= scale_x;
963 sx *= scale_x;
964 sy *= scale_y;
965 desc *= scale_y;
966 desc += asc * (scale_y - 1.0);
968 FT_Vector points[4] = {
969 { .x = -sx, .y = asc + sy },
970 { .x = adv + sx, .y = asc + sy },
971 { .x = adv + sx, .y = -desc - sy },
972 { .x = -sx, .y = -desc - sy },
975 FT_Outline_Done(render_priv->ftlibrary, &og->outline);
976 FT_Outline_New(render_priv->ftlibrary, 4, 1, &og->outline);
978 ol = &og->outline;
979 ol->n_points = ol->n_contours = 0;
980 for (i = 0; i < 4; i++) {
981 ol->points[ol->n_points] = points[i];
982 ol->tags[ol->n_points++] = 1;
984 ol->contours[ol->n_contours++] = ol->n_points - 1;
988 * Stroke an outline glyph in x/y direction. Applies various fixups to get
989 * around limitations of the FreeType stroker.
991 static void stroke_outline_glyph(ASS_Renderer *render_priv,
992 FT_OutlineGlyph *glyph, int sx, int sy)
994 if (sx <= 0 && sy <= 0)
995 return;
997 fix_freetype_stroker(*glyph, sx, sy);
999 // Borders are equal; use the regular stroker
1000 if (sx == sy && render_priv->state.stroker) {
1001 int error;
1002 error = FT_Glyph_StrokeBorder((FT_Glyph *) glyph,
1003 render_priv->state.stroker, 0, 1);
1004 if (error)
1005 ass_msg(render_priv->library, MSGL_WARN,
1006 "FT_Glyph_Stroke error: %d", error);
1008 // "Stroke" with the outline emboldener in two passes.
1009 // The outlines look uglier, but the emboldening never adds any points
1010 } else {
1011 int i;
1012 FT_Outline *ol = &(*glyph)->outline;
1013 FT_Outline nol;
1014 FT_Outline_New(render_priv->ftlibrary, ol->n_points,
1015 ol->n_contours, &nol);
1016 FT_Outline_Copy(ol, &nol);
1018 FT_Outline_Embolden(ol, sx * 2);
1019 FT_Outline_Translate(ol, -sx, -sx);
1020 FT_Outline_Embolden(&nol, sy * 2);
1021 FT_Outline_Translate(&nol, -sy, -sy);
1023 for (i = 0; i < ol->n_points; i++)
1024 ol->points[i].y = nol.points[i].y;
1026 FT_Outline_Done(render_priv->ftlibrary, &nol);
1031 * \brief Prepare glyph hash
1033 static void
1034 fill_glyph_hash(ASS_Renderer *priv, GlyphHashKey *key,
1035 ASS_Drawing *drawing, uint32_t ch)
1037 if (drawing->hash) {
1038 key->scale_x = double_to_d16(priv->state.scale_x);
1039 key->scale_y = double_to_d16(priv->state.scale_y);
1040 key->outline.x = priv->state.border_x * 0xFFFF;
1041 key->outline.y = priv->state.border_y * 0xFFFF;
1042 key->border_style = priv->state.style->BorderStyle;
1043 key->drawing_hash = drawing->hash;
1044 // not very clean, but works
1045 key->size = drawing->scale;
1046 key->ch = -1;
1047 } else {
1048 key->font = priv->state.font;
1049 key->size = priv->state.font_size;
1050 key->ch = ch;
1051 key->bold = priv->state.bold;
1052 key->italic = priv->state.italic;
1053 key->scale_x = double_to_d16(priv->state.scale_x);
1054 key->scale_y = double_to_d16(priv->state.scale_y);
1055 key->outline.x = priv->state.border_x * 0xFFFF;
1056 key->outline.y = priv->state.border_y * 0xFFFF;
1057 key->flags = priv->state.flags;
1058 key->border_style = priv->state.style->BorderStyle;
1063 * \brief Get normal and outline (border) glyphs
1064 * \param symbol ucs4 char
1065 * \param info out: struct filled with extracted data
1066 * Tries to get both glyphs from cache.
1067 * If they can't be found, gets a glyph from font face, generates outline with FT_Stroker,
1068 * and add them to cache.
1069 * The glyphs are returned in info->glyph and info->outline_glyph
1071 static void
1072 get_outline_glyph(ASS_Renderer *render_priv, int symbol, GlyphInfo *info,
1073 ASS_Drawing *drawing)
1075 GlyphHashValue *val;
1076 GlyphHashKey key;
1078 memset(&key, 0, sizeof(key));
1079 memset(info, 0, sizeof(GlyphInfo));
1081 fill_glyph_hash(render_priv, &key, drawing, symbol);
1082 val = cache_find_glyph(render_priv->cache.glyph_cache, &key);
1083 if (val) {
1084 info->glyph = val->glyph;
1085 info->outline_glyph = val->outline_glyph;
1086 info->bbox = val->bbox_scaled;
1087 info->advance.x = val->advance.x;
1088 info->advance.y = val->advance.y;
1089 if (drawing->hash) {
1090 drawing->asc = val->asc;
1091 drawing->desc = val->desc;
1093 } else {
1094 GlyphHashValue v;
1095 if (drawing->hash) {
1096 if(!ass_drawing_parse(drawing, 0))
1097 return;
1098 info->glyph = (FT_Glyph) drawing->glyph;
1099 } else {
1100 info->glyph =
1101 ass_font_get_glyph(render_priv->fontconfig_priv,
1102 render_priv->state.font, symbol,
1103 render_priv->settings.hinting,
1104 render_priv->state.flags);
1106 if (!info->glyph)
1107 return;
1109 info->advance.x = d16_to_d6(info->glyph->advance.x);
1110 info->advance.y = d16_to_d6(info->glyph->advance.y);
1111 FT_Glyph_Get_CBox(info->glyph, FT_GLYPH_BBOX_SUBPIXELS, &info->bbox);
1113 if (render_priv->state.style->BorderStyle == 3 &&
1114 (render_priv->state.border_x > 0||
1115 render_priv->state.border_y > 0)) {
1116 FT_Glyph_Copy(info->glyph, &info->outline_glyph);
1117 draw_opaque_box(render_priv, symbol, info->outline_glyph,
1118 double_to_d6(render_priv->state.border_x *
1119 render_priv->border_scale),
1120 double_to_d6(render_priv->state.border_y *
1121 render_priv->border_scale));
1122 } else if ((render_priv->state.border_x > 0
1123 || render_priv->state.border_y > 0)
1124 && key.scale_x && key.scale_y) {
1126 FT_Glyph_Copy(info->glyph, &info->outline_glyph);
1127 stroke_outline_glyph(render_priv,
1128 (FT_OutlineGlyph *) &info->outline_glyph,
1129 double_to_d6(render_priv->state.border_x *
1130 render_priv->border_scale),
1131 double_to_d6(render_priv->state.border_y *
1132 render_priv->border_scale));
1135 memset(&v, 0, sizeof(v));
1136 v.glyph = info->glyph;
1137 v.outline_glyph = info->outline_glyph;
1138 v.advance = info->advance;
1139 v.bbox_scaled = info->bbox;
1140 if (drawing->hash) {
1141 v.asc = drawing->asc;
1142 v.desc = drawing->desc;
1144 cache_add_glyph(render_priv->cache.glyph_cache, &key, &v);
1149 * \brief Apply transformation to outline points of a glyph
1150 * Applies rotations given by frx, fry and frz and projects the points back
1151 * onto the screen plane.
1153 static void
1154 transform_3d_points(FT_Vector shift, FT_Glyph glyph, double frx, double fry,
1155 double frz, double fax, double fay, double scale,
1156 int yshift)
1158 double sx = sin(frx);
1159 double sy = sin(fry);
1160 double sz = sin(frz);
1161 double cx = cos(frx);
1162 double cy = cos(fry);
1163 double cz = cos(frz);
1164 FT_Outline *outline = &((FT_OutlineGlyph) glyph)->outline;
1165 FT_Vector *p = outline->points;
1166 double x, y, z, xx, yy, zz;
1167 int i, dist;
1169 dist = 20000 * scale;
1170 for (i = 0; i < outline->n_points; i++) {
1171 x = (double) p[i].x + shift.x + (fax * (yshift - p[i].y));
1172 y = (double) p[i].y + shift.y + (-fay * p[i].x);
1173 z = 0.;
1175 xx = x * cz + y * sz;
1176 yy = -(x * sz - y * cz);
1177 zz = z;
1179 x = xx;
1180 y = yy * cx + zz * sx;
1181 z = yy * sx - zz * cx;
1183 xx = x * cy + z * sy;
1184 yy = y;
1185 zz = x * sy - z * cy;
1187 zz = FFMAX(zz, 1000 - dist);
1189 x = (xx * dist) / (zz + dist);
1190 y = (yy * dist) / (zz + dist);
1191 p[i].x = x - shift.x + 0.5;
1192 p[i].y = y - shift.y + 0.5;
1197 * \brief Apply 3d transformation to several objects
1198 * \param shift FreeType vector
1199 * \param glyph FreeType glyph
1200 * \param glyph2 FreeType glyph
1201 * \param frx x-axis rotation angle
1202 * \param fry y-axis rotation angle
1203 * \param frz z-axis rotation angle
1204 * Rotates both glyphs by frx, fry and frz. Shift vector is added before rotation and subtracted after it.
1206 static void
1207 transform_3d(FT_Vector shift, FT_Glyph *glyph, FT_Glyph *glyph2,
1208 double frx, double fry, double frz, double fax, double fay,
1209 double scale, int yshift)
1211 frx = -frx;
1212 frz = -frz;
1213 if (frx != 0. || fry != 0. || frz != 0. || fax != 0. || fay != 0.) {
1214 if (glyph && *glyph)
1215 transform_3d_points(shift, *glyph, frx, fry, frz,
1216 fax, fay, scale, yshift);
1218 if (glyph2 && *glyph2)
1219 transform_3d_points(shift, *glyph2, frx, fry, frz,
1220 fax, fay, scale, yshift);
1225 * \brief Get bitmaps for a glyph
1226 * \param info glyph info
1227 * Tries to get glyph bitmaps from bitmap cache.
1228 * If they can't be found, they are generated by rotating and rendering the glyph.
1229 * After that, bitmaps are added to the cache.
1230 * They are returned in info->bm (glyph), info->bm_o (outline) and info->bm_s (shadow).
1232 static void
1233 get_bitmap_glyph(ASS_Renderer *render_priv, GlyphInfo *info)
1235 BitmapHashValue *val;
1236 BitmapHashKey *key = &info->hash_key;
1238 val = cache_find_bitmap(render_priv->cache.bitmap_cache, key);
1240 if (val) {
1241 info->bm = val->bm;
1242 info->bm_o = val->bm_o;
1243 info->bm_s = val->bm_s;
1244 } else {
1245 FT_Vector shift;
1246 BitmapHashValue hash_val;
1247 int error;
1248 double fax_scaled, fay_scaled;
1249 info->bm = info->bm_o = info->bm_s = 0;
1250 if (info->glyph && info->symbol != '\n' && info->symbol != 0
1251 && !info->skip) {
1252 FT_Glyph glyph;
1253 FT_Glyph outline;
1254 double scale_x = render_priv->font_scale_x;
1256 FT_Glyph_Copy(info->glyph, &glyph);
1257 FT_Glyph_Copy(info->outline_glyph, &outline);
1258 // calculating rotation shift vector (from rotation origin to the glyph basepoint)
1259 shift.x = key->shift_x;
1260 shift.y = key->shift_y;
1261 fax_scaled = info->fax *
1262 render_priv->state.scale_x;
1263 fay_scaled = info->fay * render_priv->state.scale_y;
1264 // apply rotation
1265 transform_3d(shift, &glyph, &outline,
1266 info->frx, info->fry, info->frz, fax_scaled,
1267 fay_scaled, render_priv->font_scale, info->asc);
1269 // PAR correction scaling
1270 FT_Matrix m = { double_to_d16(scale_x), 0,
1271 0, double_to_d16(1.0) };
1273 // subpixel shift
1274 if (glyph) {
1275 FT_Outline *outl = &((FT_OutlineGlyph) glyph)->outline;
1276 if (scale_x != 1.0)
1277 FT_Outline_Transform(outl, &m);
1278 FT_Outline_Translate(outl, key->advance.x, -key->advance.y);
1280 if (outline) {
1281 FT_Outline *outl = &((FT_OutlineGlyph) outline)->outline;
1282 if (scale_x != 1.0)
1283 FT_Outline_Transform(outl, &m);
1284 FT_Outline_Translate(outl, key->advance.x, -key->advance.y);
1286 // render glyph
1287 error = glyph_to_bitmap(render_priv->library,
1288 render_priv->synth_priv,
1289 glyph, outline,
1290 &info->bm, &info->bm_o,
1291 &info->bm_s, info->be,
1292 info->blur * render_priv->border_scale,
1293 key->shadow_offset, key->border_style);
1294 if (error)
1295 info->symbol = 0;
1297 // add bitmaps to cache
1298 hash_val.bm_o = info->bm_o;
1299 hash_val.bm = info->bm;
1300 hash_val.bm_s = info->bm_s;
1301 cache_add_bitmap(render_priv->cache.bitmap_cache, key, &hash_val);
1303 FT_Done_Glyph(glyph);
1304 FT_Done_Glyph(outline);
1310 * This function goes through text_info and calculates text parameters.
1311 * The following text_info fields are filled:
1312 * height
1313 * lines[].height
1314 * lines[].asc
1315 * lines[].desc
1317 static void measure_text(ASS_Renderer *render_priv)
1319 TextInfo *text_info = &render_priv->text_info;
1320 int cur_line = 0;
1321 double max_asc = 0., max_desc = 0.;
1322 GlyphInfo *last = NULL;
1323 int i;
1324 int empty_line = 1;
1325 text_info->height = 0.;
1326 for (i = 0; i < text_info->length + 1; ++i) {
1327 if ((i == text_info->length) || text_info->glyphs[i].linebreak) {
1328 if (empty_line && cur_line > 0 && last && i < text_info->length) {
1329 max_asc = d6_to_double(last->asc) / 2.0;
1330 max_desc = d6_to_double(last->desc) / 2.0;
1332 text_info->lines[cur_line].asc = max_asc;
1333 text_info->lines[cur_line].desc = max_desc;
1334 text_info->height += max_asc + max_desc;
1335 cur_line++;
1336 max_asc = max_desc = 0.;
1337 empty_line = 1;
1338 } else
1339 empty_line = 0;
1340 if (i < text_info->length) {
1341 GlyphInfo *cur = text_info->glyphs + i;
1342 if (d6_to_double(cur->asc) > max_asc)
1343 max_asc = d6_to_double(cur->asc);
1344 if (d6_to_double(cur->desc) > max_desc)
1345 max_desc = d6_to_double(cur->desc);
1346 if (cur->symbol != '\n' && cur->symbol != 0)
1347 last = cur;
1350 text_info->height +=
1351 (text_info->n_lines -
1352 1) * render_priv->settings.line_spacing;
1356 * Mark extra whitespace for later removal.
1358 #define IS_WHITESPACE(x) ((x->symbol == ' ' || x->symbol == '\n') \
1359 && !x->linebreak)
1360 static void trim_whitespace(ASS_Renderer *render_priv)
1362 int i, j;
1363 GlyphInfo *cur;
1364 TextInfo *ti = &render_priv->text_info;
1366 // Mark trailing spaces
1367 i = ti->length - 1;
1368 cur = ti->glyphs + i;
1369 while (i && IS_WHITESPACE(cur)) {
1370 cur->skip++;
1371 cur = ti->glyphs + --i;
1374 // Mark leading whitespace
1375 i = 0;
1376 cur = ti->glyphs;
1377 while (i < ti->length && IS_WHITESPACE(cur)) {
1378 cur->skip++;
1379 cur = ti->glyphs + ++i;
1382 // Mark all extraneous whitespace inbetween
1383 for (i = 0; i < ti->length; ++i) {
1384 cur = ti->glyphs + i;
1385 if (cur->linebreak) {
1386 // Mark whitespace before
1387 j = i - 1;
1388 cur = ti->glyphs + j;
1389 while (j && IS_WHITESPACE(cur)) {
1390 cur->skip++;
1391 cur = ti->glyphs + --j;
1393 // A break itself can contain a whitespace, too
1394 cur = ti->glyphs + i;
1395 if (cur->symbol == ' ')
1396 cur->skip++;
1397 // Mark whitespace after
1398 j = i + 1;
1399 cur = ti->glyphs + j;
1400 while (j < ti->length && IS_WHITESPACE(cur)) {
1401 cur->skip++;
1402 cur = ti->glyphs + ++j;
1404 i = j - 1;
1408 #undef IS_WHITESPACE
1411 * \brief rearrange text between lines
1412 * \param max_text_width maximal text line width in pixels
1413 * The algo is similar to the one in libvo/sub.c:
1414 * 1. Place text, wrapping it when current line is full
1415 * 2. Try moving words from the end of a line to the beginning of the next one while it reduces
1416 * the difference in lengths between this two lines.
1417 * The result may not be optimal, but usually is good enough.
1419 * FIXME: implement style 0 and 3 correctly
1421 static void
1422 wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)
1424 int i;
1425 GlyphInfo *cur, *s1, *e1, *s2, *s3, *w;
1426 int last_space;
1427 int break_type;
1428 int exit;
1429 double pen_shift_x;
1430 double pen_shift_y;
1431 int cur_line;
1432 TextInfo *text_info = &render_priv->text_info;
1434 last_space = -1;
1435 text_info->n_lines = 1;
1436 break_type = 0;
1437 s1 = text_info->glyphs; // current line start
1438 for (i = 0; i < text_info->length; ++i) {
1439 int break_at;
1440 double s_offset, len;
1441 cur = text_info->glyphs + i;
1442 break_at = -1;
1443 s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);
1444 len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;
1446 if (cur->symbol == '\n') {
1447 break_type = 2;
1448 break_at = i;
1449 ass_msg(render_priv->library, MSGL_DBG2,
1450 "forced line break at %d", break_at);
1453 if ((len >= max_text_width)
1454 && (render_priv->state.wrap_style != 2)) {
1455 break_type = 1;
1456 break_at = last_space;
1457 if (break_at >= 0)
1458 ass_msg(render_priv->library, MSGL_DBG2, "line break at %d",
1459 break_at);
1462 if (break_at != -1) {
1463 // need to use one more line
1464 // marking break_at+1 as start of a new line
1465 int lead = break_at + 1; // the first symbol of the new line
1466 if (text_info->n_lines >= text_info->max_lines) {
1467 // Raise maximum number of lines
1468 text_info->max_lines *= 2;
1469 text_info->lines = realloc(text_info->lines,
1470 sizeof(LineInfo) *
1471 text_info->max_lines);
1473 if (lead < text_info->length)
1474 text_info->glyphs[lead].linebreak = break_type;
1475 last_space = -1;
1476 s1 = text_info->glyphs + lead;
1477 s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);
1478 text_info->n_lines++;
1481 if (cur->symbol == ' ')
1482 last_space = i;
1484 // make sure the hard linebreak is not forgotten when
1485 // there was a new soft linebreak just inserted
1486 if (cur->symbol == '\n' && break_type == 1)
1487 i--;
1489 #define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
1490 exit = 0;
1491 while (!exit && render_priv->state.wrap_style != 1) {
1492 exit = 1;
1493 w = s3 = text_info->glyphs;
1494 s1 = s2 = 0;
1495 for (i = 0; i <= text_info->length; ++i) {
1496 cur = text_info->glyphs + i;
1497 if ((i == text_info->length) || cur->linebreak) {
1498 s1 = s2;
1499 s2 = s3;
1500 s3 = cur;
1501 if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
1502 double l1, l2, l1_new, l2_new;
1504 w = s2;
1505 do {
1506 --w;
1507 } while ((w > s1) && (w->symbol == ' '));
1508 while ((w > s1) && (w->symbol != ' ')) {
1509 --w;
1511 e1 = w;
1512 while ((e1 > s1) && (e1->symbol == ' ')) {
1513 --e1;
1515 if (w->symbol == ' ')
1516 ++w;
1518 l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -
1519 (s1->bbox.xMin + s1->pos.x));
1520 l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
1521 (s2->bbox.xMin + s2->pos.x));
1522 l1_new = d6_to_double(
1523 (e1->bbox.xMax + e1->pos.x) -
1524 (s1->bbox.xMin + s1->pos.x));
1525 l2_new = d6_to_double(
1526 ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -
1527 (w->bbox.xMin + w->pos.x));
1529 if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {
1530 w->linebreak = 1;
1531 s2->linebreak = 0;
1532 exit = 0;
1536 if (i == text_info->length)
1537 break;
1541 assert(text_info->n_lines >= 1);
1542 #undef DIFF
1544 measure_text(render_priv);
1545 trim_whitespace(render_priv);
1547 pen_shift_x = 0.;
1548 pen_shift_y = 0.;
1549 cur_line = 1;
1551 i = 0;
1552 cur = text_info->glyphs + i;
1553 while (i < text_info->length && cur->skip)
1554 cur = text_info->glyphs + ++i;
1555 pen_shift_x = d6_to_double(-cur->pos.x);
1557 for (i = 0; i < text_info->length; ++i) {
1558 cur = text_info->glyphs + i;
1559 if (cur->linebreak) {
1560 while (i < text_info->length && cur->skip && cur->symbol != '\n')
1561 cur = text_info->glyphs + ++i;
1562 double height =
1563 text_info->lines[cur_line - 1].desc +
1564 text_info->lines[cur_line].asc;
1565 cur_line++;
1566 pen_shift_x = d6_to_double(-cur->pos.x);
1567 pen_shift_y += height + render_priv->settings.line_spacing;
1568 ass_msg(render_priv->library, MSGL_DBG2,
1569 "shifting from %d to %d by (%f, %f)", i,
1570 text_info->length - 1, pen_shift_x, pen_shift_y);
1572 cur->pos.x += double_to_d6(pen_shift_x);
1573 cur->pos.y += double_to_d6(pen_shift_y);
1578 * \brief determine karaoke effects
1579 * Karaoke effects cannot be calculated during parse stage (get_next_char()),
1580 * so they are done in a separate step.
1581 * Parse stage: when karaoke style override is found, its parameters are stored in the next glyph's
1582 * (the first glyph of the karaoke word)'s effect_type and effect_timing.
1583 * This function:
1584 * 1. sets effect_type for all glyphs in the word (_karaoke_ word)
1585 * 2. sets effect_timing for all glyphs to x coordinate of the border line between the left and right karaoke parts
1586 * (left part is filled with PrimaryColour, right one - with SecondaryColour).
1588 static void process_karaoke_effects(ASS_Renderer *render_priv)
1590 GlyphInfo *cur, *cur2;
1591 GlyphInfo *s1, *e1; // start and end of the current word
1592 GlyphInfo *s2; // start of the next word
1593 int i;
1594 int timing; // current timing
1595 int tm_start, tm_end; // timings at start and end of the current word
1596 int tm_current;
1597 double dt;
1598 int x;
1599 int x_start, x_end;
1601 tm_current = render_priv->time - render_priv->state.event->Start;
1602 timing = 0;
1603 s1 = s2 = 0;
1604 for (i = 0; i <= render_priv->text_info.length; ++i) {
1605 cur = render_priv->text_info.glyphs + i;
1606 if ((i == render_priv->text_info.length)
1607 || (cur->effect_type != EF_NONE)) {
1608 s1 = s2;
1609 s2 = cur;
1610 if (s1) {
1611 e1 = s2 - 1;
1612 tm_start = timing + s1->effect_skip_timing;
1613 tm_end = tm_start + s1->effect_timing;
1614 timing = tm_end;
1615 x_start = 1000000;
1616 x_end = -1000000;
1617 for (cur2 = s1; cur2 <= e1; ++cur2) {
1618 x_start = FFMIN(x_start, d6_to_int(cur2->bbox.xMin + cur2->pos.x));
1619 x_end = FFMAX(x_end, d6_to_int(cur2->bbox.xMax + cur2->pos.x));
1622 dt = (tm_current - tm_start);
1623 if ((s1->effect_type == EF_KARAOKE)
1624 || (s1->effect_type == EF_KARAOKE_KO)) {
1625 if (dt > 0)
1626 x = x_end + 1;
1627 else
1628 x = x_start;
1629 } else if (s1->effect_type == EF_KARAOKE_KF) {
1630 dt /= (tm_end - tm_start);
1631 x = x_start + (x_end - x_start) * dt;
1632 } else {
1633 ass_msg(render_priv->library, MSGL_ERR,
1634 "Unknown effect type");
1635 continue;
1638 for (cur2 = s1; cur2 <= e1; ++cur2) {
1639 cur2->effect_type = s1->effect_type;
1640 cur2->effect_timing = x - d6_to_int(cur2->pos.x);
1648 * \brief Calculate base point for positioning and rotation
1649 * \param bbox text bbox
1650 * \param alignment alignment
1651 * \param bx, by out: base point coordinates
1653 static void get_base_point(DBBox *bbox, int alignment, double *bx, double *by)
1655 const int halign = alignment & 3;
1656 const int valign = alignment & 12;
1657 if (bx)
1658 switch (halign) {
1659 case HALIGN_LEFT:
1660 *bx = bbox->xMin;
1661 break;
1662 case HALIGN_CENTER:
1663 *bx = (bbox->xMax + bbox->xMin) / 2.0;
1664 break;
1665 case HALIGN_RIGHT:
1666 *bx = bbox->xMax;
1667 break;
1669 if (by)
1670 switch (valign) {
1671 case VALIGN_TOP:
1672 *by = bbox->yMin;
1673 break;
1674 case VALIGN_CENTER:
1675 *by = (bbox->yMax + bbox->yMin) / 2.0;
1676 break;
1677 case VALIGN_SUB:
1678 *by = bbox->yMax;
1679 break;
1684 * Prepare bitmap hash key of a glyph
1686 static void
1687 fill_bitmap_hash(ASS_Renderer *priv, BitmapHashKey *hash_key,
1688 ASS_Drawing *drawing, FT_Vector pen, uint32_t code)
1690 if (!drawing->hash) {
1691 hash_key->font = priv->state.font;
1692 hash_key->size = priv->state.font_size;
1693 hash_key->bold = priv->state.bold;
1694 hash_key->italic = priv->state.italic;
1695 } else {
1696 hash_key->drawing_hash = drawing->hash;
1697 hash_key->size = drawing->scale;
1699 hash_key->ch = code;
1700 hash_key->outline.x = double_to_d16(priv->state.border_x);
1701 hash_key->outline.y = double_to_d16(priv->state.border_y);
1702 hash_key->scale_x = double_to_d16(priv->state.scale_x);
1703 hash_key->scale_y = double_to_d16(priv->state.scale_y);
1704 hash_key->frx = rot_key(priv->state.frx);
1705 hash_key->fry = rot_key(priv->state.fry);
1706 hash_key->frz = rot_key(priv->state.frz);
1707 hash_key->fax = double_to_d16(priv->state.fax);
1708 hash_key->fay = double_to_d16(priv->state.fay);
1709 hash_key->be = priv->state.be;
1710 hash_key->blur = priv->state.blur;
1711 hash_key->border_style = priv->state.style->BorderStyle;
1712 hash_key->shadow_offset.x = double_to_d6(
1713 priv->state.shadow_x * priv->border_scale -
1714 (int) (priv->state.shadow_x * priv->border_scale));
1715 hash_key->shadow_offset.y = double_to_d6(
1716 priv->state.shadow_y * priv->border_scale -
1717 (int) (priv->state.shadow_y * priv->border_scale));
1718 hash_key->flags = priv->state.flags;
1722 * \brief Main ass rendering function, glues everything together
1723 * \param event event to render
1724 * \param event_images struct containing resulting images, will also be initialized
1725 * Process event, appending resulting ASS_Image's to images_root.
1727 static int
1728 ass_render_event(ASS_Renderer *render_priv, ASS_Event *event,
1729 EventImages *event_images)
1731 char *p;
1732 FT_UInt previous;
1733 FT_UInt num_glyphs;
1734 FT_Vector pen;
1735 unsigned code;
1736 DBBox bbox;
1737 int i, j;
1738 int MarginL, MarginR, MarginV;
1739 int last_break;
1740 int alignment, halign, valign;
1741 int kern = render_priv->track->Kerning;
1742 double device_x = 0;
1743 double device_y = 0;
1744 TextInfo *text_info = &render_priv->text_info;
1745 GlyphInfo *glyphs = render_priv->text_info.glyphs;
1746 ASS_Drawing *drawing;
1748 if (event->Style >= render_priv->track->n_styles) {
1749 ass_msg(render_priv->library, MSGL_WARN, "No style found");
1750 return 1;
1752 if (!event->Text) {
1753 ass_msg(render_priv->library, MSGL_WARN, "Empty event");
1754 return 1;
1757 init_render_context(render_priv, event);
1759 drawing = render_priv->state.drawing;
1760 text_info->length = 0;
1761 pen.x = 0;
1762 pen.y = 0;
1763 previous = 0;
1764 num_glyphs = 0;
1765 p = event->Text;
1766 // Event parsing.
1767 while (1) {
1768 // get next char, executing style override
1769 // this affects render_context
1770 do {
1771 code = get_next_char(render_priv, &p);
1772 if (render_priv->state.drawing_mode && code)
1773 ass_drawing_add_char(drawing, (char) code);
1774 } while (code && render_priv->state.drawing_mode); // skip everything in drawing mode
1776 // Parse drawing
1777 if (drawing->i) {
1778 drawing->scale_x = render_priv->state.scale_x *
1779 render_priv->font_scale;
1780 drawing->scale_y = render_priv->state.scale_y *
1781 render_priv->font_scale;
1782 ass_drawing_hash(drawing);
1783 p--;
1784 code = -1;
1787 // face could have been changed in get_next_char
1788 if (!render_priv->state.font) {
1789 free_render_context(render_priv);
1790 return 1;
1793 if (code == 0)
1794 break;
1796 if (text_info->length >= text_info->max_glyphs) {
1797 // Raise maximum number of glyphs
1798 text_info->max_glyphs *= 2;
1799 text_info->glyphs = glyphs =
1800 realloc(text_info->glyphs,
1801 sizeof(GlyphInfo) * text_info->max_glyphs);
1804 // Add kerning to pen
1805 if (kern && previous && code && !drawing->hash) {
1806 FT_Vector delta;
1807 delta =
1808 ass_font_get_kerning(render_priv->state.font, previous,
1809 code);
1810 pen.x += delta.x * render_priv->state.scale_x;
1811 pen.y += delta.y * render_priv->state.scale_y;
1814 ass_font_set_transform(render_priv->state.font,
1815 render_priv->state.scale_x,
1816 render_priv->state.scale_y, NULL);
1818 get_outline_glyph(render_priv, code,
1819 glyphs + text_info->length, drawing);
1821 // Add additional space after italic to non-italic style changes
1822 if (text_info->length &&
1823 glyphs[text_info->length - 1].hash_key.italic &&
1824 !render_priv->state.italic) {
1825 int back = text_info->length - 1;
1826 GlyphInfo *og = &glyphs[back];
1827 while (back && og->bbox.xMax - og->bbox.xMin == 0
1828 && og->hash_key.italic)
1829 og = &glyphs[--back];
1830 if (og->bbox.xMax > og->advance.x) {
1831 // The FreeType oblique slants by 6/16
1832 pen.x += og->bbox.yMax * 0.375;
1836 glyphs[text_info->length].pos.x = pen.x;
1837 glyphs[text_info->length].pos.y = pen.y;
1839 pen.x += glyphs[text_info->length].advance.x;
1840 pen.x += double_to_d6(render_priv->state.hspacing *
1841 render_priv->font_scale
1842 * render_priv->state.scale_x);
1843 pen.y += glyphs[text_info->length].advance.y;
1844 pen.y += (render_priv->state.fay * render_priv->state.scale_y) *
1845 glyphs[text_info->length].advance.x;
1847 previous = code;
1849 glyphs[text_info->length].symbol = code;
1850 glyphs[text_info->length].linebreak = 0;
1851 for (i = 0; i < 4; ++i) {
1852 uint32_t clr = render_priv->state.c[i];
1853 change_alpha(&clr,
1854 mult_alpha(_a(clr), render_priv->state.fade), 1.);
1855 glyphs[text_info->length].c[i] = clr;
1857 glyphs[text_info->length].effect_type = render_priv->state.effect_type;
1858 glyphs[text_info->length].effect_timing =
1859 render_priv->state.effect_timing;
1860 glyphs[text_info->length].effect_skip_timing =
1861 render_priv->state.effect_skip_timing;
1862 glyphs[text_info->length].be = render_priv->state.be;
1863 glyphs[text_info->length].blur = render_priv->state.blur;
1864 glyphs[text_info->length].shadow_x = render_priv->state.shadow_x;
1865 glyphs[text_info->length].shadow_y = render_priv->state.shadow_y;
1866 glyphs[text_info->length].frx = render_priv->state.frx;
1867 glyphs[text_info->length].fry = render_priv->state.fry;
1868 glyphs[text_info->length].frz = render_priv->state.frz;
1869 glyphs[text_info->length].fax = render_priv->state.fax;
1870 glyphs[text_info->length].fay = render_priv->state.fay;
1871 if (drawing->hash) {
1872 glyphs[text_info->length].asc = drawing->asc;
1873 glyphs[text_info->length].desc = drawing->desc;
1874 } else {
1875 ass_font_get_asc_desc(render_priv->state.font, code,
1876 &glyphs[text_info->length].asc,
1877 &glyphs[text_info->length].desc);
1879 glyphs[text_info->length].asc *= render_priv->state.scale_y;
1880 glyphs[text_info->length].desc *= render_priv->state.scale_y;
1883 // fill bitmap hash
1884 fill_bitmap_hash(render_priv, &glyphs[text_info->length].hash_key,
1885 drawing, pen, code);
1887 text_info->length++;
1889 render_priv->state.effect_type = EF_NONE;
1890 render_priv->state.effect_timing = 0;
1891 render_priv->state.effect_skip_timing = 0;
1893 if (drawing->hash) {
1894 ass_drawing_free(drawing);
1895 drawing = render_priv->state.drawing =
1896 ass_drawing_new(render_priv->fontconfig_priv,
1897 render_priv->state.font,
1898 render_priv->ftlibrary);
1903 if (text_info->length == 0) {
1904 // no valid symbols in the event; this can be smth like {comment}
1905 free_render_context(render_priv);
1906 return 1;
1909 // depends on glyph x coordinates being monotonous, so it should be done before line wrap
1910 process_karaoke_effects(render_priv);
1912 // alignments
1913 alignment = render_priv->state.alignment;
1914 halign = alignment & 3;
1915 valign = alignment & 12;
1917 MarginL =
1918 (event->MarginL) ? event->MarginL : render_priv->state.style->MarginL;
1919 MarginR =
1920 (event->MarginR) ? event->MarginR : render_priv->state.style->MarginR;
1921 MarginV =
1922 (event->MarginV) ? event->MarginV : render_priv->state.style->MarginV;
1924 if (render_priv->state.evt_type != EVENT_HSCROLL) {
1925 double max_text_width;
1927 // calculate max length of a line
1928 max_text_width =
1929 x2scr(render_priv,
1930 render_priv->track->PlayResX - MarginR) -
1931 x2scr(render_priv, MarginL);
1933 // rearrange text in several lines
1934 wrap_lines_smart(render_priv, max_text_width);
1936 // align text
1937 last_break = -1;
1938 for (i = 1; i < text_info->length + 1; ++i) { // (text_info->length + 1) is the end of the last line
1939 if ((i == text_info->length)
1940 || glyphs[i].linebreak) {
1941 double width, shift = 0;
1942 GlyphInfo *first_glyph =
1943 glyphs + last_break + 1;
1944 GlyphInfo *last_glyph = glyphs + i - 1;
1946 while (first_glyph < last_glyph && first_glyph->skip)
1947 first_glyph++;
1949 while ((last_glyph > first_glyph)
1950 && ((last_glyph->symbol == '\n')
1951 || (last_glyph->symbol == 0)
1952 || (last_glyph->skip)))
1953 last_glyph--;
1955 width = d6_to_double(
1956 last_glyph->pos.x + last_glyph->advance.x -
1957 first_glyph->pos.x);
1958 if (halign == HALIGN_LEFT) { // left aligned, no action
1959 shift = 0;
1960 } else if (halign == HALIGN_RIGHT) { // right aligned
1961 shift = max_text_width - width;
1962 } else if (halign == HALIGN_CENTER) { // centered
1963 shift = (max_text_width - width) / 2.0;
1965 for (j = last_break + 1; j < i; ++j) {
1966 glyphs[j].pos.x += double_to_d6(shift);
1968 last_break = i - 1;
1971 } else { // render_priv->state.evt_type == EVENT_HSCROLL
1972 measure_text(render_priv);
1975 // determing text bounding box
1976 compute_string_bbox(text_info, &bbox);
1978 // determine device coordinates for text
1980 // x coordinate for everything except positioned events
1981 if (render_priv->state.evt_type == EVENT_NORMAL ||
1982 render_priv->state.evt_type == EVENT_VSCROLL) {
1983 device_x = x2scr(render_priv, MarginL);
1984 } else if (render_priv->state.evt_type == EVENT_HSCROLL) {
1985 if (render_priv->state.scroll_direction == SCROLL_RL)
1986 device_x =
1987 x2scr(render_priv,
1988 render_priv->track->PlayResX -
1989 render_priv->state.scroll_shift);
1990 else if (render_priv->state.scroll_direction == SCROLL_LR)
1991 device_x =
1992 x2scr(render_priv,
1993 render_priv->state.scroll_shift) - (bbox.xMax -
1994 bbox.xMin);
1997 // y coordinate for everything except positioned events
1998 if (render_priv->state.evt_type == EVENT_NORMAL ||
1999 render_priv->state.evt_type == EVENT_HSCROLL) {
2000 if (valign == VALIGN_TOP) { // toptitle
2001 device_y =
2002 y2scr_top(render_priv,
2003 MarginV) + text_info->lines[0].asc;
2004 } else if (valign == VALIGN_CENTER) { // midtitle
2005 double scr_y =
2006 y2scr(render_priv, render_priv->track->PlayResY / 2.0);
2007 device_y = scr_y - (bbox.yMax + bbox.yMin) / 2.0;
2008 } else { // subtitle
2009 double scr_y;
2010 if (valign != VALIGN_SUB)
2011 ass_msg(render_priv->library, MSGL_V,
2012 "Invalid valign, assuming 0 (subtitle)");
2013 scr_y =
2014 y2scr_sub(render_priv,
2015 render_priv->track->PlayResY - MarginV);
2016 device_y = scr_y;
2017 device_y -= text_info->height;
2018 device_y += text_info->lines[0].asc;
2020 } else if (render_priv->state.evt_type == EVENT_VSCROLL) {
2021 if (render_priv->state.scroll_direction == SCROLL_TB)
2022 device_y =
2023 y2scr(render_priv,
2024 render_priv->state.clip_y0 +
2025 render_priv->state.scroll_shift) - (bbox.yMax -
2026 bbox.yMin);
2027 else if (render_priv->state.scroll_direction == SCROLL_BT)
2028 device_y =
2029 y2scr(render_priv,
2030 render_priv->state.clip_y1 -
2031 render_priv->state.scroll_shift);
2034 // positioned events are totally different
2035 if (render_priv->state.evt_type == EVENT_POSITIONED) {
2036 double base_x = 0;
2037 double base_y = 0;
2038 ass_msg(render_priv->library, MSGL_DBG2, "positioned event at %f, %f",
2039 render_priv->state.pos_x, render_priv->state.pos_y);
2040 get_base_point(&bbox, alignment, &base_x, &base_y);
2041 device_x =
2042 x2scr_pos(render_priv, render_priv->state.pos_x) - base_x;
2043 device_y =
2044 y2scr_pos(render_priv, render_priv->state.pos_y) - base_y;
2047 // fix clip coordinates (they depend on alignment)
2048 if (render_priv->state.evt_type == EVENT_NORMAL ||
2049 render_priv->state.evt_type == EVENT_HSCROLL ||
2050 render_priv->state.evt_type == EVENT_VSCROLL) {
2051 render_priv->state.clip_x0 =
2052 x2scr_scaled(render_priv, render_priv->state.clip_x0);
2053 render_priv->state.clip_x1 =
2054 x2scr_scaled(render_priv, render_priv->state.clip_x1);
2055 if (valign == VALIGN_TOP) {
2056 render_priv->state.clip_y0 =
2057 y2scr_top(render_priv, render_priv->state.clip_y0);
2058 render_priv->state.clip_y1 =
2059 y2scr_top(render_priv, render_priv->state.clip_y1);
2060 } else if (valign == VALIGN_CENTER) {
2061 render_priv->state.clip_y0 =
2062 y2scr(render_priv, render_priv->state.clip_y0);
2063 render_priv->state.clip_y1 =
2064 y2scr(render_priv, render_priv->state.clip_y1);
2065 } else if (valign == VALIGN_SUB) {
2066 render_priv->state.clip_y0 =
2067 y2scr_sub(render_priv, render_priv->state.clip_y0);
2068 render_priv->state.clip_y1 =
2069 y2scr_sub(render_priv, render_priv->state.clip_y1);
2071 } else if (render_priv->state.evt_type == EVENT_POSITIONED) {
2072 render_priv->state.clip_x0 =
2073 x2scr_pos_scaled(render_priv, render_priv->state.clip_x0);
2074 render_priv->state.clip_x1 =
2075 x2scr_pos_scaled(render_priv, render_priv->state.clip_x1);
2076 render_priv->state.clip_y0 =
2077 y2scr_pos(render_priv, render_priv->state.clip_y0);
2078 render_priv->state.clip_y1 =
2079 y2scr_pos(render_priv, render_priv->state.clip_y1);
2082 // calculate rotation parameters
2084 DVector center;
2086 if (render_priv->state.have_origin) {
2087 center.x = x2scr(render_priv, render_priv->state.org_x);
2088 center.y = y2scr(render_priv, render_priv->state.org_y);
2089 } else {
2090 double bx = 0., by = 0.;
2091 get_base_point(&bbox, alignment, &bx, &by);
2092 center.x = device_x + bx;
2093 center.y = device_y + by;
2096 for (i = 0; i < text_info->length; ++i) {
2097 GlyphInfo *info = glyphs + i;
2099 if (info->hash_key.frx || info->hash_key.fry
2100 || info->hash_key.frz || info->hash_key.fax
2101 || info->hash_key.fay) {
2102 info->hash_key.shift_x = info->pos.x + double_to_d6(device_x - center.x);
2103 info->hash_key.shift_y =
2104 -(info->pos.y + double_to_d6(device_y - center.y));
2105 } else {
2106 info->hash_key.shift_x = 0;
2107 info->hash_key.shift_y = 0;
2112 // convert glyphs to bitmaps
2113 device_x *= render_priv->font_scale_x;
2114 for (i = 0; i < text_info->length; ++i) {
2115 GlyphInfo *g = glyphs + i;
2116 g->pos.x *= render_priv->font_scale_x;
2117 g->hash_key.advance.x =
2118 double_to_d6(device_x - (int) device_x +
2119 d6_to_double(g->pos.x & SUBPIXEL_MASK)) & ~SUBPIXEL_ACCURACY;
2120 g->hash_key.advance.y =
2121 double_to_d6(device_y - (int) device_y +
2122 d6_to_double(g->pos.y & SUBPIXEL_MASK)) & ~SUBPIXEL_ACCURACY;
2123 get_bitmap_glyph(render_priv, glyphs + i);
2126 memset(event_images, 0, sizeof(*event_images));
2127 event_images->top = device_y - text_info->lines[0].asc;
2128 event_images->height = text_info->height;
2129 event_images->left =
2130 (device_x + bbox.xMin * render_priv->font_scale_x) + 0.5;
2131 event_images->width =
2132 (bbox.xMax - bbox.xMin) * render_priv->font_scale_x + 0.5;
2133 event_images->detect_collisions = render_priv->state.detect_collisions;
2134 event_images->shift_direction = (valign == VALIGN_TOP) ? 1 : -1;
2135 event_images->event = event;
2136 event_images->imgs = render_text(render_priv, (int) device_x, (int) device_y);
2138 free_render_context(render_priv);
2140 return 0;
2144 * \brief deallocate image list
2145 * \param img list pointer
2147 void ass_free_images(ASS_Image *img)
2149 while (img) {
2150 ASS_Image *next = img->next;
2151 free(img);
2152 img = next;
2157 * \brief Check cache limits and reset cache if they are exceeded
2159 static void check_cache_limits(ASS_Renderer *priv, CacheStore *cache)
2161 if (cache->bitmap_cache->cache_size > cache->bitmap_max_size) {
2162 ass_msg(priv->library, MSGL_V,
2163 "Hitting hard bitmap cache limit (was: %ld bytes), "
2164 "resetting.", (long) cache->bitmap_cache->cache_size);
2165 cache->bitmap_cache = ass_bitmap_cache_reset(cache->bitmap_cache);
2166 cache->composite_cache = ass_composite_cache_reset(
2167 cache->composite_cache);
2168 ass_free_images(priv->prev_images_root);
2169 priv->prev_images_root = 0;
2172 if (cache->glyph_cache->count > cache->glyph_max
2173 || cache->glyph_cache->cache_size > cache->bitmap_max_size) {
2174 ass_msg(priv->library, MSGL_V,
2175 "Hitting hard glyph cache limit (was: %d glyphs, %ld bytes), "
2176 "resetting.",
2177 cache->glyph_cache->count, (long) cache->glyph_cache->cache_size);
2178 cache->glyph_cache = ass_glyph_cache_reset(cache->glyph_cache);
2183 * \brief Start a new frame
2185 static int
2186 ass_start_frame(ASS_Renderer *render_priv, ASS_Track *track,
2187 long long now)
2189 ASS_Settings *settings_priv = &render_priv->settings;
2191 if (!render_priv->settings.frame_width
2192 && !render_priv->settings.frame_height)
2193 return 1; // library not initialized
2195 if (render_priv->library != track->library)
2196 return 1;
2198 if (!render_priv->fontconfig_priv)
2199 return 1;
2201 free_list_clear(render_priv);
2203 if (track->n_events == 0)
2204 return 1; // nothing to do
2206 render_priv->track = track;
2207 render_priv->time = now;
2209 ass_lazy_track_init(render_priv);
2211 render_priv->font_scale = settings_priv->font_size_coeff *
2212 render_priv->orig_height / render_priv->track->PlayResY;
2213 if (render_priv->track->ScaledBorderAndShadow)
2214 render_priv->border_scale =
2215 ((double) render_priv->orig_height) /
2216 render_priv->track->PlayResY;
2217 else
2218 render_priv->border_scale = 1.;
2220 // PAR correction
2221 render_priv->font_scale_x = render_priv->settings.aspect /
2222 render_priv->settings.storage_aspect;
2224 render_priv->prev_images_root = render_priv->images_root;
2225 render_priv->images_root = 0;
2227 check_cache_limits(render_priv, &render_priv->cache);
2229 return 0;
2232 static int cmp_event_layer(const void *p1, const void *p2)
2234 ASS_Event *e1 = ((EventImages *) p1)->event;
2235 ASS_Event *e2 = ((EventImages *) p2)->event;
2236 if (e1->Layer < e2->Layer)
2237 return -1;
2238 if (e1->Layer > e2->Layer)
2239 return 1;
2240 if (e1->ReadOrder < e2->ReadOrder)
2241 return -1;
2242 if (e1->ReadOrder > e2->ReadOrder)
2243 return 1;
2244 return 0;
2247 static ASS_RenderPriv *get_render_priv(ASS_Renderer *render_priv,
2248 ASS_Event *event)
2250 if (!event->render_priv)
2251 event->render_priv = calloc(1, sizeof(ASS_RenderPriv));
2252 if (render_priv->render_id != event->render_priv->render_id) {
2253 memset(event->render_priv, 0, sizeof(ASS_RenderPriv));
2254 event->render_priv->render_id = render_priv->render_id;
2257 return event->render_priv;
2260 static int overlap(Segment *s1, Segment *s2)
2262 if (s1->a >= s2->b || s2->a >= s1->b ||
2263 s1->ha >= s2->hb || s2->ha >= s1->hb)
2264 return 0;
2265 return 1;
2268 static int cmp_segment(const void *p1, const void *p2)
2270 return ((Segment *) p1)->a - ((Segment *) p2)->a;
2273 static void
2274 shift_event(ASS_Renderer *render_priv, EventImages *ei, int shift)
2276 ASS_Image *cur = ei->imgs;
2277 while (cur) {
2278 cur->dst_y += shift;
2279 // clip top and bottom
2280 if (cur->dst_y < 0) {
2281 int clip = -cur->dst_y;
2282 cur->h -= clip;
2283 cur->bitmap += clip * cur->stride;
2284 cur->dst_y = 0;
2286 if (cur->dst_y + cur->h >= render_priv->height) {
2287 int clip = cur->dst_y + cur->h - render_priv->height;
2288 cur->h -= clip;
2290 if (cur->h <= 0) {
2291 cur->h = 0;
2292 cur->dst_y = 0;
2294 cur = cur->next;
2296 ei->top += shift;
2299 // dir: 1 - move down
2300 // -1 - move up
2301 static int fit_segment(Segment *s, Segment *fixed, int *cnt, int dir)
2303 int i;
2304 int shift = 0;
2306 if (dir == 1) // move down
2307 for (i = 0; i < *cnt; ++i) {
2308 if (s->b + shift <= fixed[i].a || s->a + shift >= fixed[i].b ||
2309 s->hb <= fixed[i].ha || s->ha >= fixed[i].hb)
2310 continue;
2311 shift = fixed[i].b - s->a;
2312 } else // dir == -1, move up
2313 for (i = *cnt - 1; i >= 0; --i) {
2314 if (s->b + shift <= fixed[i].a || s->a + shift >= fixed[i].b ||
2315 s->hb <= fixed[i].ha || s->ha >= fixed[i].hb)
2316 continue;
2317 shift = fixed[i].a - s->b;
2320 fixed[*cnt].a = s->a + shift;
2321 fixed[*cnt].b = s->b + shift;
2322 fixed[*cnt].ha = s->ha;
2323 fixed[*cnt].hb = s->hb;
2324 (*cnt)++;
2325 qsort(fixed, *cnt, sizeof(Segment), cmp_segment);
2327 return shift;
2330 static void
2331 fix_collisions(ASS_Renderer *render_priv, EventImages *imgs, int cnt)
2333 Segment *used = malloc(cnt * sizeof(*used));
2334 int cnt_used = 0;
2335 int i, j;
2337 // fill used[] with fixed events
2338 for (i = 0; i < cnt; ++i) {
2339 ASS_RenderPriv *priv;
2340 if (!imgs[i].detect_collisions)
2341 continue;
2342 priv = get_render_priv(render_priv, imgs[i].event);
2343 if (priv->height > 0) { // it's a fixed event
2344 Segment s;
2345 s.a = priv->top;
2346 s.b = priv->top + priv->height;
2347 s.ha = priv->left;
2348 s.hb = priv->left + priv->width;
2349 if (priv->height != imgs[i].height) { // no, it's not
2350 ass_msg(render_priv->library, MSGL_WARN,
2351 "Event height has changed");
2352 priv->top = 0;
2353 priv->height = 0;
2354 priv->left = 0;
2355 priv->width = 0;
2357 for (j = 0; j < cnt_used; ++j)
2358 if (overlap(&s, used + j)) { // no, it's not
2359 priv->top = 0;
2360 priv->height = 0;
2361 priv->left = 0;
2362 priv->width = 0;
2364 if (priv->height > 0) { // still a fixed event
2365 used[cnt_used].a = priv->top;
2366 used[cnt_used].b = priv->top + priv->height;
2367 used[cnt_used].ha = priv->left;
2368 used[cnt_used].hb = priv->left + priv->width;
2369 cnt_used++;
2370 shift_event(render_priv, imgs + i, priv->top - imgs[i].top);
2374 qsort(used, cnt_used, sizeof(Segment), cmp_segment);
2376 // try to fit other events in free spaces
2377 for (i = 0; i < cnt; ++i) {
2378 ASS_RenderPriv *priv;
2379 if (!imgs[i].detect_collisions)
2380 continue;
2381 priv = get_render_priv(render_priv, imgs[i].event);
2382 if (priv->height == 0) { // not a fixed event
2383 int shift;
2384 Segment s;
2385 s.a = imgs[i].top;
2386 s.b = imgs[i].top + imgs[i].height;
2387 s.ha = imgs[i].left;
2388 s.hb = imgs[i].left + imgs[i].width;
2389 shift = fit_segment(&s, used, &cnt_used, imgs[i].shift_direction);
2390 if (shift)
2391 shift_event(render_priv, imgs + i, shift);
2392 // make it fixed
2393 priv->top = imgs[i].top;
2394 priv->height = imgs[i].height;
2395 priv->left = imgs[i].left;
2396 priv->width = imgs[i].width;
2401 free(used);
2405 * \brief compare two images
2406 * \param i1 first image
2407 * \param i2 second image
2408 * \return 0 if identical, 1 if different positions, 2 if different content
2410 static int ass_image_compare(ASS_Image *i1, ASS_Image *i2)
2412 if (i1->w != i2->w)
2413 return 2;
2414 if (i1->h != i2->h)
2415 return 2;
2416 if (i1->stride != i2->stride)
2417 return 2;
2418 if (i1->color != i2->color)
2419 return 2;
2420 if (i1->bitmap != i2->bitmap)
2421 return 2;
2422 if (i1->dst_x != i2->dst_x)
2423 return 1;
2424 if (i1->dst_y != i2->dst_y)
2425 return 1;
2426 return 0;
2430 * \brief compare current and previous image list
2431 * \param priv library handle
2432 * \return 0 if identical, 1 if different positions, 2 if different content
2434 static int ass_detect_change(ASS_Renderer *priv)
2436 ASS_Image *img, *img2;
2437 int diff;
2439 img = priv->prev_images_root;
2440 img2 = priv->images_root;
2441 diff = 0;
2442 while (img && diff < 2) {
2443 ASS_Image *next, *next2;
2444 next = img->next;
2445 if (img2) {
2446 int d = ass_image_compare(img, img2);
2447 if (d > diff)
2448 diff = d;
2449 next2 = img2->next;
2450 } else {
2451 // previous list is shorter
2452 diff = 2;
2453 break;
2455 img = next;
2456 img2 = next2;
2459 // is the previous list longer?
2460 if (img2)
2461 diff = 2;
2463 return diff;
2467 * \brief render a frame
2468 * \param priv library handle
2469 * \param track track
2470 * \param now current video timestamp (ms)
2471 * \param detect_change a value describing how the new images differ from the previous ones will be written here:
2472 * 0 if identical, 1 if different positions, 2 if different content.
2473 * Can be NULL, in that case no detection is performed.
2475 ASS_Image *ass_render_frame(ASS_Renderer *priv, ASS_Track *track,
2476 long long now, int *detect_change)
2478 int i, cnt, rc;
2479 EventImages *last;
2480 ASS_Image **tail;
2482 // init frame
2483 rc = ass_start_frame(priv, track, now);
2484 if (rc != 0)
2485 return 0;
2487 // render events separately
2488 cnt = 0;
2489 for (i = 0; i < track->n_events; ++i) {
2490 ASS_Event *event = track->events + i;
2491 if ((event->Start <= now)
2492 && (now < (event->Start + event->Duration))) {
2493 if (cnt >= priv->eimg_size) {
2494 priv->eimg_size += 100;
2495 priv->eimg =
2496 realloc(priv->eimg,
2497 priv->eimg_size * sizeof(EventImages));
2499 rc = ass_render_event(priv, event, priv->eimg + cnt);
2500 if (!rc)
2501 ++cnt;
2505 // sort by layer
2506 qsort(priv->eimg, cnt, sizeof(EventImages), cmp_event_layer);
2508 // call fix_collisions for each group of events with the same layer
2509 last = priv->eimg;
2510 for (i = 1; i < cnt; ++i)
2511 if (last->event->Layer != priv->eimg[i].event->Layer) {
2512 fix_collisions(priv, last, priv->eimg + i - last);
2513 last = priv->eimg + i;
2515 if (cnt > 0)
2516 fix_collisions(priv, last, priv->eimg + cnt - last);
2518 // concat lists
2519 tail = &priv->images_root;
2520 for (i = 0; i < cnt; ++i) {
2521 ASS_Image *cur = priv->eimg[i].imgs;
2522 while (cur) {
2523 *tail = cur;
2524 tail = &cur->next;
2525 cur = cur->next;
2529 if (detect_change)
2530 *detect_change = ass_detect_change(priv);
2532 // free the previous image list
2533 ass_free_images(priv->prev_images_root);
2534 priv->prev_images_root = 0;
2536 return priv->images_root;