-
Notifications
You must be signed in to change notification settings - Fork 33
/
schrift.c
1569 lines (1394 loc) · 42.2 KB
/
schrift.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of libschrift.
*
* © 2019-2022 Thomas Oltmann and contributors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER)
# define restrict __restrict
#endif
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN 1
# include <windows.h>
#else
# define _POSIX_C_SOURCE 1
# include <fcntl.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
#include "schrift.h"
#define SCHRIFT_VERSION "0.10.2"
#define FILE_MAGIC_ONE 0x00010000
#define FILE_MAGIC_TWO 0x74727565
#define HORIZONTAL_KERNING 0x01
#define MINIMUM_KERNING 0x02
#define CROSS_STREAM_KERNING 0x04
#define OVERRIDE_KERNING 0x08
#define POINT_IS_ON_CURVE 0x01
#define X_CHANGE_IS_SMALL 0x02
#define Y_CHANGE_IS_SMALL 0x04
#define REPEAT_FLAG 0x08
#define X_CHANGE_IS_ZERO 0x10
#define X_CHANGE_IS_POSITIVE 0x10
#define Y_CHANGE_IS_ZERO 0x20
#define Y_CHANGE_IS_POSITIVE 0x20
#define OFFSETS_ARE_LARGE 0x001
#define ACTUAL_XY_OFFSETS 0x002
#define GOT_A_SINGLE_SCALE 0x008
#define THERE_ARE_MORE_COMPONENTS 0x020
#define GOT_AN_X_AND_Y_SCALE 0x040
#define GOT_A_SCALE_MATRIX 0x080
/* macros */
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define SIGN(x) (((x) > 0) - ((x) < 0))
/* Allocate values on the stack if they are small enough, else spill to heap. */
#define STACK_ALLOC(var, type, thresh, count) \
type var##_stack_[thresh]; \
var = (count) <= (thresh) ? var##_stack_ : calloc(sizeof(type), count);
#define STACK_FREE(var) \
if (var != var##_stack_) free(var);
enum { SrcMapping, SrcUser };
/* structs */
typedef struct Point Point;
typedef struct Line Line;
typedef struct Curve Curve;
typedef struct Cell Cell;
typedef struct Outline Outline;
typedef struct Raster Raster;
struct Point { double x, y; };
struct Line { uint_least16_t beg, end; };
struct Curve { uint_least16_t beg, end, ctrl; };
struct Cell { double area, cover; };
struct Outline
{
Point *points;
Curve *curves;
Line *lines;
uint_least16_t numPoints;
uint_least16_t capPoints;
uint_least16_t numCurves;
uint_least16_t capCurves;
uint_least16_t numLines;
uint_least16_t capLines;
};
struct Raster
{
Cell *cells;
int width;
int height;
};
struct SFT_Font
{
const uint8_t *memory;
uint_fast32_t size;
#if defined(_WIN32)
HANDLE mapping;
#endif
int source;
uint_least16_t unitsPerEm;
int_least16_t locaFormat;
uint_least16_t numLongHmtx;
};
/* function declarations */
/* generic utility functions */
static void *reallocarray(void *optr, size_t nmemb, size_t size);
static inline int fast_floor(double x);
static inline int fast_ceil (double x);
/* file loading */
static int map_file (SFT_Font *font, const char *filename);
static void unmap_file(SFT_Font *font);
static int init_font (SFT_Font *font);
/* simple mathematical operations */
static Point midpoint(Point a, Point b);
static void transform_points(unsigned int numPts, Point *points, double trf[6]);
static void clip_points(unsigned int numPts, Point *points, int width, int height);
/* 'outline' data structure management */
static int init_outline(Outline *outl);
static void free_outline(Outline *outl);
static int grow_points (Outline *outl);
static int grow_curves (Outline *outl);
static int grow_lines (Outline *outl);
/* TTF parsing utilities */
static inline int is_safe_offset(SFT_Font *font, uint_fast32_t offset, uint_fast32_t margin);
static void *csearch(const void *key, const void *base,
size_t nmemb, size_t size, int (*compar)(const void *, const void *));
static int cmpu16(const void *a, const void *b);
static int cmpu32(const void *a, const void *b);
static inline uint_least8_t getu8 (SFT_Font *font, uint_fast32_t offset);
static inline int_least8_t geti8 (SFT_Font *font, uint_fast32_t offset);
static inline uint_least16_t getu16(SFT_Font *font, uint_fast32_t offset);
static inline int_least16_t geti16(SFT_Font *font, uint_fast32_t offset);
static inline uint_least32_t getu32(SFT_Font *font, uint_fast32_t offset);
static int gettable(SFT_Font *font, char tag[4], uint_fast32_t *offset);
/* codepoint to glyph id translation */
static int cmap_fmt4(SFT_Font *font, uint_fast32_t table, SFT_UChar charCode, uint_fast32_t *glyph);
static int cmap_fmt6(SFT_Font *font, uint_fast32_t table, SFT_UChar charCode, uint_fast32_t *glyph);
static int glyph_id(SFT_Font *font, SFT_UChar charCode, uint_fast32_t *glyph);
/* glyph metrics lookup */
static int hor_metrics(SFT_Font *font, uint_fast32_t glyph, int *advanceWidth, int *leftSideBearing);
static int glyph_bbox(const SFT *sft, uint_fast32_t outline, int box[4]);
/* decoding outlines */
static int outline_offset(SFT_Font *font, uint_fast32_t glyph, uint_fast32_t *offset);
static int simple_flags(SFT_Font *font, uint_fast32_t *offset, uint_fast16_t numPts, uint8_t *flags);
static int simple_points(SFT_Font *font, uint_fast32_t offset, uint_fast16_t numPts, uint8_t *flags, Point *points);
static int decode_contour(uint8_t *flags, uint_fast16_t basePoint, uint_fast16_t count, Outline *outl);
static int simple_outline(SFT_Font *font, uint_fast32_t offset, unsigned int numContours, Outline *outl);
static int compound_outline(SFT_Font *font, uint_fast32_t offset, int recDepth, Outline *outl);
static int decode_outline(SFT_Font *font, uint_fast32_t offset, int recDepth, Outline *outl);
/* tesselation */
static int is_flat(Outline *outl, Curve curve);
static int tesselate_curve(Curve curve, Outline *outl);
static int tesselate_curves(Outline *outl);
/* silhouette rasterization */
static void draw_line(Raster buf, Point origin, Point goal);
static void draw_lines(Outline *outl, Raster buf);
/* post-processing */
static void post_process(Raster buf, uint8_t *image);
/* glyph rendering */
static int render_outline(Outline *outl, double transform[6], SFT_Image image);
/* function implementations */
const char *
sft_version(void)
{
return SCHRIFT_VERSION;
}
/* Loads a font from a user-supplied memory range. */
SFT_Font *
sft_loadmem(const void *mem, size_t size)
{
SFT_Font *font;
if (size > UINT32_MAX) {
return NULL;
}
if (!(font = calloc(1, sizeof *font))) {
return NULL;
}
font->memory = mem;
font->size = (uint_fast32_t) size;
font->source = SrcUser;
if (init_font(font) < 0) {
sft_freefont(font);
return NULL;
}
return font;
}
/* Loads a font from the file system. To do so, it has to map the entire font into memory. */
SFT_Font *
sft_loadfile(char const *filename)
{
SFT_Font *font;
if (!(font = calloc(1, sizeof *font))) {
return NULL;
}
if (map_file(font, filename) < 0) {
free(font);
return NULL;
}
if (init_font(font) < 0) {
sft_freefont(font);
return NULL;
}
return font;
}
void
sft_freefont(SFT_Font *font)
{
if (!font) return;
/* Only unmap if we mapped it ourselves. */
if (font->source == SrcMapping)
unmap_file(font);
free(font);
}
int
sft_lmetrics(const SFT *sft, SFT_LMetrics *metrics)
{
double factor;
uint_fast32_t hhea;
memset(metrics, 0, sizeof *metrics);
if (gettable(sft->font, "hhea", &hhea) < 0)
return -1;
if (!is_safe_offset(sft->font, hhea, 36))
return -1;
factor = sft->yScale / sft->font->unitsPerEm;
metrics->ascender = geti16(sft->font, hhea + 4) * factor;
metrics->descender = geti16(sft->font, hhea + 6) * factor;
metrics->lineGap = geti16(sft->font, hhea + 8) * factor;
return 0;
}
int
sft_lookup(const SFT *sft, SFT_UChar codepoint, SFT_Glyph *glyph)
{
return glyph_id(sft->font, codepoint, glyph);
}
int
sft_gmetrics(const SFT *sft, SFT_Glyph glyph, SFT_GMetrics *metrics)
{
int adv, lsb;
double xScale = sft->xScale / sft->font->unitsPerEm;
uint_fast32_t outline;
int bbox[4];
memset(metrics, 0, sizeof *metrics);
if (hor_metrics(sft->font, glyph, &adv, &lsb) < 0)
return -1;
metrics->advanceWidth = adv * xScale;
metrics->leftSideBearing = lsb * xScale + sft->xOffset;
if (outline_offset(sft->font, glyph, &outline) < 0)
return -1;
if (!outline)
return 0;
if (glyph_bbox(sft, outline, bbox) < 0)
return -1;
metrics->minWidth = bbox[2] - bbox[0] + 1;
metrics->minHeight = bbox[3] - bbox[1] + 1;
metrics->yOffset = sft->flags & SFT_DOWNWARD_Y ? -bbox[3] : bbox[1];
return 0;
}
int
sft_kerning(const SFT *sft, SFT_Glyph leftGlyph, SFT_Glyph rightGlyph,
SFT_Kerning *kerning)
{
void *match;
uint_fast32_t offset;
unsigned int numTables, numPairs, length, format, flags;
int value;
uint8_t key[4];
memset(kerning, 0, sizeof *kerning);
if (gettable(sft->font, "kern", &offset) < 0)
return 0;
/* Read kern table header. */
if (!is_safe_offset(sft->font, offset, 4))
return -1;
if (getu16(sft->font, offset) != 0)
return 0;
numTables = getu16(sft->font, offset + 2);
offset += 4;
while (numTables > 0) {
/* Read subtable header. */
if (!is_safe_offset(sft->font, offset, 6))
return -1;
length = getu16(sft->font, offset + 2);
format = getu8 (sft->font, offset + 4);
flags = getu8 (sft->font, offset + 5);
offset += 6;
if (format == 0 && (flags & HORIZONTAL_KERNING) && !(flags & MINIMUM_KERNING)) {
/* Read format 0 header. */
if (!is_safe_offset(sft->font, offset, 8))
return -1;
numPairs = getu16(sft->font, offset);
offset += 8;
/* Look up character code pair via binary search. */
key[0] = (leftGlyph >> 8) & 0xFF;
key[1] = leftGlyph & 0xFF;
key[2] = (rightGlyph >> 8) & 0xFF;
key[3] = rightGlyph & 0xFF;
if ((match = bsearch(key, sft->font->memory + offset,
numPairs, 6, cmpu32)) != NULL) {
value = geti16(sft->font, (uint_fast32_t) ((uint8_t *) match - sft->font->memory + 4));
if (flags & CROSS_STREAM_KERNING) {
kerning->yShift += value;
} else {
kerning->xShift += value;
}
}
}
offset += length;
--numTables;
}
kerning->xShift = kerning->xShift / sft->font->unitsPerEm * sft->xScale;
kerning->yShift = kerning->yShift / sft->font->unitsPerEm * sft->yScale;
return 0;
}
int
sft_render(const SFT *sft, SFT_Glyph glyph, SFT_Image image)
{
uint_fast32_t outline;
double transform[6];
int bbox[4];
Outline outl;
if (outline_offset(sft->font, glyph, &outline) < 0)
return -1;
if (!outline)
return 0;
if (glyph_bbox(sft, outline, bbox) < 0)
return -1;
/* Set up the transformation matrix such that
* the transformed bounding boxes min corner lines
* up with the (0, 0) point. */
transform[0] = sft->xScale / sft->font->unitsPerEm;
transform[1] = 0.0;
transform[2] = 0.0;
transform[4] = sft->xOffset - bbox[0];
if (sft->flags & SFT_DOWNWARD_Y) {
transform[3] = -sft->yScale / sft->font->unitsPerEm;
transform[5] = bbox[3] - sft->yOffset;
} else {
transform[3] = +sft->yScale / sft->font->unitsPerEm;
transform[5] = sft->yOffset - bbox[1];
}
memset(&outl, 0, sizeof outl);
if (init_outline(&outl) < 0)
goto failure;
if (decode_outline(sft->font, outline, 0, &outl) < 0)
goto failure;
if (render_outline(&outl, transform, image) < 0)
goto failure;
free_outline(&outl);
return 0;
failure:
free_outline(&outl);
return -1;
}
/* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW */
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
/* OpenBSD's reallocarray() standard libary function.
* A wrapper for realloc() that takes two size args like calloc().
* Useful because it eliminates common integer overflow bugs. */
static void *
reallocarray(void *optr, size_t nmemb, size_t size)
{
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
nmemb > 0 && SIZE_MAX / nmemb < size) {
errno = ENOMEM;
return NULL;
}
return realloc(optr, size * nmemb);
}
/* TODO maybe we should use long here instead of int. */
static inline int
fast_floor(double x)
{
int i = (int) x;
return i - (i > x);
}
static inline int
fast_ceil(double x)
{
int i = (int) x;
return i + (i < x);
}
#if defined(_WIN32)
static int
map_file(SFT_Font *font, const char *filename)
{
HANDLE file;
DWORD high, low;
font->mapping = NULL;
font->memory = NULL;
file = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (file == INVALID_HANDLE_VALUE) {
return -1;
}
low = GetFileSize(file, &high);
if (low == INVALID_FILE_SIZE) {
CloseHandle(file);
return -1;
}
font->size = (size_t)high << (8 * sizeof(DWORD)) | low;
font->mapping = CreateFileMapping(file, NULL, PAGE_READONLY, high, low, NULL);
if (!font->mapping) {
CloseHandle(file);
return -1;
}
CloseHandle(file);
font->memory = MapViewOfFile(font->mapping, FILE_MAP_READ, 0, 0, 0);
if (!font->memory) {
CloseHandle(font->mapping);
font->mapping = NULL;
return -1;
}
return 0;
}
static void
unmap_file(SFT_Font *font)
{
if (font->memory) {
UnmapViewOfFile(font->memory);
font->memory = NULL;
}
if (font->mapping) {
CloseHandle(font->mapping);
font->mapping = NULL;
}
}
#else
static int
map_file(SFT_Font *font, const char *filename)
{
struct stat info;
int fd;
font->memory = MAP_FAILED;
font->size = 0;
font->source = SrcMapping;
if ((fd = open(filename, O_RDONLY)) < 0) {
return -1;
}
if (fstat(fd, &info) < 0) {
close(fd);
return -1;
}
/* FIXME do some basic validation on info.st_size maybe - it is signed for example, so it *could* be negative .. */
font->memory = mmap(NULL, (size_t) info.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
font->size = (uint_fast32_t) info.st_size;
close(fd);
return font->memory == MAP_FAILED ? -1 : 0;
}
static void
unmap_file(SFT_Font *font)
{
assert(font->memory != MAP_FAILED);
munmap((void *) font->memory, font->size);
}
#endif
static int
init_font(SFT_Font *font)
{
uint_fast32_t scalerType, head, hhea;
if (!is_safe_offset(font, 0, 12))
return -1;
/* Check for a compatible scalerType (magic number). */
scalerType = getu32(font, 0);
if (scalerType != FILE_MAGIC_ONE && scalerType != FILE_MAGIC_TWO)
return -1;
if (gettable(font, "head", &head) < 0)
return -1;
if (!is_safe_offset(font, head, 54))
return -1;
font->unitsPerEm = getu16(font, head + 18);
font->locaFormat = geti16(font, head + 50);
if (gettable(font, "hhea", &hhea) < 0)
return -1;
if (!is_safe_offset(font, hhea, 36))
return -1;
font->numLongHmtx = getu16(font, hhea + 34);
return 0;
}
static Point
midpoint(Point a, Point b)
{
return (Point) {
0.5 * (a.x + b.x),
0.5 * (a.y + b.y)
};
}
/* Applies an affine linear transformation matrix to a set of points. */
static void
transform_points(unsigned int numPts, Point *points, double trf[6])
{
Point pt;
unsigned int i;
for (i = 0; i < numPts; ++i) {
pt = points[i];
points[i] = (Point) {
pt.x * trf[0] + pt.y * trf[2] + trf[4],
pt.x * trf[1] + pt.y * trf[3] + trf[5]
};
}
}
static void
clip_points(unsigned int numPts, Point *points, int width, int height)
{
Point pt;
unsigned int i;
for (i = 0; i < numPts; ++i) {
pt = points[i];
if (pt.x < 0.0) {
points[i].x = 0.0;
}
if (pt.x >= width) {
points[i].x = nextafter(width, 0.0);
}
if (pt.y < 0.0) {
points[i].y = 0.0;
}
if (pt.y >= height) {
points[i].y = nextafter(height, 0.0);
}
}
}
static int
init_outline(Outline *outl)
{
/* TODO Smaller initial allocations */
outl->numPoints = 0;
outl->capPoints = 64;
if (!(outl->points = malloc(outl->capPoints * sizeof *outl->points)))
return -1;
outl->numCurves = 0;
outl->capCurves = 64;
if (!(outl->curves = malloc(outl->capCurves * sizeof *outl->curves)))
return -1;
outl->numLines = 0;
outl->capLines = 64;
if (!(outl->lines = malloc(outl->capLines * sizeof *outl->lines)))
return -1;
return 0;
}
static void
free_outline(Outline *outl)
{
free(outl->points);
free(outl->curves);
free(outl->lines);
}
static int
grow_points(Outline *outl)
{
void *mem;
uint_fast16_t cap;
assert(outl->capPoints);
/* Since we use uint_fast16_t for capacities, we have to be extra careful not to trigger integer overflow. */
if (outl->capPoints > UINT16_MAX / 2)
return -1;
cap = (uint_fast16_t) (2U * outl->capPoints);
if (!(mem = reallocarray(outl->points, cap, sizeof *outl->points)))
return -1;
outl->capPoints = (uint_least16_t) cap;
outl->points = mem;
return 0;
}
static int
grow_curves(Outline *outl)
{
void *mem;
uint_fast16_t cap;
assert(outl->capCurves);
if (outl->capCurves > UINT16_MAX / 2)
return -1;
cap = (uint_fast16_t) (2U * outl->capCurves);
if (!(mem = reallocarray(outl->curves, cap, sizeof *outl->curves)))
return -1;
outl->capCurves = (uint_least16_t) cap;
outl->curves = mem;
return 0;
}
static int
grow_lines(Outline *outl)
{
void *mem;
uint_fast16_t cap;
assert(outl->capLines);
if (outl->capLines > UINT16_MAX / 2)
return -1;
cap = (uint_fast16_t) (2U * outl->capLines);
if (!(mem = reallocarray(outl->lines, cap, sizeof *outl->lines)))
return -1;
outl->capLines = (uint_least16_t) cap;
outl->lines = mem;
return 0;
}
static inline int
is_safe_offset(SFT_Font *font, uint_fast32_t offset, uint_fast32_t margin)
{
if (offset > font->size) return 0;
if (font->size - offset < margin) return 0;
return 1;
}
/* Like bsearch(), but returns the next highest element if key could not be found. */
static void *
csearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
const uint8_t *bytes = base, *sample;
size_t low = 0, high = nmemb - 1, mid;
if (!nmemb) return NULL;
while (low != high) {
mid = low + (high - low) / 2;
sample = bytes + mid * size;
if (compar(key, sample) > 0) {
low = mid + 1;
} else {
high = mid;
}
}
return (uint8_t *) bytes + low * size;
}
/* Used as a comparison function for [bc]search(). */
static int
cmpu16(const void *a, const void *b)
{
return memcmp(a, b, 2);
}
/* Used as a comparison function for [bc]search(). */
static int
cmpu32(const void *a, const void *b)
{
return memcmp(a, b, 4);
}
static inline uint_least8_t
getu8(SFT_Font *font, uint_fast32_t offset)
{
assert(offset + 1 <= font->size);
return *(font->memory + offset);
}
static inline int_least8_t
geti8(SFT_Font *font, uint_fast32_t offset)
{
return (int_least8_t) getu8(font, offset);
}
static inline uint_least16_t
getu16(SFT_Font *font, uint_fast32_t offset)
{
assert(offset + 2 <= font->size);
const uint8_t *base = font->memory + offset;
uint_least16_t b1 = base[0], b0 = base[1];
return (uint_least16_t) (b1 << 8 | b0);
}
static inline int16_t
geti16(SFT_Font *font, uint_fast32_t offset)
{
return (int_least16_t) getu16(font, offset);
}
static inline uint32_t
getu32(SFT_Font *font, uint_fast32_t offset)
{
assert(offset + 4 <= font->size);
const uint8_t *base = font->memory + offset;
uint_least32_t b3 = base[0], b2 = base[1], b1 = base[2], b0 = base[3];
return (uint_least32_t) (b3 << 24 | b2 << 16 | b1 << 8 | b0);
}
static int
gettable(SFT_Font *font, char tag[4], uint_fast32_t *offset)
{
void *match;
unsigned int numTables;
/* No need to bounds-check access to the first 12 bytes - this gets already checked by init_font(). */
numTables = getu16(font, 4);
if (!is_safe_offset(font, 12, (uint_fast32_t) numTables * 16))
return -1;
if (!(match = bsearch(tag, font->memory + 12, numTables, 16, cmpu32)))
return -1;
*offset = getu32(font, (uint_fast32_t) ((uint8_t *) match - font->memory + 8));
return 0;
}
static int
cmap_fmt4(SFT_Font *font, uint_fast32_t table, SFT_UChar charCode, SFT_Glyph *glyph)
{
const uint8_t *segPtr;
uint_fast32_t segIdxX2;
uint_fast32_t endCodes, startCodes, idDeltas, idRangeOffsets, idOffset;
uint_fast16_t segCountX2, idRangeOffset, startCode, shortCode, idDelta, id;
uint8_t key[2] = { (uint8_t) (charCode >> 8), (uint8_t) charCode };
/* cmap format 4 only supports the Unicode BMP. */
if (charCode > 0xFFFF) {
*glyph = 0;
return 0;
}
shortCode = (uint_fast16_t) charCode;
if (!is_safe_offset(font, table, 8))
return -1;
segCountX2 = getu16(font, table);
if ((segCountX2 & 1) || !segCountX2)
return -1;
/* Find starting positions of the relevant arrays. */
endCodes = table + 8;
startCodes = endCodes + segCountX2 + 2;
idDeltas = startCodes + segCountX2;
idRangeOffsets = idDeltas + segCountX2;
if (!is_safe_offset(font, idRangeOffsets, segCountX2))
return -1;
/* Find the segment that contains shortCode by binary searching over
* the highest codes in the segments. */
segPtr = csearch(key, font->memory + endCodes, segCountX2 / 2, 2, cmpu16);
segIdxX2 = (uint_fast32_t) (segPtr - (font->memory + endCodes));
/* Look up segment info from the arrays & short circuit if the spec requires. */
if ((startCode = getu16(font, startCodes + segIdxX2)) > shortCode)
return 0;
idDelta = getu16(font, idDeltas + segIdxX2);
if (!(idRangeOffset = getu16(font, idRangeOffsets + segIdxX2))) {
/* Intentional integer under- and overflow. */
*glyph = (shortCode + idDelta) & 0xFFFF;
return 0;
}
/* Calculate offset into glyph array and determine ultimate value. */
idOffset = idRangeOffsets + segIdxX2 + idRangeOffset + 2U * (unsigned int) (shortCode - startCode);
if (!is_safe_offset(font, idOffset, 2))
return -1;
id = getu16(font, idOffset);
/* Intentional integer under- and overflow. */
*glyph = id ? (id + idDelta) & 0xFFFF : 0;
return 0;
}
static int
cmap_fmt6(SFT_Font *font, uint_fast32_t table, SFT_UChar charCode, SFT_Glyph *glyph)
{
unsigned int firstCode, entryCount;
/* cmap format 6 only supports the Unicode BMP. */
if (charCode > 0xFFFF) {
*glyph = 0;
return 0;
}
if (!is_safe_offset(font, table, 4))
return -1;
firstCode = getu16(font, table);
entryCount = getu16(font, table + 2);
if (!is_safe_offset(font, table, 4 + 2 * entryCount))
return -1;
if (charCode < firstCode)
return -1;
charCode -= firstCode;
if (!(charCode < entryCount))
return -1;
*glyph = getu16(font, table + 4 + 2 * charCode);
return 0;
}
static int
cmap_fmt12_13(SFT_Font *font, uint_fast32_t table, SFT_UChar charCode, SFT_Glyph *glyph, int which)
{
uint32_t len, numEntries;
uint_fast32_t i;
*glyph = 0;
/* check that the entire header is present */
if (!is_safe_offset(font, table, 16))
return -1;
len = getu32(font, table + 4);
/* A minimal header is 16 bytes */
if (len < 16)
return -1;
if (!is_safe_offset(font, table, len))
return -1;
numEntries = getu32(font, table + 12);
for (i = 0; i < numEntries; ++i) {
uint32_t firstCode, lastCode, glyphOffset;
firstCode = getu32(font, table + (i * 12) + 16);
lastCode = getu32(font, table + (i * 12) + 16 + 4);
if (charCode < firstCode || charCode > lastCode)
continue;
glyphOffset = getu32(font, table + (i * 12) + 16 + 8);
if (which == 12)
*glyph = (charCode-firstCode) + glyphOffset;
else
*glyph = glyphOffset;
return 0;
}
return 0;
}
/* Maps Unicode code points to glyph indices. */
static int
glyph_id(SFT_Font *font, SFT_UChar charCode, SFT_Glyph *glyph)
{
uint_fast32_t cmap, entry, table;
unsigned int idx, numEntries;
int type, format;
*glyph = 0;
if (gettable(font, "cmap", &cmap) < 0)
return -1;
if (!is_safe_offset(font, cmap, 4))
return -1;
numEntries = getu16(font, cmap + 2);
if (!is_safe_offset(font, cmap, 4 + numEntries * 8))
return -1;
/* First look for a 'full repertoire'/non-BMP map. */
for (idx = 0; idx < numEntries; ++idx) {
entry = cmap + 4 + idx * 8;
type = getu16(font, entry) * 0100 + getu16(font, entry + 2);
/* Complete unicode map */
if (type == 0004 || type == 0312) {
table = cmap + getu32(font, entry + 4);
if (!is_safe_offset(font, table, 8))
return -1;
/* Dispatch based on cmap format. */
format = getu16(font, table);
switch (format) {
case 12:
return cmap_fmt12_13(font, table, charCode, glyph, 12);
default:
return -1;
}
}
}
/* If no 'full repertoire' cmap was found, try looking for a BMP map. */
for (idx = 0; idx < numEntries; ++idx) {
entry = cmap + 4 + idx * 8;
type = getu16(font, entry) * 0100 + getu16(font, entry + 2);
/* Unicode BMP */
if (type == 0003 || type == 0301) {
table = cmap + getu32(font, entry + 4);
if (!is_safe_offset(font, table, 6))
return -1;
/* Dispatch based on cmap format. */
switch (getu16(font, table)) {
case 4:
return cmap_fmt4(font, table + 6, charCode, glyph);
case 6:
return cmap_fmt6(font, table + 6, charCode, glyph);
default:
return -1;
}
}
}
return -1;
}
static int
hor_metrics(SFT_Font *font, SFT_Glyph glyph, int *advanceWidth, int *leftSideBearing)
{
uint_fast32_t hmtx, offset, boundary;
if (gettable(font, "hmtx", &hmtx) < 0)
return -1;
if (glyph < font->numLongHmtx) {
/* glyph is inside long metrics segment. */
offset = hmtx + 4 * glyph;
if (!is_safe_offset(font, offset, 4))
return -1;
*advanceWidth = getu16(font, offset);
*leftSideBearing = geti16(font, offset + 2);
return 0;
} else {
/* glyph is inside short metrics segment. */
boundary = hmtx + 4U * (uint_fast32_t) font->numLongHmtx;
if (boundary < 4)
return -1;
offset = boundary - 4;
if (!is_safe_offset(font, offset, 4))
return -1;
*advanceWidth = getu16(font, offset);
offset = boundary + 2 * (glyph - font->numLongHmtx);
if (!is_safe_offset(font, offset, 2))
return -1;
*leftSideBearing = geti16(font, offset);
return 0;
}
}
static int
glyph_bbox(const SFT *sft, uint_fast32_t outline, int box[4])
{
double xScale, yScale;
/* Read the bounding box from the font file verbatim. */
if (!is_safe_offset(sft->font, outline, 10))
return -1;
box[0] = geti16(sft->font, outline + 2);
box[1] = geti16(sft->font, outline + 4);
box[2] = geti16(sft->font, outline + 6);
box[3] = geti16(sft->font, outline + 8);
if (box[2] <= box[0] || box[3] <= box[1])
return -1;
/* Transform the bounding box into SFT coordinate space. */
xScale = sft->xScale / sft->font->unitsPerEm;
yScale = sft->yScale / sft->font->unitsPerEm;
box[0] = (int) floor(box[0] * xScale + sft->xOffset);
box[1] = (int) floor(box[1] * yScale + sft->yOffset);