Relicense to ISC
[libass.git] / libass / ass_font.c
blob74467df6b03aaebea00dbe2811aa3733685a3f2d
1 /*
2 * Copyright (C) 2006 Evgeniy Stepanov <eugeni.stepanov@gmail.com>
4 * This file is part of libass.
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include "config.h"
21 #include <inttypes.h>
22 #include <ft2build.h>
23 #include FT_FREETYPE_H
24 #include FT_SYNTHESIS_H
25 #include FT_GLYPH_H
26 #include FT_TRUETYPE_TABLES_H
27 #include FT_OUTLINE_H
28 #include <strings.h>
30 #include "ass.h"
31 #include "ass_library.h"
32 #include "ass_font.h"
33 #include "ass_bitmap.h"
34 #include "ass_cache.h"
35 #include "ass_fontconfig.h"
36 #include "ass_utils.h"
38 #define VERTICAL_LOWER_BOUND 0x02f1
40 /**
41 * Select a good charmap, prefer Microsoft Unicode charmaps.
42 * Otherwise, let FreeType decide.
44 static void charmap_magic(ASS_Library *library, FT_Face face)
46 int i;
47 int ms_cmap = -1;
49 // Search for a Microsoft Unicode cmap
50 for (i = 0; i < face->num_charmaps; ++i) {
51 FT_CharMap cmap = face->charmaps[i];
52 unsigned pid = cmap->platform_id;
53 unsigned eid = cmap->encoding_id;
54 if (pid == 3 /*microsoft */
55 && (eid == 1 /*unicode bmp */
56 || eid == 10 /*full unicode */ )) {
57 FT_Set_Charmap(face, cmap);
58 return;
59 } else if (pid == 3 && ms_cmap < 0)
60 ms_cmap = i;
63 // Try the first Microsoft cmap if no Microsoft Unicode cmap was found
64 if (ms_cmap >= 0) {
65 FT_CharMap cmap = face->charmaps[ms_cmap];
66 FT_Set_Charmap(face, cmap);
67 return;
70 if (!face->charmap) {
71 if (face->num_charmaps == 0) {
72 ass_msg(library, MSGL_WARN, "Font face with no charmaps");
73 return;
75 ass_msg(library, MSGL_WARN,
76 "No charmap autodetected, trying the first one");
77 FT_Set_Charmap(face, face->charmaps[0]);
78 return;
82 /**
83 * \brief find a memory font by name
85 static int find_font(ASS_Library *library, char *name)
87 int i;
88 for (i = 0; i < library->num_fontdata; ++i)
89 if (strcasecmp(name, library->fontdata[i].name) == 0)
90 return i;
91 return -1;
94 static void face_set_size(FT_Face face, double size);
96 static void buggy_font_workaround(FT_Face face)
98 // Some fonts have zero Ascender/Descender fields in 'hhea' table.
99 // In this case, get the information from 'os2' table or, as
100 // a last resort, from face.bbox.
101 if (face->ascender + face->descender == 0 || face->height == 0) {
102 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
103 if (os2) {
104 face->ascender = os2->sTypoAscender;
105 face->descender = os2->sTypoDescender;
106 face->height = face->ascender - face->descender;
107 } else {
108 face->ascender = face->bbox.yMax;
109 face->descender = face->bbox.yMin;
110 face->height = face->ascender - face->descender;
116 * \brief Select a face with the given charcode and add it to ASS_Font
117 * \return index of the new face in font->faces, -1 if failed
119 static int add_face(void *fc_priv, ASS_Font *font, uint32_t ch)
121 char *path;
122 int index;
123 FT_Face face;
124 int error;
125 int mem_idx;
127 if (font->n_faces == ASS_FONT_MAX_FACES)
128 return -1;
130 path =
131 fontconfig_select(font->library, fc_priv, font->desc.family,
132 font->desc.treat_family_as_pattern,
133 font->desc.bold, font->desc.italic, &index, ch);
134 if (!path)
135 return -1;
137 mem_idx = find_font(font->library, path);
138 if (mem_idx >= 0) {
139 error =
140 FT_New_Memory_Face(font->ftlibrary,
141 (unsigned char *) font->library->
142 fontdata[mem_idx].data,
143 font->library->fontdata[mem_idx].size, index,
144 &face);
145 if (error) {
146 ass_msg(font->library, MSGL_WARN,
147 "Error opening memory font: '%s'", path);
148 free(path);
149 return -1;
151 } else {
152 error = FT_New_Face(font->ftlibrary, path, index, &face);
153 if (error) {
154 ass_msg(font->library, MSGL_WARN,
155 "Error opening font: '%s', %d", path, index);
156 free(path);
157 return -1;
160 charmap_magic(font->library, face);
161 buggy_font_workaround(face);
163 font->faces[font->n_faces++] = face;
164 face_set_size(face, font->size);
165 free(path);
166 return font->n_faces - 1;
170 * \brief Create a new ASS_Font according to "desc" argument
172 ASS_Font *ass_font_new(void *font_cache, ASS_Library *library,
173 FT_Library ftlibrary, void *fc_priv,
174 ASS_FontDesc *desc)
176 int error;
177 ASS_Font *fontp;
178 ASS_Font font;
180 fontp = ass_font_cache_find((Hashmap *) font_cache, desc);
181 if (fontp)
182 return fontp;
184 font.library = library;
185 font.ftlibrary = ftlibrary;
186 font.n_faces = 0;
187 font.desc.family = strdup(desc->family);
188 font.desc.treat_family_as_pattern = desc->treat_family_as_pattern;
189 font.desc.bold = desc->bold;
190 font.desc.italic = desc->italic;
191 font.desc.vertical = desc->vertical;
193 font.scale_x = font.scale_y = 1.;
194 font.v.x = font.v.y = 0;
195 font.size = 0.;
197 error = add_face(fc_priv, &font, 0);
198 if (error == -1) {
199 free(font.desc.family);
200 return 0;
201 } else
202 return ass_font_cache_add((Hashmap *) font_cache, &font);
206 * \brief Set font transformation matrix and shift vector
208 void ass_font_set_transform(ASS_Font *font, double scale_x,
209 double scale_y, FT_Vector *v)
211 font->scale_x = scale_x;
212 font->scale_y = scale_y;
213 if (v) {
214 font->v.x = v->x;
215 font->v.y = v->y;
219 static void face_set_size(FT_Face face, double size)
221 TT_HoriHeader *hori = FT_Get_Sfnt_Table(face, ft_sfnt_hhea);
222 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
223 double mscale = 1.;
224 FT_Size_RequestRec rq;
225 FT_Size_Metrics *m = &face->size->metrics;
226 // VSFilter uses metrics from TrueType OS/2 table
227 // The idea was borrowed from asa (http://asa.diac24.net)
228 if (hori && os2) {
229 int hori_height = hori->Ascender - hori->Descender;
230 int os2_height = os2->usWinAscent + os2->usWinDescent;
231 if (hori_height && os2_height)
232 mscale = (double) hori_height / os2_height;
234 memset(&rq, 0, sizeof(rq));
235 rq.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
236 rq.width = 0;
237 rq.height = double_to_d6(size * mscale);
238 rq.horiResolution = rq.vertResolution = 0;
239 FT_Request_Size(face, &rq);
240 m->ascender /= mscale;
241 m->descender /= mscale;
242 m->height /= mscale;
246 * \brief Set font size
248 void ass_font_set_size(ASS_Font *font, double size)
250 int i;
251 if (font->size != size) {
252 font->size = size;
253 for (i = 0; i < font->n_faces; ++i)
254 face_set_size(font->faces[i], size);
259 * \brief Get maximal font ascender and descender.
260 * \param ch character code
261 * The values are extracted from the font face that provides glyphs for the given character
263 void ass_font_get_asc_desc(ASS_Font *font, uint32_t ch, int *asc,
264 int *desc)
266 int i;
267 for (i = 0; i < font->n_faces; ++i) {
268 FT_Face face = font->faces[i];
269 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
270 if (FT_Get_Char_Index(face, ch)) {
271 int y_scale = face->size->metrics.y_scale;
272 if (os2) {
273 *asc = FT_MulFix(os2->usWinAscent, y_scale);
274 *desc = FT_MulFix(os2->usWinDescent, y_scale);
275 } else {
276 *asc = FT_MulFix(face->ascender, y_scale);
277 *desc = FT_MulFix(-face->descender, y_scale);
279 if (font->desc.vertical && ch >= VERTICAL_LOWER_BOUND) {
280 *asc = FT_MulFix(face->max_advance_width, y_scale);
282 return;
286 *asc = *desc = 0;
290 * Strike a glyph with a horizontal line; it's possible to underline it
291 * and/or strike through it. For the line's position and size, truetype
292 * tables are consulted. Obviously this relies on the data in the tables
293 * being accurate.
296 static int ass_strike_outline_glyph(FT_Face face, ASS_Font *font,
297 FT_Glyph glyph, int under, int through)
299 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
300 TT_Postscript *ps = FT_Get_Sfnt_Table(face, ft_sfnt_post);
301 FT_Outline *ol = &((FT_OutlineGlyph) glyph)->outline;
302 int bear, advance, y_scale, i, dir;
304 if (!under && !through)
305 return 0;
307 // Grow outline
308 i = (under ? 4 : 0) + (through ? 4 : 0);
309 ol->points = realloc(ol->points, sizeof(FT_Vector) *
310 (ol->n_points + i));
311 ol->tags = realloc(ol->tags, ol->n_points + i);
312 i = !!under + !!through;
313 ol->contours = realloc(ol->contours, sizeof(short) *
314 (ol->n_contours + i));
316 // If the bearing is negative, the glyph starts left of the current
317 // pen position
318 bear = FFMIN(face->glyph->metrics.horiBearingX, 0);
319 // We're adding half a pixel to avoid small gaps
320 advance = d16_to_d6(glyph->advance.x) + 32;
321 y_scale = face->size->metrics.y_scale;
323 // Reverse drawing direction for non-truetype fonts
324 dir = FT_Outline_Get_Orientation(ol);
326 // Add points to the outline
327 if (under && ps) {
328 int pos, size;
329 pos = FT_MulFix(ps->underlinePosition, y_scale * font->scale_y);
330 size = FT_MulFix(ps->underlineThickness,
331 y_scale * font->scale_y / 2);
333 if (pos > 0 || size <= 0)
334 return 1;
336 FT_Vector points[4] = {
337 {.x = bear, .y = pos + size},
338 {.x = advance, .y = pos + size},
339 {.x = advance, .y = pos - size},
340 {.x = bear, .y = pos - size},
343 if (dir == FT_ORIENTATION_TRUETYPE) {
344 for (i = 0; i < 4; i++) {
345 ol->points[ol->n_points] = points[i];
346 ol->tags[ol->n_points++] = 1;
348 } else {
349 for (i = 3; i >= 0; i--) {
350 ol->points[ol->n_points] = points[i];
351 ol->tags[ol->n_points++] = 1;
355 ol->contours[ol->n_contours++] = ol->n_points - 1;
358 if (through && os2) {
359 int pos, size;
360 pos = FT_MulFix(os2->yStrikeoutPosition, y_scale * font->scale_y);
361 size = FT_MulFix(os2->yStrikeoutSize, y_scale * font->scale_y / 2);
363 if (pos < 0 || size <= 0)
364 return 1;
366 FT_Vector points[4] = {
367 {.x = bear, .y = pos + size},
368 {.x = advance, .y = pos + size},
369 {.x = advance, .y = pos - size},
370 {.x = bear, .y = pos - size},
373 if (dir == FT_ORIENTATION_TRUETYPE) {
374 for (i = 0; i < 4; i++) {
375 ol->points[ol->n_points] = points[i];
376 ol->tags[ol->n_points++] = 1;
378 } else {
379 for (i = 3; i >= 0; i--) {
380 ol->points[ol->n_points] = points[i];
381 ol->tags[ol->n_points++] = 1;
385 ol->contours[ol->n_contours++] = ol->n_points - 1;
388 return 0;
392 * Slightly embold a glyph without touching its metrics
394 static void ass_glyph_embolden(FT_GlyphSlot slot)
396 int str;
398 if (slot->format != FT_GLYPH_FORMAT_OUTLINE)
399 return;
401 str = FT_MulFix(slot->face->units_per_EM,
402 slot->face->size->metrics.y_scale) / 64;
404 FT_Outline_Embolden(&slot->outline, str);
408 * \brief Get a glyph
409 * \param ch character code
411 FT_Glyph ass_font_get_glyph(void *fontconfig_priv, ASS_Font *font,
412 uint32_t ch, ASS_Hinting hinting, int deco)
414 int error;
415 int index = 0;
416 int i;
417 FT_Glyph glyph;
418 FT_Face face = 0;
419 int flags = 0;
420 int vertical = font->desc.vertical;
422 if (ch < 0x20)
423 return 0;
424 // Handle NBSP like a regular space when rendering the glyph
425 if (ch == 0xa0)
426 ch = ' ';
427 if (font->n_faces == 0)
428 return 0;
430 for (i = 0; i < font->n_faces; ++i) {
431 face = font->faces[i];
432 index = FT_Get_Char_Index(face, ch);
433 if (index)
434 break;
437 #ifdef CONFIG_FONTCONFIG
438 if (index == 0) {
439 int face_idx;
440 ass_msg(font->library, MSGL_INFO,
441 "Glyph 0x%X not found, selecting one more "
442 "font for (%s, %d, %d)", ch, font->desc.family,
443 font->desc.bold, font->desc.italic);
444 face_idx = add_face(fontconfig_priv, font, ch);
445 if (face_idx >= 0) {
446 face = font->faces[face_idx];
447 index = FT_Get_Char_Index(face, ch);
448 if (index == 0 && face->num_charmaps > 0) {
449 ass_msg(font->library, MSGL_WARN,
450 "Glyph 0x%X not found, falling back to first charmap", ch);
451 FT_CharMap cur = face->charmap;
452 FT_Set_Charmap(face, face->charmaps[0]);
453 index = FT_Get_Char_Index(face, ch);
454 FT_Set_Charmap(face, cur);
456 if (index == 0) {
457 ass_msg(font->library, MSGL_ERR,
458 "Glyph 0x%X not found in font for (%s, %d, %d)",
459 ch, font->desc.family, font->desc.bold,
460 font->desc.italic);
464 #endif
466 flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH
467 | FT_LOAD_IGNORE_TRANSFORM;
468 switch (hinting) {
469 case ASS_HINTING_NONE:
470 flags |= FT_LOAD_NO_HINTING;
471 break;
472 case ASS_HINTING_LIGHT:
473 flags |= FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT;
474 break;
475 case ASS_HINTING_NORMAL:
476 flags |= FT_LOAD_FORCE_AUTOHINT;
477 break;
478 case ASS_HINTING_NATIVE:
479 break;
482 error = FT_Load_Glyph(face, index, flags);
483 if (error) {
484 ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
485 index);
486 return 0;
488 if (!(face->style_flags & FT_STYLE_FLAG_ITALIC) &&
489 (font->desc.italic > 55)) {
490 FT_GlyphSlot_Oblique(face->glyph);
493 if (!(face->style_flags & FT_STYLE_FLAG_BOLD) &&
494 (font->desc.bold > 80)) {
495 ass_glyph_embolden(face->glyph);
497 error = FT_Get_Glyph(face->glyph, &glyph);
498 if (error) {
499 ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
500 index);
501 return 0;
504 // Rotate glyph, if needed
505 if (vertical && ch >= VERTICAL_LOWER_BOUND) {
506 FT_Matrix m = { 0, double_to_d16(-1.0), double_to_d16(1.0), 0 };
507 FT_Outline_Transform(&((FT_OutlineGlyph) glyph)->outline, &m);
508 FT_Outline_Translate(&((FT_OutlineGlyph) glyph)->outline,
509 face->glyph->metrics.vertAdvance,
511 glyph->advance.x = face->glyph->linearVertAdvance;
514 // Apply scaling and shift
515 FT_Matrix scale = { double_to_d16(font->scale_x), 0, 0,
516 double_to_d16(font->scale_y) };
517 FT_Outline *outl = &((FT_OutlineGlyph) glyph)->outline;
518 FT_Outline_Transform(outl, &scale);
519 FT_Outline_Translate(outl, font->v.x, font->v.y);
520 glyph->advance.x *= font->scale_x;
522 ass_strike_outline_glyph(face, font, glyph, deco & DECO_UNDERLINE,
523 deco & DECO_STRIKETHROUGH);
525 return glyph;
529 * \brief Get kerning for the pair of glyphs.
531 FT_Vector ass_font_get_kerning(ASS_Font *font, uint32_t c1, uint32_t c2)
533 FT_Vector v = { 0, 0 };
534 int i;
536 if (font->desc.vertical)
537 return v;
539 for (i = 0; i < font->n_faces; ++i) {
540 FT_Face face = font->faces[i];
541 int i1 = FT_Get_Char_Index(face, c1);
542 int i2 = FT_Get_Char_Index(face, c2);
543 if (i1 && i2) {
544 if (FT_HAS_KERNING(face))
545 FT_Get_Kerning(face, i1, i2, FT_KERNING_DEFAULT, &v);
546 return v;
548 if (i1 || i2) // these glyphs are from different font faces, no kerning information
549 return v;
551 return v;
555 * \brief Deallocate ASS_Font
557 void ass_font_free(ASS_Font *font)
559 int i;
560 for (i = 0; i < font->n_faces; ++i)
561 if (font->faces[i])
562 FT_Done_Face(font->faces[i]);
563 free(font->desc.family);
564 free(font);
568 * \brief Calculate the cbox of a series of points
570 static void
571 get_contour_cbox(FT_BBox *box, FT_Vector *points, int start, int end)
573 box->xMin = box->yMin = INT_MAX;
574 box->xMax = box->yMax = INT_MIN;
575 int i;
577 for (i = start; i <= end; i++) {
578 box->xMin = (points[i].x < box->xMin) ? points[i].x : box->xMin;
579 box->xMax = (points[i].x > box->xMax) ? points[i].x : box->xMax;
580 box->yMin = (points[i].y < box->yMin) ? points[i].y : box->yMin;
581 box->yMax = (points[i].y > box->yMax) ? points[i].y : box->yMax;
586 * \brief Determine winding direction of a contour
587 * \return direction; 0 = clockwise
589 static int get_contour_direction(FT_Vector *points, int start, int end)
591 int i;
592 long long sum = 0;
593 int x = points[start].x;
594 int y = points[start].y;
595 for (i = start + 1; i <= end; i++) {
596 sum += x * (points[i].y - y) - y * (points[i].x - x);
597 x = points[i].x;
598 y = points[i].y;
600 sum += x * (points[start].y - y) - y * (points[start].x - x);
601 return sum > 0;
605 * \brief Fix-up stroker result for huge borders by removing inside contours
606 * that would reverse in size
608 void fix_freetype_stroker(FT_OutlineGlyph glyph, int border_x, int border_y)
610 int nc = glyph->outline.n_contours;
611 int begin, stop;
612 char modified = 0;
613 char *valid_cont = malloc(nc);
614 int start = 0;
615 int end = -1;
616 FT_BBox *boxes = malloc(nc * sizeof(FT_BBox));
617 int i, j;
618 int inside_direction;
620 inside_direction = FT_Outline_Get_Orientation(&glyph->outline) ==
621 FT_ORIENTATION_TRUETYPE;
623 // create a list of cboxes of the contours
624 for (i = 0; i < nc; i++) {
625 start = end + 1;
626 end = glyph->outline.contours[i];
627 get_contour_cbox(&boxes[i], glyph->outline.points, start, end);
630 // for each contour, check direction and whether it's "outside"
631 // or contained in another contour
632 end = -1;
633 for (i = 0; i < nc; i++) {
634 start = end + 1;
635 end = glyph->outline.contours[i];
636 int dir = get_contour_direction(glyph->outline.points, start, end);
637 valid_cont[i] = 1;
638 if (dir == inside_direction) {
639 for (j = 0; j < nc; j++) {
640 if (i == j)
641 continue;
642 if (boxes[i].xMin >= boxes[j].xMin &&
643 boxes[i].xMax <= boxes[j].xMax &&
644 boxes[i].yMin >= boxes[j].yMin &&
645 boxes[i].yMax <= boxes[j].yMax)
646 goto check_inside;
648 /* "inside" contour but we can't find anything it could be
649 * inside of - assume the font is buggy and it should be
650 * an "outside" contour, and reverse it */
651 for (j = 0; j < (end + 1 - start) / 2; j++) {
652 FT_Vector temp = glyph->outline.points[start + j];
653 char temp2 = glyph->outline.tags[start + j];
654 glyph->outline.points[start + j] = glyph->outline.points[end - j];
655 glyph->outline.points[end - j] = temp;
656 glyph->outline.tags[start + j] = glyph->outline.tags[end - j];
657 glyph->outline.tags[end - j] = temp2;
659 dir ^= 1;
661 check_inside:
662 if (dir == inside_direction) {
663 FT_BBox box;
664 get_contour_cbox(&box, glyph->outline.points, start, end);
665 int width = box.xMax - box.xMin;
666 int height = box.yMax - box.yMin;
667 if (width < border_x * 2 || height < border_y * 2) {
668 valid_cont[i] = 0;
669 modified = 1;
674 // zero-out contours that can be removed; much simpler than copying
675 if (modified) {
676 for (i = 0; i < nc; i++) {
677 if (valid_cont[i])
678 continue;
679 begin = (i == 0) ? 0 : glyph->outline.contours[i - 1] + 1;
680 stop = glyph->outline.contours[i];
681 for (j = begin; j <= stop; j++) {
682 glyph->outline.points[j].x = 0;
683 glyph->outline.points[j].y = 0;
684 glyph->outline.tags[j] = 0;
689 free(boxes);
690 free(valid_cont);