Fix TextInfo reallocation
[libass.git] / libass / ass_font.c
blobad2863c5786ff6a0156e03d2da60252ec1754dcc
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 <inttypes.h>
24 #include <ft2build.h>
25 #include FT_FREETYPE_H
26 #include FT_SYNTHESIS_H
27 #include FT_GLYPH_H
28 #include FT_TRUETYPE_TABLES_H
29 #include FT_OUTLINE_H
31 #include "ass.h"
32 #include "ass_library.h"
33 #include "ass_font.h"
34 #include "ass_bitmap.h"
35 #include "ass_cache.h"
36 #include "ass_fontconfig.h"
37 #include "ass_utils.h"
39 #define VERTICAL_LOWER_BOUND 0x02f1
41 /**
42 * Select a good charmap, prefer Microsoft Unicode charmaps.
43 * Otherwise, let FreeType decide.
45 static void charmap_magic(ASS_Library *library, FT_Face face)
47 int i;
48 int ms_cmap = -1;
50 // Search for a Microsoft Unicode cmap
51 for (i = 0; i < face->num_charmaps; ++i) {
52 FT_CharMap cmap = face->charmaps[i];
53 unsigned pid = cmap->platform_id;
54 unsigned eid = cmap->encoding_id;
55 if (pid == 3 /*microsoft */
56 && (eid == 1 /*unicode bmp */
57 || eid == 10 /*full unicode */ )) {
58 FT_Set_Charmap(face, cmap);
59 return;
60 } else if (pid == 3 && ms_cmap < 0)
61 ms_cmap = i;
64 // Try the first Microsoft cmap if no Microsoft Unicode cmap was found
65 if (ms_cmap >= 0) {
66 FT_CharMap cmap = face->charmaps[ms_cmap];
67 FT_Set_Charmap(face, cmap);
68 return;
71 if (!face->charmap) {
72 if (face->num_charmaps == 0) {
73 ass_msg(library, MSGL_WARN, "Font face with no charmaps");
74 return;
76 ass_msg(library, MSGL_WARN,
77 "No charmap autodetected, trying the first one");
78 FT_Set_Charmap(face, face->charmaps[0]);
79 return;
83 /**
84 * \brief find a memory font by name
86 static int find_font(ASS_Library *library, char *name)
88 int i;
89 for (i = 0; i < library->num_fontdata; ++i)
90 if (strcasecmp(name, library->fontdata[i].name) == 0)
91 return i;
92 return -1;
95 static void face_set_size(FT_Face face, double size);
97 static void buggy_font_workaround(FT_Face face)
99 // Some fonts have zero Ascender/Descender fields in 'hhea' table.
100 // In this case, get the information from 'os2' table or, as
101 // a last resort, from face.bbox.
102 if (face->ascender + face->descender == 0 || face->height == 0) {
103 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
104 if (os2) {
105 face->ascender = os2->sTypoAscender;
106 face->descender = os2->sTypoDescender;
107 face->height = face->ascender - face->descender;
108 } else {
109 face->ascender = face->bbox.yMax;
110 face->descender = face->bbox.yMin;
111 face->height = face->ascender - face->descender;
117 * \brief Select a face with the given charcode and add it to ASS_Font
118 * \return index of the new face in font->faces, -1 if failed
120 static int add_face(void *fc_priv, ASS_Font *font, uint32_t ch)
122 char *path;
123 int index;
124 FT_Face face;
125 int error;
126 int mem_idx;
128 if (font->n_faces == ASS_FONT_MAX_FACES)
129 return -1;
131 path =
132 fontconfig_select(font->library, fc_priv, font->desc.family,
133 font->desc.treat_family_as_pattern,
134 font->desc.bold, font->desc.italic, &index, ch);
135 if (!path)
136 return -1;
138 mem_idx = find_font(font->library, path);
139 if (mem_idx >= 0) {
140 error =
141 FT_New_Memory_Face(font->ftlibrary,
142 (unsigned char *) font->library->
143 fontdata[mem_idx].data,
144 font->library->fontdata[mem_idx].size, index,
145 &face);
146 if (error) {
147 ass_msg(font->library, MSGL_WARN,
148 "Error opening memory font: '%s'", path);
149 free(path);
150 return -1;
152 } else {
153 error = FT_New_Face(font->ftlibrary, path, index, &face);
154 if (error) {
155 ass_msg(font->library, MSGL_WARN,
156 "Error opening font: '%s', %d", path, index);
157 free(path);
158 return -1;
161 charmap_magic(font->library, face);
162 buggy_font_workaround(face);
164 font->faces[font->n_faces++] = face;
165 face_set_size(face, font->size);
166 free(path);
167 return font->n_faces - 1;
171 * \brief Create a new ASS_Font according to "desc" argument
173 ASS_Font *ass_font_new(void *font_cache, ASS_Library *library,
174 FT_Library ftlibrary, void *fc_priv,
175 ASS_FontDesc *desc)
177 int error;
178 ASS_Font *fontp;
179 ASS_Font font;
181 fontp = ass_font_cache_find((Hashmap *) font_cache, desc);
182 if (fontp)
183 return fontp;
185 font.library = library;
186 font.ftlibrary = ftlibrary;
187 font.n_faces = 0;
188 font.desc.family = strdup(desc->family);
189 font.desc.treat_family_as_pattern = desc->treat_family_as_pattern;
190 font.desc.bold = desc->bold;
191 font.desc.italic = desc->italic;
192 font.desc.vertical = desc->vertical;
194 font.scale_x = font.scale_y = 1.;
195 font.v.x = font.v.y = 0;
196 font.size = 0.;
198 error = add_face(fc_priv, &font, 0);
199 if (error == -1) {
200 free(font.desc.family);
201 return 0;
202 } else
203 return ass_font_cache_add((Hashmap *) font_cache, &font);
207 * \brief Set font transformation matrix and shift vector
209 void ass_font_set_transform(ASS_Font *font, double scale_x,
210 double scale_y, FT_Vector *v)
212 font->scale_x = scale_x;
213 font->scale_y = scale_y;
214 if (v) {
215 font->v.x = v->x;
216 font->v.y = v->y;
220 static void face_set_size(FT_Face face, double size)
222 TT_HoriHeader *hori = FT_Get_Sfnt_Table(face, ft_sfnt_hhea);
223 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
224 double mscale = 1.;
225 FT_Size_RequestRec rq;
226 FT_Size_Metrics *m = &face->size->metrics;
227 // VSFilter uses metrics from TrueType OS/2 table
228 // The idea was borrowed from asa (http://asa.diac24.net)
229 if (hori && os2) {
230 int hori_height = hori->Ascender - hori->Descender;
231 int os2_height = os2->usWinAscent + os2->usWinDescent;
232 if (hori_height && os2_height)
233 mscale = (double) hori_height / os2_height;
235 memset(&rq, 0, sizeof(rq));
236 rq.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
237 rq.width = 0;
238 rq.height = double_to_d6(size * mscale);
239 rq.horiResolution = rq.vertResolution = 0;
240 FT_Request_Size(face, &rq);
241 m->ascender /= mscale;
242 m->descender /= mscale;
243 m->height /= mscale;
247 * \brief Set font size
249 void ass_font_set_size(ASS_Font *font, double size)
251 int i;
252 if (font->size != size) {
253 font->size = size;
254 for (i = 0; i < font->n_faces; ++i)
255 face_set_size(font->faces[i], size);
260 * \brief Get maximal font ascender and descender.
261 * \param ch character code
262 * The values are extracted from the font face that provides glyphs for the given character
264 void ass_font_get_asc_desc(ASS_Font *font, uint32_t ch, int *asc,
265 int *desc)
267 int i;
268 for (i = 0; i < font->n_faces; ++i) {
269 FT_Face face = font->faces[i];
270 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
271 if (FT_Get_Char_Index(face, ch)) {
272 int y_scale = face->size->metrics.y_scale;
273 if (os2) {
274 *asc = FT_MulFix(os2->usWinAscent, y_scale);
275 *desc = FT_MulFix(os2->usWinDescent, y_scale);
276 } else {
277 *asc = FT_MulFix(face->ascender, y_scale);
278 *desc = FT_MulFix(-face->descender, y_scale);
280 if (font->desc.vertical && ch >= VERTICAL_LOWER_BOUND) {
281 *asc = FT_MulFix(face->max_advance_width, y_scale);
283 return;
287 *asc = *desc = 0;
291 * Strike a glyph with a horizontal line; it's possible to underline it
292 * and/or strike through it. For the line's position and size, truetype
293 * tables are consulted. Obviously this relies on the data in the tables
294 * being accurate.
297 static int ass_strike_outline_glyph(FT_Face face, ASS_Font *font,
298 FT_Glyph glyph, int under, int through)
300 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
301 TT_Postscript *ps = FT_Get_Sfnt_Table(face, ft_sfnt_post);
302 FT_Outline *ol = &((FT_OutlineGlyph) glyph)->outline;
303 int bear, advance, y_scale, i, dir;
305 if (!under && !through)
306 return 0;
308 // Grow outline
309 i = (under ? 4 : 0) + (through ? 4 : 0);
310 ol->points = realloc(ol->points, sizeof(FT_Vector) *
311 (ol->n_points + i));
312 ol->tags = realloc(ol->tags, ol->n_points + i);
313 i = !!under + !!through;
314 ol->contours = realloc(ol->contours, sizeof(short) *
315 (ol->n_contours + i));
317 // If the bearing is negative, the glyph starts left of the current
318 // pen position
319 bear = FFMIN(face->glyph->metrics.horiBearingX, 0);
320 // We're adding half a pixel to avoid small gaps
321 advance = d16_to_d6(glyph->advance.x) + 32;
322 y_scale = face->size->metrics.y_scale;
324 // Reverse drawing direction for non-truetype fonts
325 dir = FT_Outline_Get_Orientation(ol);
327 // Add points to the outline
328 if (under && ps) {
329 int pos, size;
330 pos = FT_MulFix(ps->underlinePosition, y_scale * font->scale_y);
331 size = FT_MulFix(ps->underlineThickness,
332 y_scale * font->scale_y / 2);
334 if (pos > 0 || size <= 0)
335 return 1;
337 FT_Vector points[4] = {
338 {.x = bear, .y = pos + size},
339 {.x = advance, .y = pos + size},
340 {.x = advance, .y = pos - size},
341 {.x = bear, .y = pos - size},
344 if (dir == FT_ORIENTATION_TRUETYPE) {
345 for (i = 0; i < 4; i++) {
346 ol->points[ol->n_points] = points[i];
347 ol->tags[ol->n_points++] = 1;
349 } else {
350 for (i = 3; i >= 0; i--) {
351 ol->points[ol->n_points] = points[i];
352 ol->tags[ol->n_points++] = 1;
356 ol->contours[ol->n_contours++] = ol->n_points - 1;
359 if (through && os2) {
360 int pos, size;
361 pos = FT_MulFix(os2->yStrikeoutPosition, y_scale * font->scale_y);
362 size = FT_MulFix(os2->yStrikeoutSize, y_scale * font->scale_y / 2);
364 if (pos < 0 || size <= 0)
365 return 1;
367 FT_Vector points[4] = {
368 {.x = bear, .y = pos + size},
369 {.x = advance, .y = pos + size},
370 {.x = advance, .y = pos - size},
371 {.x = bear, .y = pos - size},
374 if (dir == FT_ORIENTATION_TRUETYPE) {
375 for (i = 0; i < 4; i++) {
376 ol->points[ol->n_points] = points[i];
377 ol->tags[ol->n_points++] = 1;
379 } else {
380 for (i = 3; i >= 0; i--) {
381 ol->points[ol->n_points] = points[i];
382 ol->tags[ol->n_points++] = 1;
386 ol->contours[ol->n_contours++] = ol->n_points - 1;
389 return 0;
393 * Slightly embold a glyph without touching its metrics
395 static void ass_glyph_embolden(FT_GlyphSlot slot)
397 int str;
399 if (slot->format != FT_GLYPH_FORMAT_OUTLINE)
400 return;
402 str = FT_MulFix(slot->face->units_per_EM,
403 slot->face->size->metrics.y_scale) / 64;
405 FT_Outline_Embolden(&slot->outline, str);
409 * \brief Get a glyph
410 * \param ch character code
412 FT_Glyph ass_font_get_glyph(void *fontconfig_priv, ASS_Font *font,
413 uint32_t ch, ASS_Hinting hinting, int deco)
415 int error;
416 int index = 0;
417 int i;
418 FT_Glyph glyph;
419 FT_Face face = 0;
420 int flags = 0;
421 int vertical = font->desc.vertical;
423 if (ch < 0x20)
424 return 0;
425 // Handle NBSP like a regular space when rendering the glyph
426 if (ch == 0xa0)
427 ch = ' ';
428 if (font->n_faces == 0)
429 return 0;
431 for (i = 0; i < font->n_faces; ++i) {
432 face = font->faces[i];
433 index = FT_Get_Char_Index(face, ch);
434 if (index)
435 break;
438 #ifdef CONFIG_FONTCONFIG
439 if (index == 0) {
440 int face_idx;
441 ass_msg(font->library, MSGL_INFO,
442 "Glyph 0x%X not found, selecting one more "
443 "font for (%s, %d, %d)", ch, font->desc.family,
444 font->desc.bold, font->desc.italic);
445 face_idx = add_face(fontconfig_priv, font, ch);
446 if (face_idx >= 0) {
447 face = font->faces[face_idx];
448 index = FT_Get_Char_Index(face, ch);
449 if (index == 0) {
450 ass_msg(font->library, MSGL_ERR,
451 "Glyph 0x%X not found in font for (%s, %d, %d)",
452 ch, font->desc.family, font->desc.bold,
453 font->desc.italic);
457 #endif
459 flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH
460 | FT_LOAD_IGNORE_TRANSFORM;
461 switch (hinting) {
462 case ASS_HINTING_NONE:
463 flags |= FT_LOAD_NO_HINTING;
464 break;
465 case ASS_HINTING_LIGHT:
466 flags |= FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT;
467 break;
468 case ASS_HINTING_NORMAL:
469 flags |= FT_LOAD_FORCE_AUTOHINT;
470 break;
471 case ASS_HINTING_NATIVE:
472 break;
475 error = FT_Load_Glyph(face, index, flags);
476 if (error) {
477 ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
478 index);
479 return 0;
481 if (!(face->style_flags & FT_STYLE_FLAG_ITALIC) &&
482 (font->desc.italic > 55)) {
483 FT_GlyphSlot_Oblique(face->glyph);
486 if (!(face->style_flags & FT_STYLE_FLAG_BOLD) &&
487 (font->desc.bold > 80)) {
488 ass_glyph_embolden(face->glyph);
490 error = FT_Get_Glyph(face->glyph, &glyph);
491 if (error) {
492 ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
493 index);
494 return 0;
497 // Rotate glyph, if needed
498 if (vertical && ch >= VERTICAL_LOWER_BOUND) {
499 FT_Matrix m = { 0, double_to_d16(-1.0), double_to_d16(1.0), 0 };
500 FT_Outline_Transform(&((FT_OutlineGlyph) glyph)->outline, &m);
501 FT_Outline_Translate(&((FT_OutlineGlyph) glyph)->outline,
502 face->glyph->metrics.vertAdvance,
504 glyph->advance.x = face->glyph->linearVertAdvance;
507 // Apply scaling and shift
508 FT_Matrix scale = { double_to_d16(font->scale_x), 0, 0,
509 double_to_d16(font->scale_y) };
510 FT_Outline *outl = &((FT_OutlineGlyph) glyph)->outline;
511 FT_Outline_Transform(outl, &scale);
512 FT_Outline_Translate(outl, font->v.x, font->v.y);
513 glyph->advance.x *= font->scale_x;
515 ass_strike_outline_glyph(face, font, glyph, deco & DECO_UNDERLINE,
516 deco & DECO_STRIKETHROUGH);
518 return glyph;
522 * \brief Get kerning for the pair of glyphs.
524 FT_Vector ass_font_get_kerning(ASS_Font *font, uint32_t c1, uint32_t c2)
526 FT_Vector v = { 0, 0 };
527 int i;
529 if (font->desc.vertical)
530 return v;
532 for (i = 0; i < font->n_faces; ++i) {
533 FT_Face face = font->faces[i];
534 int i1 = FT_Get_Char_Index(face, c1);
535 int i2 = FT_Get_Char_Index(face, c2);
536 if (i1 && i2) {
537 if (FT_HAS_KERNING(face))
538 FT_Get_Kerning(face, i1, i2, FT_KERNING_DEFAULT, &v);
539 return v;
541 if (i1 || i2) // these glyphs are from different font faces, no kerning information
542 return v;
544 return v;
548 * \brief Deallocate ASS_Font
550 void ass_font_free(ASS_Font *font)
552 int i;
553 for (i = 0; i < font->n_faces; ++i)
554 if (font->faces[i])
555 FT_Done_Face(font->faces[i]);
556 if (font->desc.family)
557 free(font->desc.family);
558 free(font);
562 * \brief Calculate the cbox of a series of points
564 static void
565 get_contour_cbox(FT_BBox *box, FT_Vector *points, int start, int end)
567 box->xMin = box->yMin = INT_MAX;
568 box->xMax = box->yMax = INT_MIN;
569 int i;
571 for (i = start; i <= end; i++) {
572 box->xMin = (points[i].x < box->xMin) ? points[i].x : box->xMin;
573 box->xMax = (points[i].x > box->xMax) ? points[i].x : box->xMax;
574 box->yMin = (points[i].y < box->yMin) ? points[i].y : box->yMin;
575 box->yMax = (points[i].y > box->yMax) ? points[i].y : box->yMax;
580 * \brief Determine winding direction of a contour
581 * \return direction; 0 = clockwise
583 static int get_contour_direction(FT_Vector *points, int start, int end)
585 int i;
586 long long sum = 0;
587 int x = points[start].x;
588 int y = points[start].y;
589 for (i = start + 1; i <= end; i++) {
590 sum += x * (points[i].y - y) - y * (points[i].x - x);
591 x = points[i].x;
592 y = points[i].y;
594 sum += x * (points[start].y - y) - y * (points[start].x - x);
595 return sum > 0;
599 * \brief Fix-up stroker result for huge borders by removing inside contours
600 * that would reverse in size
602 void fix_freetype_stroker(FT_OutlineGlyph glyph, int border_x, int border_y)
604 int nc = glyph->outline.n_contours;
605 int begin, stop;
606 char modified = 0;
607 char *valid_cont = malloc(nc);
608 int start = 0;
609 int end = -1;
610 FT_BBox *boxes = malloc(nc * sizeof(FT_BBox));
611 int i, j;
612 int inside_direction;
614 inside_direction = FT_Outline_Get_Orientation(&glyph->outline) ==
615 FT_ORIENTATION_TRUETYPE;
617 // create a list of cboxes of the contours
618 for (i = 0; i < nc; i++) {
619 start = end + 1;
620 end = glyph->outline.contours[i];
621 get_contour_cbox(&boxes[i], glyph->outline.points, start, end);
624 // for each contour, check direction and whether it's "outside"
625 // or contained in another contour
626 end = -1;
627 for (i = 0; i < nc; i++) {
628 start = end + 1;
629 end = glyph->outline.contours[i];
630 int dir = get_contour_direction(glyph->outline.points, start, end);
631 valid_cont[i] = 1;
632 if (dir == inside_direction) {
633 for (j = 0; j < nc; j++) {
634 if (i == j)
635 continue;
636 if (boxes[i].xMin >= boxes[j].xMin &&
637 boxes[i].xMax <= boxes[j].xMax &&
638 boxes[i].yMin >= boxes[j].yMin &&
639 boxes[i].yMax <= boxes[j].yMax)
640 goto check_inside;
642 /* "inside" contour but we can't find anything it could be
643 * inside of - assume the font is buggy and it should be
644 * an "outside" contour, and reverse it */
645 for (j = 0; j < (end + 1 - start) / 2; j++) {
646 FT_Vector temp = glyph->outline.points[start + j];
647 char temp2 = glyph->outline.tags[start + j];
648 glyph->outline.points[start + j] = glyph->outline.points[end - j];
649 glyph->outline.points[end - j] = temp;
650 glyph->outline.tags[start + j] = glyph->outline.tags[end - j];
651 glyph->outline.tags[end - j] = temp2;
653 dir ^= 1;
655 check_inside:
656 if (dir == inside_direction) {
657 FT_BBox box;
658 get_contour_cbox(&box, glyph->outline.points, start, end);
659 int width = box.xMax - box.xMin;
660 int height = box.yMax - box.yMin;
661 if (width < border_x * 2 || height < border_y * 2) {
662 valid_cont[i] = 0;
663 modified = 1;
668 // zero-out contours that can be removed; much simpler than copying
669 if (modified) {
670 for (i = 0; i < nc; i++) {
671 if (valid_cont[i])
672 continue;
673 begin = (i == 0) ? 0 : glyph->outline.contours[i - 1] + 1;
674 stop = glyph->outline.contours[i];
675 for (j = begin; j <= stop; j++) {
676 glyph->outline.points[j].x = 0;
677 glyph->outline.points[j].y = 0;
678 glyph->outline.tags[j] = 0;
683 free(boxes);
684 free(valid_cont);