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.
20 #include "ass_compat.h"
24 #include FT_FREETYPE_H
25 #include FT_SYNTHESIS_H
27 #include FT_TRUETYPE_TABLES_H
32 #include "ass_library.h"
34 #include "ass_fontselect.h"
35 #include "ass_utils.h"
36 #include "ass_shaper.h"
39 * Select a good charmap, prefer Microsoft Unicode charmaps.
40 * Otherwise, let FreeType decide.
42 void charmap_magic(ASS_Library *library, FT_Face face)
47 // Search for a Microsoft Unicode cmap
48 for (i = 0; i < face->num_charmaps; ++i) {
49 FT_CharMap cmap = face->charmaps[i];
50 unsigned pid = cmap->platform_id;
51 unsigned eid = cmap->encoding_id;
52 if (pid == 3 /*microsoft */
53 && (eid == 1 /*unicode bmp */
54 || eid == 10 /*full unicode */ )) {
55 FT_Set_Charmap(face, cmap);
57 } else if (pid == 3 && ms_cmap < 0)
61 // Try the first Microsoft cmap if no Microsoft Unicode cmap was found
63 FT_CharMap cmap = face->charmaps[ms_cmap];
64 FT_Set_Charmap(face, cmap);
69 if (face->num_charmaps == 0) {
70 ass_msg(library, MSGL_WARN, "Font face with no charmaps");
73 ass_msg(library, MSGL_WARN,
74 "No charmap autodetected, trying the first one");
75 FT_Set_Charmap(face, face->charmaps[0]);
81 * Adjust char index if the charmap is weird
82 * (currently just MS Symbol)
85 uint32_t ass_font_index_magic(FT_Face face, uint32_t symbol)
90 switch(face->charmap->encoding){
91 case FT_ENCODING_MS_SYMBOL:
92 return 0xF000 | symbol;
98 static void buggy_font_workaround(FT_Face face)
100 // Some fonts have zero Ascender/Descender fields in 'hhea' table.
101 // In this case, get the information from 'os2' table or, as
102 // a last resort, from face.bbox.
103 if (face->ascender + face->descender == 0 || face->height == 0) {
104 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
106 face->ascender = os2->sTypoAscender;
107 face->descender = os2->sTypoDescender;
108 face->height = face->ascender - face->descender;
110 face->ascender = face->bbox.yMax;
111 face->descender = face->bbox.yMin;
112 face->height = face->ascender - face->descender;
118 read_stream_font(FT_Stream stream, unsigned long offset, unsigned char *buffer,
121 ASS_FontStream *font = (ASS_FontStream *)stream->descriptor.pointer;
123 font->func(font->priv, buffer, offset, count);
128 close_stream_font(FT_Stream stream)
130 free(stream->descriptor.pointer);
135 * \brief Select a face with the given charcode and add it to ASS_Font
136 * \return index of the new face in font->faces, -1 if failed
138 static int add_face(ASS_FontSelector *fontsel, ASS_Font *font, uint32_t ch)
141 char *postscript_name = NULL;
142 int i, index, uid, error;
143 ASS_FontStream stream = { NULL, NULL };
146 if (font->n_faces == ASS_FONT_MAX_FACES)
149 path = ass_font_select(fontsel, font->library, font , &index,
150 &postscript_name, &uid, &stream, ch);
155 for (i = 0; i < font->n_faces; i++) {
156 if (font->faces_uid[i] == uid) {
157 ass_msg(font->library, MSGL_INFO,
158 "Got a font face that already is available! Skipping.");
165 FT_Stream ftstream = calloc(1, sizeof(FT_StreamRec));
166 ASS_FontStream *fs = calloc(1, sizeof(ASS_FontStream));
169 ftstream->size = stream.func(stream.priv, NULL, 0, 0);
170 ftstream->read = read_stream_font;
171 ftstream->close = close_stream_font;
172 ftstream->descriptor.pointer = (void *)fs;
174 memset(&args, 0, sizeof(FT_Open_Args));
175 args.flags = FT_OPEN_STREAM;
176 args.stream = ftstream;
178 error = FT_Open_Face(font->ftlibrary, &args, index, &face);
181 ass_msg(font->library, MSGL_WARN,
182 "Error opening memory font: '%s'", path);
187 error = FT_New_Face(font->ftlibrary, path, index, &face);
189 ass_msg(font->library, MSGL_WARN,
190 "Error opening font: '%s', %d", path, index);
194 if (postscript_name && index < 0 && face->num_faces > 0) {
195 // The font provider gave us a post_script name and is not sure
196 // about the face index.. so use the postscript name to find the
197 // correct face_index in the collection!
198 for (int i = 0; i < face->num_faces; i++) {
200 error = FT_New_Face(font->ftlibrary, path, i, &face);
202 ass_msg(font->library, MSGL_WARN,
203 "Error opening font: '%s', %d", path, i);
207 const char *face_psname = FT_Get_Postscript_Name(face);
208 if (face_psname != NULL &&
209 strcmp(face_psname, postscript_name) == 0)
215 charmap_magic(font->library, face);
216 buggy_font_workaround(face);
218 font->faces[font->n_faces] = face;
219 font->faces_uid[font->n_faces++] = uid;
220 ass_face_set_size(face, font->size);
221 return font->n_faces - 1;
225 * \brief Create a new ASS_Font according to "desc" argument
227 ASS_Font *ass_font_new(ASS_Renderer *render_priv, ASS_FontDesc *desc)
229 ASS_Font *font = ass_cache_get(render_priv->cache.font_cache, desc, render_priv);
232 if (font->desc.family)
234 ass_cache_dec_ref(font);
238 size_t ass_font_construct(void *key, void *value, void *priv)
240 ASS_Renderer *render_priv = priv;
241 ASS_FontDesc *desc = key;
242 ASS_Font *font = value;
244 font->library = render_priv->library;
245 font->ftlibrary = render_priv->ftlibrary;
246 font->shaper_priv = NULL;
248 font->desc.family = desc->family;
249 font->desc.bold = desc->bold;
250 font->desc.italic = desc->italic;
251 font->desc.vertical = desc->vertical;
255 int error = add_face(render_priv->fontselect, font, 0);
257 font->desc.family = NULL;
261 void ass_face_set_size(FT_Face face, double size)
263 TT_HoriHeader *hori = FT_Get_Sfnt_Table(face, ft_sfnt_hhea);
264 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
266 FT_Size_RequestRec rq;
267 FT_Size_Metrics *m = &face->size->metrics;
268 // VSFilter uses metrics from TrueType OS/2 table
269 // The idea was borrowed from asa (http://asa.diac24.net)
273 ft_height = hori->Ascender - hori->Descender;
275 ft_height = os2->sTypoAscender - os2->sTypoDescender;
276 /* sometimes used for signed values despite unsigned in spec */
277 int os2_height = (short)os2->usWinAscent + (short)os2->usWinDescent;
278 if (ft_height && os2_height)
279 mscale = (double) ft_height / os2_height;
281 memset(&rq, 0, sizeof(rq));
282 rq.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
284 rq.height = double_to_d6(size * mscale);
285 rq.horiResolution = rq.vertResolution = 0;
286 FT_Request_Size(face, &rq);
287 m->ascender /= mscale;
288 m->descender /= mscale;
293 * \brief Set font size
295 void ass_font_set_size(ASS_Font *font, double size)
298 if (font->size != size) {
300 for (i = 0; i < font->n_faces; ++i)
301 ass_face_set_size(font->faces[i], size);
306 * \brief Get maximal font ascender and descender.
308 void ass_font_get_asc_desc(ASS_Font *font, int face_index,
312 FT_Face face = font->faces[face_index];
313 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
315 a = (short) os2->usWinAscent;
316 d = (short) os2->usWinDescent;
319 d = -face->descender;
321 int y_scale = face->size->metrics.y_scale;
322 *asc = FT_MulFix(a, y_scale);
323 *desc = FT_MulFix(d, y_scale);
326 static void add_line(FT_Outline *ol, int bear, int advance, int dir, int pos, int size) {
327 FT_Vector points[4] = {
328 {.x = bear, .y = pos + size},
329 {.x = advance, .y = pos + size},
330 {.x = advance, .y = pos - size},
331 {.x = bear, .y = pos - size},
334 if (dir == FT_ORIENTATION_TRUETYPE) {
336 for (i = 0; i < 4; i++) {
337 ol->points[ol->n_points] = points[i];
338 ol->tags[ol->n_points++] = 1;
342 for (i = 3; i >= 0; i--) {
343 ol->points[ol->n_points] = points[i];
344 ol->tags[ol->n_points++] = 1;
348 ol->contours[ol->n_contours++] = ol->n_points - 1;
352 * Strike a glyph with a horizontal line; it's possible to underline it
353 * and/or strike through it. For the line's position and size, truetype
354 * tables are consulted. Obviously this relies on the data in the tables
358 static int ass_strike_outline_glyph(FT_Face face, ASS_Font *font,
359 FT_Glyph glyph, int under, int through)
361 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
362 TT_Postscript *ps = FT_Get_Sfnt_Table(face, ft_sfnt_post);
363 FT_Outline *ol = &((FT_OutlineGlyph) glyph)->outline;
364 int advance, y_scale, i, dir;
366 if (!under && !through)
370 i = (under ? 4 : 0) + (through ? 4 : 0);
371 if (ol->n_points > SHRT_MAX - i)
373 if (!ASS_REALLOC_ARRAY(ol->points, ol->n_points + i))
375 if (!ASS_REALLOC_ARRAY(ol->tags, ol->n_points + i))
377 i = !!under + !!through;
378 if (ol->n_contours > SHRT_MAX - i)
380 if (!ASS_REALLOC_ARRAY(ol->contours, ol->n_contours + i))
383 advance = d16_to_d6(glyph->advance.x);
384 y_scale = face->size->metrics.y_scale;
386 // Reverse drawing direction for non-truetype fonts
387 dir = FT_Outline_Get_Orientation(ol);
389 // Add points to the outline
391 int pos = FT_MulFix(ps->underlinePosition, y_scale);
392 int size = FT_MulFix(ps->underlineThickness, y_scale / 2);
394 if (pos > 0 || size <= 0)
397 add_line(ol, 0, advance, dir, pos, size);
400 if (through && os2) {
401 int pos = FT_MulFix(os2->yStrikeoutPosition, y_scale);
402 int size = FT_MulFix(os2->yStrikeoutSize, y_scale / 2);
404 if (pos < 0 || size <= 0)
407 add_line(ol, 0, advance, dir, pos, size);
414 * Slightly embold a glyph without touching its metrics
416 static void ass_glyph_embolden(FT_GlyphSlot slot)
420 if (slot->format != FT_GLYPH_FORMAT_OUTLINE)
423 str = FT_MulFix(slot->face->units_per_EM,
424 slot->face->size->metrics.y_scale) / 64;
426 FT_Outline_Embolden(&slot->outline, str);
430 * \brief Get glyph and face index
431 * Finds a face that has the requested codepoint and returns both face
434 int ass_font_get_index(ASS_FontSelector *fontsel, ASS_Font *font,
435 uint32_t symbol, int *face_index, int *glyph_index)
447 // Handle NBSP like a regular space when rendering the glyph
450 if (font->n_faces == 0) {
455 // try with the requested face
456 if (*face_index < font->n_faces) {
457 face = font->faces[*face_index];
458 index = FT_Get_Char_Index(face, ass_font_index_magic(face, symbol));
461 // not found in requested face, try all others
462 for (i = 0; i < font->n_faces && index == 0; ++i) {
463 face = font->faces[i];
464 index = FT_Get_Char_Index(face, ass_font_index_magic(face, symbol));
471 ass_msg(font->library, MSGL_INFO,
472 "Glyph 0x%X not found, selecting one more "
473 "font for (%s, %d, %d)", symbol, font->desc.family,
474 font->desc.bold, font->desc.italic);
475 face_idx = *face_index = add_face(fontsel, font, symbol);
477 face = font->faces[face_idx];
478 index = FT_Get_Char_Index(face, ass_font_index_magic(face, symbol));
479 if (index == 0 && face->num_charmaps > 0) {
481 ass_msg(font->library, MSGL_WARN,
482 "Glyph 0x%X not found, broken font? Trying all charmaps", symbol);
483 for (i = 0; i < face->num_charmaps; i++) {
484 FT_Set_Charmap(face, face->charmaps[i]);
485 if ((index = FT_Get_Char_Index(face, ass_font_index_magic(face, symbol))) != 0) break;
489 ass_msg(font->library, MSGL_ERR,
490 "Glyph 0x%X not found in font for (%s, %d, %d)",
491 symbol, font->desc.family, font->desc.bold,
497 // FIXME: make sure we have a valid face_index. this is a HACK.
498 *face_index = FFMAX(*face_index, 0);
499 *glyph_index = index;
506 * \param ch character code
508 FT_Glyph ass_font_get_glyph(ASS_Font *font, int face_index, int index,
509 ASS_Hinting hinting, int deco)
513 FT_Face face = font->faces[face_index];
516 flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH
517 | FT_LOAD_IGNORE_TRANSFORM;
519 case ASS_HINTING_NONE:
520 flags |= FT_LOAD_NO_HINTING;
522 case ASS_HINTING_LIGHT:
523 flags |= FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT;
525 case ASS_HINTING_NORMAL:
526 flags |= FT_LOAD_FORCE_AUTOHINT;
528 case ASS_HINTING_NATIVE:
532 error = FT_Load_Glyph(face, index, flags);
534 ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
538 if (!(face->style_flags & FT_STYLE_FLAG_ITALIC) &&
539 (font->desc.italic > 55)) {
540 FT_GlyphSlot_Oblique(face->glyph);
543 if (!(face->style_flags & FT_STYLE_FLAG_BOLD) &&
544 (font->desc.bold > 400)) {
545 ass_glyph_embolden(face->glyph);
547 error = FT_Get_Glyph(face->glyph, &glyph);
549 ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
554 // Rotate glyph, if needed
555 if (deco & DECO_ROTATE) {
556 FT_Matrix m = { 0, double_to_d16(-1.0), double_to_d16(1.0), 0 };
557 TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
561 desc = FT_MulFix(os2->sTypoDescender, face->size->metrics.y_scale);
563 FT_Outline_Translate(&((FT_OutlineGlyph) glyph)->outline, 0, -desc);
564 FT_Outline_Transform(&((FT_OutlineGlyph) glyph)->outline, &m);
565 FT_Outline_Translate(&((FT_OutlineGlyph) glyph)->outline,
566 face->glyph->metrics.vertAdvance, desc);
567 glyph->advance.x = face->glyph->linearVertAdvance;
570 ass_strike_outline_glyph(face, font, glyph, deco & DECO_UNDERLINE,
571 deco & DECO_STRIKETHROUGH);
577 * \brief Deallocate ASS_Font internals
579 void ass_font_clear(ASS_Font *font)
582 if (font->shaper_priv)
583 ass_shaper_font_data_free(font->shaper_priv);
584 for (i = 0; i < font->n_faces; ++i) {
586 FT_Done_Face(font->faces[i]);
588 free(font->desc.family);