]> granicus.if.org Git - libass/blob - libass/ass_shaper.c
Cache HarfBuzz fonts
[libass] / libass / ass_shaper.c
1 /*
2  * Copyright (C) 2011 Grigori Goronzy <greg@chown.ath.cx>
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 <fribidi/fribidi.h>
20 #include <hb-ft.h>
21
22 #include "ass_shaper.h"
23 #include "ass_render.h"
24 #include "ass_font.h"
25 #include "ass_parse.h"
26
27 #define MAX_RUNS 50
28
29 enum {
30     VERT = 0,
31     VKNA,
32     KERN
33 };
34 #define NUM_FEATURES 3
35
36 struct ass_shaper {
37     // FriBidi log2vis
38     int n_glyphs;
39     FriBidiChar *event_text;
40     FriBidiCharType *ctypes;
41     FriBidiLevel *emblevels;
42     FriBidiStrIndex *cmap;
43     FriBidiParType base_direction;
44     // OpenType features
45     int n_features;
46     hb_feature_t *features;
47 };
48
49 struct ass_shaper_font_data {
50     hb_font_t *fonts[ASS_FONT_MAX_FACES];
51 };
52
53 /**
54  * \brief Print version information
55  */
56 void ass_shaper_info(ASS_Library *lib)
57 {
58     ass_msg(lib, MSGL_V, "Complex text layout enabled, using FriBidi "
59             FRIBIDI_VERSION " HarfBuzz-ng %s", hb_version_string());
60 }
61
62 /**
63  * \brief grow arrays, if needed
64  * \param new_size requested size
65  */
66 static void check_allocations(ASS_Shaper *shaper, size_t new_size)
67 {
68     if (new_size > shaper->n_glyphs) {
69         shaper->event_text = realloc(shaper->event_text, sizeof(FriBidiChar) * new_size);
70         shaper->ctypes     = realloc(shaper->ctypes, sizeof(FriBidiCharType) * new_size);
71         shaper->emblevels  = realloc(shaper->emblevels, sizeof(FriBidiLevel) * new_size);
72         shaper->cmap       = realloc(shaper->cmap, sizeof(FriBidiStrIndex) * new_size);
73     }
74 }
75
76 /**
77  * \brief set up the HarfBuzz OpenType feature list with some
78  * standard features.
79  */
80 static void init_features(ASS_Shaper *shaper)
81 {
82     shaper->features = calloc(sizeof(hb_feature_t), NUM_FEATURES);
83
84     shaper->n_features = NUM_FEATURES;
85     shaper->features[VERT].tag = HB_TAG('v', 'e', 'r', 't');
86     shaper->features[VERT].end = INT_MAX;
87     shaper->features[VKNA].tag = HB_TAG('v', 'k', 'n', 'a');
88     shaper->features[VKNA].end = INT_MAX;
89     shaper->features[KERN].tag = HB_TAG('k', 'e', 'r', 'n');
90     shaper->features[KERN].end = INT_MAX;
91 }
92
93 /**
94  * \brief Create a new shaper instance and preallocate data structures
95  * \param prealloc preallocation size
96  */
97 ASS_Shaper *ass_shaper_new(size_t prealloc)
98 {
99     ASS_Shaper *shaper = calloc(sizeof(*shaper), 1);
100
101     shaper->base_direction = FRIBIDI_PAR_ON;
102     init_features(shaper);
103     check_allocations(shaper, prealloc);
104
105     return shaper;
106 }
107
108 /**
109  * \brief Free shaper and related data
110  */
111 void ass_shaper_free(ASS_Shaper *shaper)
112 {
113     free(shaper->event_text);
114     free(shaper->ctypes);
115     free(shaper->emblevels);
116     free(shaper->cmap);
117     free(shaper->features);
118     free(shaper);
119 }
120
121 void ass_shaper_font_data_free(ASS_ShaperFontData *priv)
122 {
123     int i;
124     for (i = 0; i < ASS_FONT_MAX_FACES; i++)
125         if (priv->fonts[i])
126             hb_font_destroy(priv->fonts[i]);
127     free(priv);
128 }
129
130 /**
131  * \brief Set features depending on properties of the run
132  */
133 static void set_run_features(ASS_Shaper *shaper, GlyphInfo *info)
134 {
135         // enable vertical substitutions for @font runs
136         if (info->font->desc.vertical)
137             shaper->features[VERT].value = shaper->features[VKNA].value = 1;
138         else
139             shaper->features[VERT].value = shaper->features[VKNA].value = 0;
140 }
141
142 /**
143  * \brief Retrieve HarfBuzz font from cache.
144  * Create it from FreeType font, if needed.
145  * \param info glyph cluster
146  * \return HarfBuzz font
147  */
148 static hb_font_t *get_hb_font(GlyphInfo *info)
149 {
150     ASS_Font *font = info->font;
151     hb_font_t **hb_fonts;
152
153     if (!font->shaper_priv)
154         font->shaper_priv = calloc(sizeof(ASS_ShaperFontData), 1);
155
156     hb_fonts = font->shaper_priv->fonts;
157     if (!hb_fonts[info->face_index])
158         hb_fonts[info->face_index] =
159             hb_ft_font_create(font->faces[info->face_index], NULL);
160
161     return hb_fonts[info->face_index];
162 }
163
164 /**
165  * \brief Shape event text with HarfBuzz. Full OpenType shaping.
166  * \param glyphs glyph clusters
167  * \param len number of clusters
168  */
169 static void shape_harfbuzz(ASS_Shaper *shaper, GlyphInfo *glyphs, size_t len)
170 {
171     int i, j;
172     int run = 0;
173     struct {
174         int offset;
175         int end;
176         hb_buffer_t *buf;
177         hb_font_t *font;
178     } runs[MAX_RUNS];
179
180
181     for (i = 0; i < len && run < MAX_RUNS; i++, run++) {
182         // get length and level of the current run
183         int k = i;
184         int level = glyphs[i].shape_run_id;
185         int direction = shaper->emblevels[k] % 2;
186         while (i < (len - 1) && level == glyphs[i+1].shape_run_id)
187             i++;
188         //printf("run %d from %d to %d with level %d\n", run, k, i, level);
189         runs[run].offset = k;
190         runs[run].end    = i;
191         runs[run].buf    = hb_buffer_create(i - k + 1);
192         runs[run].font   = get_hb_font(glyphs + k);
193         set_run_features(shaper, glyphs + k);
194         hb_buffer_set_direction(runs[run].buf, direction ? HB_DIRECTION_RTL :
195                 HB_DIRECTION_LTR);
196         hb_buffer_add_utf32(runs[run].buf, shaper->event_text + k, i - k + 1,
197                 0, i - k + 1);
198         hb_shape(runs[run].font, runs[run].buf, shaper->features,
199                 shaper->n_features);
200     }
201     //printf("shaped %d runs\n", run);
202
203     // Initialize: skip all glyphs, this is undone later as needed
204     for (i = 0; i < len; i++)
205         glyphs[i].skip = 1;
206
207     // Update glyph indexes, positions and advances from the shaped runs
208     for (i = 0; i < run; i++) {
209         int num_glyphs = hb_buffer_get_length(runs[i].buf);
210         hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(runs[i].buf, NULL);
211         hb_glyph_position_t *pos    = hb_buffer_get_glyph_positions(runs[i].buf, NULL);
212         //printf("run text len %d num_glyphs %d\n", runs[i].end - runs[i].offset + 1,
213         //        num_glyphs);
214         // Update glyphs
215         for (j = 0; j < num_glyphs; j++) {
216             int idx = glyph_info[j].cluster + runs[i].offset;
217             GlyphInfo *info = glyphs + idx;
218             GlyphInfo *root = info;
219 #if 0
220             printf("run %d cluster %d codepoint %d -> '%c'\n", i, idx,
221                     glyph_info[j].codepoint, event_text[idx]);
222             printf("position %d %d advance %d %d\n",
223                     pos[j].x_offset, pos[j].y_offset,
224                     pos[j].x_advance, pos[j].y_advance);
225 #endif
226
227             // if we have more than one glyph per cluster, allocate a new one
228             // and attach to the root glyph
229             if (info->skip == 0) {
230                 //printf("duplicate cluster entry, adding glyph\n");
231                 while (info->next)
232                     info = info->next;
233                 info->next = malloc(sizeof(GlyphInfo));
234                 memcpy(info->next, info, sizeof(GlyphInfo));
235                 info = info->next;
236                 info->next = NULL;
237             }
238
239             // set position and advance
240             info->skip = 0;
241             info->glyph_index = glyph_info[j].codepoint;
242             info->offset.x    = pos[j].x_offset * info->scale_x;
243             info->offset.y    = -pos[j].y_offset * info->scale_y;
244             info->advance.x   = pos[j].x_advance * info->scale_x;
245             info->advance.y   = -pos[j].y_advance * info->scale_y;
246
247             // accumulate advance in the root glyph
248             root->cluster_advance.x += info->advance.x;
249             root->cluster_advance.y += info->advance.y;
250         }
251     }
252
253     // Free runs and associated data
254     for (i = 0; i < run; i++) {
255         hb_buffer_destroy(runs[i].buf);
256     }
257
258 }
259
260 /**
261  * \brief Shape event text with FriBidi. Does mirroring and simple
262  * Arabic shaping.
263  * \param len number of clusters
264  */
265 static void shape_fribidi(ASS_Shaper *shaper, size_t len)
266 {
267     FriBidiJoiningType *joins = calloc(sizeof(*joins), len);
268
269     fribidi_get_joining_types(shaper->event_text, len, joins);
270     fribidi_join_arabic(shaper->ctypes, len, shaper->emblevels, joins);
271     fribidi_shape(FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC,
272             shaper->emblevels, len, joins, shaper->event_text);
273
274     free(joins);
275 }
276
277 /**
278  * \brief Toggle kerning for HarfBuzz shaping.
279  * NOTE: currently only works with OpenType fonts, the TrueType fallback *always*
280  * kerns. It's a bug in HarfBuzz.
281  */
282 void ass_shaper_set_kerning(ASS_Shaper *shaper, int kern)
283 {
284     shaper->features[KERN].value = !!kern;
285 }
286
287 /**
288  * \brief Find shape runs according to the event's selected fonts
289  */
290 void ass_shaper_find_runs(ASS_Shaper *shaper, ASS_Renderer *render_priv,
291                           GlyphInfo *glyphs, size_t len)
292 {
293     int i;
294     int shape_run = 0;
295
296     for (i = 0; i < len; i++) {
297         GlyphInfo *last = glyphs + i - 1;
298         GlyphInfo *info = glyphs + i;
299         // skip drawings
300         if (info->symbol == 0xfffc)
301             continue;
302         // initialize face_index to continue with the same face, if possible
303         // XXX: can be problematic in some cases, for example if a font misses
304         // a single glyph, like space (U+0020)
305         if (i > 0)
306             info->face_index = last->face_index;
307         // set size and get glyph index
308         double size_scaled = ensure_font_size(render_priv,
309                 info->font_size * render_priv->font_scale);
310         ass_font_set_size(info->font, size_scaled);
311         ass_font_get_index(render_priv->fontconfig_priv, info->font,
312                 info->symbol, &info->face_index, &info->glyph_index);
313         // shape runs share the same font face and size
314         if (i > 0 && (last->font != info->font ||
315                     last->font_size != info->font_size ||
316                     last->face_index != info->face_index))
317             shape_run++;
318         info->shape_run_id = shape_run;
319         //printf("glyph '%c' shape run id %d face %d\n", info->symbol, info->shape_run_id,
320         //        info->face_index);
321     }
322
323 }
324
325 /**
326  * \brief Set base direction (paragraph direction) of the text.
327  * \param dir base direction
328  */
329 void ass_shaper_set_base_direction(ASS_Shaper *shaper, FriBidiParType dir)
330 {
331     shaper->base_direction = dir;
332 }
333
334 /**
335  * \brief Shape an event's text. Calculates directional runs and shapes them.
336  * \param text_info event's text
337  */
338 void ass_shaper_shape(ASS_Shaper *shaper, TextInfo *text_info)
339 {
340     int i, last_break;
341     FriBidiParType dir;
342     GlyphInfo *glyphs = text_info->glyphs;
343
344     check_allocations(shaper, text_info->length);
345
346     // Get bidi character types and embedding levels
347     last_break = 0;
348     for (i = 0; i < text_info->length; i++) {
349         shaper->event_text[i] = glyphs[i].symbol;
350         // embedding levels should be calculated paragraph by paragraph
351         if (glyphs[i].symbol == '\n' || i == text_info->length - 1) {
352             //printf("paragraph from %d to %d\n", last_break, i);
353             dir = shaper->base_direction;
354             fribidi_get_bidi_types(shaper->event_text + last_break,
355                     i - last_break + 1, shaper->ctypes + last_break);
356             fribidi_get_par_embedding_levels(shaper->ctypes + last_break,
357                     i - last_break + 1, &dir, shaper->emblevels + last_break);
358             last_break = i + 1;
359         }
360     }
361
362     // add embedding levels to shape runs for final runs
363     for (i = 0; i < text_info->length; i++) {
364         glyphs[i].shape_run_id += shaper->emblevels[i];
365     }
366
367 #if 0
368     printf("levels ");
369     for (i = 0; i < text_info->length; i++) {
370         printf("%d ", glyphs[i].shape_run_id);
371     }
372     printf("\n");
373 #endif
374
375     //shape_fribidi(shaper, text_info->length);
376     shape_harfbuzz(shaper, glyphs, text_info->length);
377
378     // Update glyphs
379     for (i = 0; i < text_info->length; i++) {
380         glyphs[i].symbol = shaper->event_text[i];
381         // Skip direction override control characters
382         // NOTE: Behdad said HarfBuzz is supposed to remove these, but this hasn't
383         // been implemented yet
384         if (glyphs[i].symbol <= 0x202F && glyphs[i].symbol >= 0x202a) {
385             glyphs[i].symbol = 0;
386             glyphs[i].skip++;
387         }
388     }
389 }
390
391 /**
392  * \brief clean up additional data temporarily needed for shaping and
393  * (e.g. additional glyphs allocated)
394  */
395 void ass_shaper_cleanup(ASS_Shaper *shaper, TextInfo *text_info)
396 {
397     int i;
398
399     for (i = 0; i < text_info->length; i++) {
400         GlyphInfo *info = text_info->glyphs + i;
401         info = info->next;
402         while (info) {
403             GlyphInfo *next = info->next;
404             free(info);
405             info = next;
406         }
407     }
408 }
409
410 /**
411  * \brief Calculate reorder map to render glyphs in visual order
412  */
413 FriBidiStrIndex *ass_shaper_reorder(ASS_Shaper *shaper, TextInfo *text_info)
414 {
415     int i;
416
417     // Initialize reorder map
418     for (i = 0; i < text_info->length; i++)
419         shaper->cmap[i] = i;
420
421     // Create reorder map line-by-line
422     for (i = 0; i < text_info->n_lines; i++) {
423         LineInfo *line = text_info->lines + i;
424         int level;
425         FriBidiParType dir = FRIBIDI_PAR_ON;
426
427         // FIXME: we should actually specify
428         // the correct paragraph base direction
429         level = fribidi_reorder_line(FRIBIDI_FLAGS_DEFAULT,
430                 shaper->ctypes + line->offset, line->len, 0, dir,
431                 shaper->emblevels + line->offset, NULL,
432                 shaper->cmap + line->offset);
433         //printf("reorder line %d to level %d\n", i, level);
434     }
435
436 #if 0
437     printf("map ");
438     for (i = 0; i < text_info->length; i++) {
439         printf("%d ", cmap[i]);
440     }
441     printf("\n");
442 #endif
443
444     return shaper->cmap;
445 }
446
447 /**
448  * \brief Resolve a Windows font encoding number to a suitable
449  * base direction. 177 and 178 are Hebrew and Arabic respectively, and
450  * they map to RTL. 1 is autodetection and is mapped to just that.
451  * Everything else is mapped to LTR.
452  * \param enc Windows font encoding
453  */
454 FriBidiParType resolve_base_direction(int enc)
455 {
456     switch (enc) {
457         case 1:
458             return FRIBIDI_PAR_ON;
459         case 177:
460         case 178:
461             return FRIBIDI_PAR_RTL;
462         default:
463             return FRIBIDI_PAR_LTR;
464     }
465 }