]> granicus.if.org Git - libass/blob - libass/ass_font.c
font: extract transformation from ass_font_get_glyph()
[libass] / libass / ass_font.c
1 /*
2  * Copyright (C) 2006 Evgeniy Stepanov <eugeni.stepanov@gmail.com>
3  *
4  * This file is part of libass.
5  *
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.
9  *
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.
17  */
18
19 #include "config.h"
20 #include "ass_compat.h"
21
22 #include <inttypes.h>
23 #include <ft2build.h>
24 #include FT_FREETYPE_H
25 #include FT_SYNTHESIS_H
26 #include FT_GLYPH_H
27 #include FT_TRUETYPE_TABLES_H
28 #include FT_OUTLINE_H
29 #include <limits.h>
30
31 #include "ass.h"
32 #include "ass_library.h"
33 #include "ass_font.h"
34 #include "ass_fontselect.h"
35 #include "ass_utils.h"
36 #include "ass_shaper.h"
37
38 /**
39  * Select a good charmap, prefer Microsoft Unicode charmaps.
40  * Otherwise, let FreeType decide.
41  */
42 void charmap_magic(ASS_Library *library, FT_Face face)
43 {
44     int i;
45     int ms_cmap = -1;
46
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);
56             return;
57         } else if (pid == 3 && ms_cmap < 0)
58             ms_cmap = i;
59     }
60
61     // Try the first Microsoft cmap if no Microsoft Unicode cmap was found
62     if (ms_cmap >= 0) {
63         FT_CharMap cmap = face->charmaps[ms_cmap];
64         FT_Set_Charmap(face, cmap);
65         return;
66     }
67
68     if (!face->charmap) {
69         if (face->num_charmaps == 0) {
70             ass_msg(library, MSGL_WARN, "Font face with no charmaps");
71             return;
72         }
73         ass_msg(library, MSGL_WARN,
74                 "No charmap autodetected, trying the first one");
75         FT_Set_Charmap(face, face->charmaps[0]);
76         return;
77     }
78 }
79
80 /**
81  * Adjust char index if the charmap is weird
82  * (currently just MS Symbol)
83  */
84
85 uint32_t ass_font_index_magic(FT_Face face, uint32_t symbol)
86 {
87     if (!face->charmap)
88         return symbol;
89
90     switch(face->charmap->encoding){
91     case FT_ENCODING_MS_SYMBOL:
92         return 0xF000 | symbol;
93     default:
94         return symbol;
95     }
96 }
97
98 static void buggy_font_workaround(FT_Face face)
99 {
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);
105         if (os2) {
106             face->ascender = os2->sTypoAscender;
107             face->descender = os2->sTypoDescender;
108             face->height = face->ascender - face->descender;
109         } else {
110             face->ascender = face->bbox.yMax;
111             face->descender = face->bbox.yMin;
112             face->height = face->ascender - face->descender;
113         }
114     }
115 }
116
117 static unsigned long
118 read_stream_font(FT_Stream stream, unsigned long offset, unsigned char *buffer,
119                  unsigned long count)
120 {
121     ASS_FontStream *font = (ASS_FontStream *)stream->descriptor.pointer;
122
123     font->func(font->priv, buffer, offset, count);
124     return count;
125 }
126
127 static void
128 close_stream_font(FT_Stream stream)
129 {
130     free(stream->descriptor.pointer);
131     free(stream);
132 }
133
134 /**
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
137  */
138 static int add_face(ASS_FontSelector *fontsel, ASS_Font *font, uint32_t ch)
139 {
140     char *path;
141     char *postscript_name = NULL;
142     int i, index, uid, error;
143     ASS_FontStream stream = { NULL, NULL };
144     FT_Face face;
145
146     if (font->n_faces == ASS_FONT_MAX_FACES)
147         return -1;
148
149     path = ass_font_select(fontsel, font->library, font , &index,
150             &postscript_name, &uid, &stream, ch);
151
152     if (!path)
153         return -1;
154
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.");
159             return i;
160         }
161     }
162
163     if (stream.func) {
164         FT_Open_Args args;
165         FT_Stream ftstream = calloc(1, sizeof(FT_StreamRec));
166         ASS_FontStream *fs  = calloc(1, sizeof(ASS_FontStream));
167
168         *fs = stream;
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;
173
174         memset(&args, 0, sizeof(FT_Open_Args));
175         args.flags  = FT_OPEN_STREAM;
176         args.stream = ftstream;
177
178         error = FT_Open_Face(font->ftlibrary, &args, index, &face);
179
180         if (error) {
181             ass_msg(font->library, MSGL_WARN,
182                     "Error opening memory font: '%s'", path);
183             return -1;
184         }
185
186     } else {
187         error = FT_New_Face(font->ftlibrary, path, index, &face);
188         if (error) {
189             ass_msg(font->library, MSGL_WARN,
190                     "Error opening font: '%s', %d", path, index);
191             return -1;
192         }
193
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++) {
199                 FT_Done_Face(face);
200                 error = FT_New_Face(font->ftlibrary, path, i, &face);
201                 if (error) {
202                     ass_msg(font->library, MSGL_WARN,
203                             "Error opening font: '%s', %d", path, i);
204                     return -1;
205                 }
206
207                 const char *face_psname = FT_Get_Postscript_Name(face);
208                 if (face_psname != NULL &&
209                     strcmp(face_psname, postscript_name) == 0)
210                     break;
211             }
212         }
213     }
214
215     charmap_magic(font->library, face);
216     buggy_font_workaround(face);
217
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;
222 }
223
224 /**
225  * \brief Create a new ASS_Font according to "desc" argument
226  */
227 ASS_Font *ass_font_new(ASS_Renderer *render_priv, ASS_FontDesc *desc)
228 {
229     ASS_Font *font = ass_cache_get(render_priv->cache.font_cache, desc, render_priv);
230     if (!font)
231         return NULL;
232     if (font->desc.family)
233         return font;
234     ass_cache_dec_ref(font);
235     return NULL;
236 }
237
238 size_t ass_font_construct(void *key, void *value, void *priv)
239 {
240     ASS_Renderer *render_priv = priv;
241     ASS_FontDesc *desc = key;
242     ASS_Font *font = value;
243
244     font->library = render_priv->library;
245     font->ftlibrary = render_priv->ftlibrary;
246     font->shaper_priv = NULL;
247     font->n_faces = 0;
248     font->desc.family = desc->family;
249     font->desc.bold = desc->bold;
250     font->desc.italic = desc->italic;
251     font->desc.vertical = desc->vertical;
252
253     font->size = 0.;
254
255     int error = add_face(render_priv->fontselect, font, 0);
256     if (error == -1)
257         font->desc.family = NULL;
258     return 1;
259 }
260
261 void ass_face_set_size(FT_Face face, double size)
262 {
263     TT_HoriHeader *hori = FT_Get_Sfnt_Table(face, ft_sfnt_hhea);
264     TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
265     double mscale = 1.;
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)
270     if (os2) {
271         int ft_height = 0;
272         if (hori)
273             ft_height = hori->Ascender - hori->Descender;
274         if (!ft_height)
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;
280     }
281     memset(&rq, 0, sizeof(rq));
282     rq.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
283     rq.width = 0;
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;
289     m->height /= mscale;
290 }
291
292 /**
293  * \brief Set font size
294  **/
295 void ass_font_set_size(ASS_Font *font, double size)
296 {
297     int i;
298     if (font->size != size) {
299         font->size = size;
300         for (i = 0; i < font->n_faces; ++i)
301             ass_face_set_size(font->faces[i], size);
302     }
303 }
304
305 /**
306  * \brief Get maximal font ascender and descender.
307  **/
308 void ass_font_get_asc_desc(ASS_Font *font, int face_index,
309                            int *asc, int *desc)
310 {
311     FT_Long a, d;
312     FT_Face face = font->faces[face_index];
313     TT_OS2 *os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
314     if (os2) {
315         a = (short) os2->usWinAscent;
316         d = (short) os2->usWinDescent;
317     } else {
318         a =  face->ascender;
319         d = -face->descender;
320     }
321     int y_scale = face->size->metrics.y_scale;
322     *asc  = FT_MulFix(a, y_scale);
323     *desc = FT_MulFix(d, y_scale);
324 }
325
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},
332     };
333
334     if (dir == FT_ORIENTATION_TRUETYPE) {
335         int i;
336         for (i = 0; i < 4; i++) {
337             ol->points[ol->n_points] = points[i];
338             ol->tags[ol->n_points++] = 1;
339         }
340     } else {
341         int i;
342         for (i = 3; i >= 0; i--) {
343             ol->points[ol->n_points] = points[i];
344             ol->tags[ol->n_points++] = 1;
345         }
346     }
347
348     ol->contours[ol->n_contours++] = ol->n_points - 1;
349 }
350
351 /*
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
355  * being accurate.
356  *
357  */
358 static int ass_strike_outline_glyph(FT_Face face, ASS_Font *font,
359                                     FT_Glyph glyph, int under, int through)
360 {
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;
365
366     if (!under && !through)
367         return 0;
368
369     // Grow outline
370     i = (under ? 4 : 0) + (through ? 4 : 0);
371     if (ol->n_points > SHRT_MAX - i)
372         return 0;
373     if (!ASS_REALLOC_ARRAY(ol->points, ol->n_points + i))
374         return 0;
375     if (!ASS_REALLOC_ARRAY(ol->tags, ol->n_points + i))
376         return 0;
377     i = !!under + !!through;
378     if (ol->n_contours > SHRT_MAX - i)
379         return 0;
380     if (!ASS_REALLOC_ARRAY(ol->contours, ol->n_contours + i))
381         return 0;
382
383     advance = d16_to_d6(glyph->advance.x);
384     y_scale = face->size->metrics.y_scale;
385
386     // Reverse drawing direction for non-truetype fonts
387     dir = FT_Outline_Get_Orientation(ol);
388
389     // Add points to the outline
390     if (under && ps) {
391         int pos = FT_MulFix(ps->underlinePosition, y_scale);
392         int size = FT_MulFix(ps->underlineThickness, y_scale / 2);
393
394         if (pos > 0 || size <= 0)
395             return 1;
396
397         add_line(ol, 0, advance, dir, pos, size);
398     }
399
400     if (through && os2) {
401         int pos = FT_MulFix(os2->yStrikeoutPosition, y_scale);
402         int size = FT_MulFix(os2->yStrikeoutSize, y_scale / 2);
403
404         if (pos < 0 || size <= 0)
405             return 1;
406
407         add_line(ol, 0, advance, dir, pos, size);
408     }
409
410     return 0;
411 }
412
413 /**
414  * Slightly embold a glyph without touching its metrics
415  */
416 static void ass_glyph_embolden(FT_GlyphSlot slot)
417 {
418     int str;
419
420     if (slot->format != FT_GLYPH_FORMAT_OUTLINE)
421         return;
422
423     str = FT_MulFix(slot->face->units_per_EM,
424                     slot->face->size->metrics.y_scale) / 64;
425
426     FT_Outline_Embolden(&slot->outline, str);
427 }
428
429 /**
430  * \brief Get glyph and face index
431  * Finds a face that has the requested codepoint and returns both face
432  * and glyph index.
433  */
434 int ass_font_get_index(ASS_FontSelector *fontsel, ASS_Font *font,
435                        uint32_t symbol, int *face_index, int *glyph_index)
436 {
437     int index = 0;
438     int i;
439     FT_Face face = 0;
440
441     *glyph_index = 0;
442
443     if (symbol < 0x20) {
444         *face_index = 0;
445         return 0;
446     }
447     // Handle NBSP like a regular space when rendering the glyph
448     if (symbol == 0xa0)
449         symbol = ' ';
450     if (font->n_faces == 0) {
451         *face_index = 0;
452         return 0;
453     }
454
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));
459     }
460
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));
465         if (index)
466             *face_index = i;
467     }
468
469     if (index == 0) {
470         int face_idx;
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);
476         if (face_idx >= 0) {
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) {
480                 int i;
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;
486                 }
487             }
488             if (index == 0) {
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,
492                         font->desc.italic);
493             }
494         }
495     }
496
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;
500
501     return 1;
502 }
503
504 /**
505  * \brief Get a glyph
506  * \param ch character code
507  **/
508 FT_Glyph ass_font_get_glyph(ASS_Font *font, int face_index, int index,
509                             ASS_Hinting hinting, int deco)
510 {
511     int error;
512     FT_Glyph glyph;
513     FT_Face face = font->faces[face_index];
514     int flags = 0;
515
516     flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH
517             | FT_LOAD_IGNORE_TRANSFORM;
518     switch (hinting) {
519     case ASS_HINTING_NONE:
520         flags |= FT_LOAD_NO_HINTING;
521         break;
522     case ASS_HINTING_LIGHT:
523         flags |= FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT;
524         break;
525     case ASS_HINTING_NORMAL:
526         flags |= FT_LOAD_FORCE_AUTOHINT;
527         break;
528     case ASS_HINTING_NATIVE:
529         break;
530     }
531
532     error = FT_Load_Glyph(face, index, flags);
533     if (error) {
534         ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
535                 index);
536         return 0;
537     }
538     if (!(face->style_flags & FT_STYLE_FLAG_ITALIC) &&
539         (font->desc.italic > 55)) {
540         FT_GlyphSlot_Oblique(face->glyph);
541     }
542
543     if (!(face->style_flags & FT_STYLE_FLAG_BOLD) &&
544         (font->desc.bold > 400)) {
545         ass_glyph_embolden(face->glyph);
546     }
547     error = FT_Get_Glyph(face->glyph, &glyph);
548     if (error) {
549         ass_msg(font->library, MSGL_WARN, "Error loading glyph, index %d",
550                 index);
551         return 0;
552     }
553
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);
558         int desc = 0;
559
560         if (os2)
561             desc = FT_MulFix(os2->sTypoDescender, face->size->metrics.y_scale);
562
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;
568     }
569
570     ass_strike_outline_glyph(face, font, glyph, deco & DECO_UNDERLINE,
571                              deco & DECO_STRIKETHROUGH);
572
573     return glyph;
574 }
575
576 /**
577  * \brief Deallocate ASS_Font internals
578  **/
579 void ass_font_clear(ASS_Font *font)
580 {
581     int i;
582     if (font->shaper_priv)
583         ass_shaper_font_data_free(font->shaper_priv);
584     for (i = 0; i < font->n_faces; ++i) {
585         if (font->faces[i])
586             FT_Done_Face(font->faces[i]);
587     }
588     free(font->desc.family);
589 }