xref: /aosp_15_r20/external/harfbuzz_ng/src/OT/Color/CBDT/CBDT.hh (revision 2d1272b857b1f7575e6e246373e1cb218663db8a)
1 /*
2  * Copyright © 2016  Google, Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Seigo Nonaka, Calder Kitagawa
25  */
26 
27 #ifndef OT_COLOR_CBDT_CBDT_HH
28 #define OT_COLOR_CBDT_CBDT_HH
29 
30 #include "../../../hb-open-type.hh"
31 #include "../../../hb-paint.hh"
32 
33 /*
34  * CBLC -- Color Bitmap Location
35  * https://docs.microsoft.com/en-us/typography/opentype/spec/cblc
36  * https://docs.microsoft.com/en-us/typography/opentype/spec/eblc
37  * CBDT -- Color Bitmap Data
38  * https://docs.microsoft.com/en-us/typography/opentype/spec/cbdt
39  * https://docs.microsoft.com/en-us/typography/opentype/spec/ebdt
40  */
41 #define HB_OT_TAG_CBLC HB_TAG('C','B','L','C')
42 #define HB_OT_TAG_CBDT HB_TAG('C','B','D','T')
43 
44 
45 namespace OT {
46 
47 struct cblc_bitmap_size_subset_context_t
48 {
49   const char *cbdt;
50   unsigned int cbdt_length;
51   hb_vector_t<char> *cbdt_prime;
52   unsigned int size;		/* INOUT
53 				 *  Input: old size of IndexSubtable
54 				 *  Output: new size of IndexSubtable
55 				 */
56   unsigned int num_tables;	/* INOUT
57 				 *  Input: old number of subtables.
58 				 *  Output: new number of subtables.
59 				 */
60   hb_codepoint_t start_glyph;	/* OUT */
61   hb_codepoint_t end_glyph;	/* OUT */
62 };
63 
64 static inline bool
_copy_data_to_cbdt(hb_vector_t<char> * cbdt_prime,const void * data,unsigned length)65 _copy_data_to_cbdt (hb_vector_t<char> *cbdt_prime,
66 		    const void        *data,
67 		    unsigned           length)
68 {
69   unsigned int new_len = cbdt_prime->length + length;
70   if (unlikely (!cbdt_prime->alloc (new_len))) return false;
71   hb_memcpy (cbdt_prime->arrayZ + cbdt_prime->length, data, length);
72   cbdt_prime->length = new_len;
73   return true;
74 }
75 
76 struct SmallGlyphMetrics
77 {
sanitizeOT::SmallGlyphMetrics78   bool sanitize (hb_sanitize_context_t *c) const
79   {
80     TRACE_SANITIZE (this);
81     return_trace (c->check_struct (this));
82   }
83 
get_extentsOT::SmallGlyphMetrics84   void get_extents (hb_font_t *font, hb_glyph_extents_t *extents, bool scale) const
85   {
86     extents->x_bearing = bearingX;
87     extents->y_bearing = bearingY;
88     extents->width = width;
89     extents->height = -static_cast<int> (height);
90 
91     if (scale)
92       font->scale_glyph_extents (extents);
93   }
94 
95   HBUINT8	height;
96   HBUINT8	width;
97   HBINT8	bearingX;
98   HBINT8	bearingY;
99   HBUINT8	advance;
100   public:
101   DEFINE_SIZE_STATIC (5);
102 };
103 
104 struct BigGlyphMetrics : SmallGlyphMetrics
105 {
106   HBINT8	vertBearingX;
107   HBINT8	vertBearingY;
108   HBUINT8	vertAdvance;
109   public:
110   DEFINE_SIZE_STATIC (8);
111 };
112 
113 struct SBitLineMetrics
114 {
sanitizeOT::SBitLineMetrics115   bool sanitize (hb_sanitize_context_t *c) const
116   {
117     TRACE_SANITIZE (this);
118     return_trace (c->check_struct (this));
119   }
120 
121   HBINT8	ascender;
122   HBINT8	decender;
123   HBUINT8	widthMax;
124   HBINT8	caretSlopeNumerator;
125   HBINT8	caretSlopeDenominator;
126   HBINT8	caretOffset;
127   HBINT8	minOriginSB;
128   HBINT8	minAdvanceSB;
129   HBINT8	maxBeforeBL;
130   HBINT8	minAfterBL;
131   HBINT8	padding1;
132   HBINT8	padding2;
133   public:
134   DEFINE_SIZE_STATIC (12);
135 };
136 
137 
138 /*
139  * Index Subtables.
140  */
141 
142 struct IndexSubtableHeader
143 {
sanitizeOT::IndexSubtableHeader144   bool sanitize (hb_sanitize_context_t *c) const
145   {
146     TRACE_SANITIZE (this);
147     return_trace (c->check_struct (this));
148   }
149 
150   HBUINT16	indexFormat;
151   HBUINT16	imageFormat;
152   HBUINT32	imageDataOffset;
153   public:
154   DEFINE_SIZE_STATIC (8);
155 };
156 
157 template <typename OffsetType>
158 struct IndexSubtableFormat1Or3
159 {
sanitizeOT::IndexSubtableFormat1Or3160   bool sanitize (hb_sanitize_context_t *c, unsigned int glyph_count) const
161   {
162     TRACE_SANITIZE (this);
163     return_trace (c->check_struct (this) &&
164 		  offsetArrayZ.sanitize (c, glyph_count + 1));
165   }
166 
get_image_dataOT::IndexSubtableFormat1Or3167   bool get_image_data (unsigned int idx,
168 		       unsigned int *offset,
169 		       unsigned int *length) const
170   {
171     if (unlikely (offsetArrayZ[idx + 1] <= offsetArrayZ[idx]))
172       return false;
173 
174     *offset = header.imageDataOffset + offsetArrayZ[idx];
175     *length = offsetArrayZ[idx + 1] - offsetArrayZ[idx];
176     return true;
177   }
178 
add_offsetOT::IndexSubtableFormat1Or3179   bool add_offset (hb_serialize_context_t *c,
180 		   unsigned int offset,
181 		   unsigned int *size /* OUT (accumulated) */)
182   {
183     TRACE_SERIALIZE (this);
184     Offset<OffsetType> embedded_offset;
185     embedded_offset = offset;
186     *size += sizeof (OffsetType);
187     auto *o = c->embed (embedded_offset);
188     return_trace ((bool) o);
189   }
190 
191   IndexSubtableHeader	header;
192   UnsizedArrayOf<Offset<OffsetType>>
193 			offsetArrayZ;
194   public:
195   DEFINE_SIZE_ARRAY (8, offsetArrayZ);
196 };
197 
198 struct IndexSubtableFormat1 : IndexSubtableFormat1Or3<HBUINT32> {};
199 struct IndexSubtableFormat3 : IndexSubtableFormat1Or3<HBUINT16> {};
200 
201 struct IndexSubtable
202 {
sanitizeOT::IndexSubtable203   bool sanitize (hb_sanitize_context_t *c, unsigned int glyph_count) const
204   {
205     TRACE_SANITIZE (this);
206     if (!u.header.sanitize (c)) return_trace (false);
207     hb_barrier ();
208     switch (u.header.indexFormat)
209     {
210     case 1: return_trace (u.format1.sanitize (c, glyph_count));
211     case 3: return_trace (u.format3.sanitize (c, glyph_count));
212     default:return_trace (true);
213     }
214   }
215 
216   bool
finish_subtableOT::IndexSubtable217   finish_subtable (hb_serialize_context_t *c,
218 		   unsigned int cbdt_prime_len,
219 		   unsigned int num_glyphs,
220 		   unsigned int *size /* OUT (accumulated) */)
221   {
222     TRACE_SERIALIZE (this);
223 
224     unsigned int local_offset = cbdt_prime_len - u.header.imageDataOffset;
225     switch (u.header.indexFormat)
226     {
227     case 1: return_trace (u.format1.add_offset (c, local_offset, size));
228     case 3: {
229       if (!u.format3.add_offset (c, local_offset, size))
230 	return_trace (false);
231       if (!(num_glyphs & 0x01))  // Pad to 32-bit alignment if needed.
232 	return_trace (u.format3.add_offset (c, 0, size));
233       return_trace (true);
234     }
235     // TODO: implement 2, 4, 5.
236     case 2: case 4:  // No-op.
237     case 5:  // Pad to 32-bit aligned.
238     default: return_trace (false);
239     }
240   }
241 
242   bool
fill_missing_glyphsOT::IndexSubtable243   fill_missing_glyphs (hb_serialize_context_t *c,
244 		       unsigned int cbdt_prime_len,
245 		       unsigned int num_missing,
246 		       unsigned int *size /* OUT (accumulated) */,
247 		       unsigned int *num_glyphs /* OUT (accumulated) */)
248   {
249     TRACE_SERIALIZE (this);
250 
251     unsigned int local_offset = cbdt_prime_len - u.header.imageDataOffset;
252     switch (u.header.indexFormat)
253     {
254     case 1: {
255       for (unsigned int i = 0; i < num_missing; i++)
256       {
257 	if (unlikely (!u.format1.add_offset (c, local_offset, size)))
258 	  return_trace (false);
259 	*num_glyphs += 1;
260       }
261       return_trace (true);
262     }
263     case 3: {
264       for (unsigned int i = 0; i < num_missing; i++)
265       {
266 	if (unlikely (!u.format3.add_offset (c, local_offset, size)))
267 	  return_trace (false);
268 	*num_glyphs += 1;
269       }
270       return_trace (true);
271     }
272     // TODO: implement 2, 4, 5.
273     case 2:  // Add empty space in cbdt_prime?.
274     case 4: case 5:  // No-op as sparse is supported.
275     default: return_trace (false);
276     }
277   }
278 
279   bool
copy_glyph_at_idxOT::IndexSubtable280   copy_glyph_at_idx (hb_serialize_context_t *c, unsigned int idx,
281 		     const char *cbdt, unsigned int cbdt_length,
282 		     hb_vector_t<char> *cbdt_prime /* INOUT */,
283 		     IndexSubtable *subtable_prime /* INOUT */,
284 		     unsigned int *size /* OUT (accumulated) */) const
285   {
286     TRACE_SERIALIZE (this);
287 
288     unsigned int offset, length, format;
289     if (unlikely (!get_image_data (idx, &offset, &length, &format))) return_trace (false);
290     if (unlikely (offset > cbdt_length || cbdt_length - offset < length)) return_trace (false);
291 
292     auto *header_prime = subtable_prime->get_header ();
293     unsigned int new_local_offset = cbdt_prime->length - (unsigned int) header_prime->imageDataOffset;
294     if (unlikely (!_copy_data_to_cbdt (cbdt_prime, cbdt + offset, length))) return_trace (false);
295 
296     return_trace (subtable_prime->add_offset (c, new_local_offset, size));
297   }
298 
299   bool
add_offsetOT::IndexSubtable300   add_offset (hb_serialize_context_t *c, unsigned int local_offset,
301 	      unsigned int *size /* OUT (accumulated) */)
302   {
303     TRACE_SERIALIZE (this);
304     switch (u.header.indexFormat)
305     {
306     case 1: return_trace (u.format1.add_offset (c, local_offset, size));
307     case 3: return_trace (u.format3.add_offset (c, local_offset, size));
308     // TODO: Implement tables 2, 4, 5
309     case 2:  // Should be a no-op.
310     case 4: case 5:  // Handle sparse cases.
311     default: return_trace (false);
312     }
313   }
314 
get_extentsOT::IndexSubtable315   bool get_extents (hb_glyph_extents_t *extents HB_UNUSED, bool scale HB_UNUSED) const
316   {
317     switch (u.header.indexFormat)
318     {
319     case 2: case 5: /* TODO */
320     case 1: case 3: case 4: /* Variable-metrics formats do not have metrics here. */
321     default:return (false);
322     }
323   }
324 
325   bool
get_image_dataOT::IndexSubtable326   get_image_data (unsigned int idx, unsigned int *offset,
327 		  unsigned int *length, unsigned int *format) const
328   {
329     *format = u.header.imageFormat;
330     switch (u.header.indexFormat)
331     {
332     case 1: return u.format1.get_image_data (idx, offset, length);
333     case 3: return u.format3.get_image_data (idx, offset, length);
334     default: return false;
335     }
336   }
337 
get_headerOT::IndexSubtable338   const IndexSubtableHeader* get_header () const { return &u.header; }
339 
populate_headerOT::IndexSubtable340   void populate_header (unsigned index_format,
341 			unsigned image_format,
342 			unsigned int image_data_offset,
343 			unsigned int *size)
344   {
345     u.header.indexFormat = index_format;
346     u.header.imageFormat = image_format;
347     u.header.imageDataOffset = image_data_offset;
348     switch (u.header.indexFormat)
349     {
350     case 1: *size += IndexSubtableFormat1::min_size; break;
351     case 3: *size += IndexSubtableFormat3::min_size; break;
352     }
353   }
354 
355   protected:
356   union {
357   IndexSubtableHeader	header;
358   IndexSubtableFormat1	format1;
359   IndexSubtableFormat3	format3;
360   /* TODO: Format 2, 4, 5. */
361   } u;
362   public:
363   DEFINE_SIZE_UNION (8, header);
364 };
365 
366 struct IndexSubtableRecord
367 {
368   /* XXX Remove this and fix by not inserting it into vector. */
operator =OT::IndexSubtableRecord369   IndexSubtableRecord& operator = (const IndexSubtableRecord &o)
370   {
371     firstGlyphIndex = o.firstGlyphIndex;
372     lastGlyphIndex = o.lastGlyphIndex;
373     offsetToSubtable = (unsigned) o.offsetToSubtable;
374     assert (offsetToSubtable.is_null ());
375     return *this;
376   }
377 
sanitizeOT::IndexSubtableRecord378   bool sanitize (hb_sanitize_context_t *c, const void *base) const
379   {
380     TRACE_SANITIZE (this);
381     return_trace (c->check_struct (this) &&
382 		  hb_barrier () &&
383 		  firstGlyphIndex <= lastGlyphIndex &&
384 		  offsetToSubtable.sanitize (c, base, lastGlyphIndex - firstGlyphIndex + 1));
385   }
386 
get_subtableOT::IndexSubtableRecord387   const IndexSubtable* get_subtable (const void *base) const
388   {
389     return &(base+offsetToSubtable);
390   }
391 
add_new_subtableOT::IndexSubtableRecord392   bool add_new_subtable (hb_subset_context_t* c,
393 			 cblc_bitmap_size_subset_context_t *bitmap_size_context,
394 			 IndexSubtableRecord *record,
395 			 const hb_vector_t<hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*>> *lookup, /* IN */
396 			 const void *base,
397 			 unsigned int *start /* INOUT */) const
398   {
399     TRACE_SERIALIZE (this);
400 
401     auto *subtable = c->serializer->start_embed<IndexSubtable> ();
402     if (unlikely (!c->serializer->extend_min (subtable))) return_trace (false);
403 
404     auto *old_subtable = get_subtable (base);
405     auto *old_header = old_subtable->get_header ();
406 
407     subtable->populate_header (old_header->indexFormat,
408 			       old_header->imageFormat,
409 			       bitmap_size_context->cbdt_prime->length,
410 			       &bitmap_size_context->size);
411 
412     unsigned int num_glyphs = 0;
413     bool early_exit = false;
414     for (unsigned int i = *start; i < lookup->length; i++)
415     {
416       hb_codepoint_t new_gid = (*lookup)[i].first;
417       const IndexSubtableRecord *next_record = (*lookup)[i].second;
418       const IndexSubtable *next_subtable = next_record->get_subtable (base);
419       auto *next_header = next_subtable->get_header ();
420       if (next_header != old_header)
421       {
422 	*start = i;
423 	early_exit = true;
424 	break;
425       }
426       unsigned int num_missing = record->add_glyph_for_subset (new_gid);
427       if (unlikely (!subtable->fill_missing_glyphs (c->serializer,
428 						    bitmap_size_context->cbdt_prime->length,
429 						    num_missing,
430 						    &bitmap_size_context->size,
431 						    &num_glyphs)))
432 	return_trace (false);
433 
434       hb_codepoint_t old_gid = 0;
435       c->plan->old_gid_for_new_gid (new_gid, &old_gid);
436       if (old_gid < next_record->firstGlyphIndex)
437 	return_trace (false);
438 
439       unsigned int old_idx = (unsigned int) old_gid - next_record->firstGlyphIndex;
440       if (unlikely (!next_subtable->copy_glyph_at_idx (c->serializer,
441 						       old_idx,
442 						       bitmap_size_context->cbdt,
443 						       bitmap_size_context->cbdt_length,
444 						       bitmap_size_context->cbdt_prime,
445 						       subtable,
446 						       &bitmap_size_context->size)))
447 	return_trace (false);
448       num_glyphs += 1;
449     }
450     if (!early_exit)
451       *start = lookup->length;
452     if (unlikely (!subtable->finish_subtable (c->serializer,
453 					      bitmap_size_context->cbdt_prime->length,
454 					      num_glyphs,
455 					      &bitmap_size_context->size)))
456       return_trace (false);
457     return_trace (true);
458   }
459 
add_new_recordOT::IndexSubtableRecord460   bool add_new_record (hb_subset_context_t *c,
461 		       cblc_bitmap_size_subset_context_t *bitmap_size_context,
462 		       const hb_vector_t<hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*>> *lookup, /* IN */
463 		       const void *base,
464 		       unsigned int *start, /* INOUT */
465 		       hb_vector_t<IndexSubtableRecord>* records /* INOUT */) const
466   {
467     TRACE_SERIALIZE (this);
468     auto snap = c->serializer->snapshot ();
469     unsigned int old_size = bitmap_size_context->size;
470     unsigned int old_cbdt_prime_length = bitmap_size_context->cbdt_prime->length;
471 
472     // Set to invalid state to indicate filling glyphs is not yet started.
473     if (unlikely (!c->serializer->check_success (records->resize (records->length + 1))))
474       return_trace (false);
475 
476     records->tail ().firstGlyphIndex = 1;
477     records->tail ().lastGlyphIndex = 0;
478     bitmap_size_context->size += IndexSubtableRecord::min_size;
479 
480     c->serializer->push ();
481 
482     if (unlikely (!add_new_subtable (c, bitmap_size_context, &(records->tail ()), lookup, base, start)))
483     {
484       c->serializer->pop_discard ();
485       c->serializer->revert (snap);
486       bitmap_size_context->cbdt_prime->shrink (old_cbdt_prime_length);
487       bitmap_size_context->size = old_size;
488       records->resize (records->length - 1);
489       return_trace (false);
490     }
491 
492     bitmap_size_context->num_tables += 1;
493     return_trace (true);
494   }
495 
add_glyph_for_subsetOT::IndexSubtableRecord496   unsigned int add_glyph_for_subset (hb_codepoint_t gid)
497   {
498     if (firstGlyphIndex > lastGlyphIndex)
499     {
500       firstGlyphIndex = gid;
501       lastGlyphIndex = gid;
502       return 0;
503     }
504     // TODO maybe assert? this shouldn't occur.
505     if (lastGlyphIndex > gid)
506       return 0;
507     unsigned int num_missing = (unsigned int) (gid - lastGlyphIndex - 1);
508     lastGlyphIndex = gid;
509     return num_missing;
510   }
511 
get_extentsOT::IndexSubtableRecord512   bool get_extents (hb_glyph_extents_t *extents, const void *base, bool scale) const
513   { return (base+offsetToSubtable).get_extents (extents, scale); }
514 
get_image_dataOT::IndexSubtableRecord515   bool get_image_data (unsigned int  gid,
516 		       const void   *base,
517 		       unsigned int *offset,
518 		       unsigned int *length,
519 		       unsigned int *format) const
520   {
521     if (gid < firstGlyphIndex || gid > lastGlyphIndex) return false;
522     return (base+offsetToSubtable).get_image_data (gid - firstGlyphIndex,
523 						   offset, length, format);
524   }
525 
526   HBGlyphID16			firstGlyphIndex;
527   HBGlyphID16			lastGlyphIndex;
528   Offset32To<IndexSubtable>	offsetToSubtable;
529   public:
530   DEFINE_SIZE_STATIC (8);
531 };
532 
533 struct IndexSubtableArray
534 {
535   friend struct CBDT;
536 
sanitizeOT::IndexSubtableArray537   bool sanitize (hb_sanitize_context_t *c, unsigned int count) const
538   {
539     TRACE_SANITIZE (this);
540     return_trace (indexSubtablesZ.sanitize (c, count, this));
541   }
542 
543   void
build_lookupOT::IndexSubtableArray544   build_lookup (hb_subset_context_t *c, cblc_bitmap_size_subset_context_t *bitmap_size_context,
545 		hb_vector_t<hb_pair_t<hb_codepoint_t,
546 		const IndexSubtableRecord*>> *lookup /* OUT */) const
547   {
548     bool start_glyph_is_set = false;
549     unsigned num_glyphs = c->plan->num_output_glyphs ();
550     for (hb_codepoint_t new_gid = 0; new_gid < num_glyphs; new_gid++)
551     {
552       hb_codepoint_t old_gid;
553       if (unlikely (!c->plan->old_gid_for_new_gid (new_gid, &old_gid))) continue;
554 
555       const IndexSubtableRecord* record = find_table (old_gid, bitmap_size_context->num_tables);
556       if (unlikely (!record)) continue;
557 
558       // Don't add gaps to the lookup. The best way to determine if a glyph is a
559       // gap is that it has no image data.
560       unsigned int offset, length, format;
561       if (unlikely (!record->get_image_data (old_gid, this, &offset, &length, &format))) continue;
562 
563       lookup->push (hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*> (new_gid, record));
564 
565       if (!start_glyph_is_set)
566       {
567 	bitmap_size_context->start_glyph = new_gid;
568 	start_glyph_is_set = true;
569       }
570 
571       bitmap_size_context->end_glyph = new_gid;
572     }
573   }
574 
575   bool
subsetOT::IndexSubtableArray576   subset (hb_subset_context_t *c,
577 	  cblc_bitmap_size_subset_context_t *bitmap_size_context) const
578   {
579     TRACE_SUBSET (this);
580 
581     hb_vector_t<hb_pair_t<hb_codepoint_t, const IndexSubtableRecord*>> lookup;
582     build_lookup (c, bitmap_size_context, &lookup);
583     if (unlikely (!c->serializer->propagate_error (lookup)))
584       return false;
585 
586     bitmap_size_context->size = 0;
587     bitmap_size_context->num_tables = 0;
588     hb_vector_t<IndexSubtableRecord> records;
589     for (unsigned int start = 0; start < lookup.length;)
590     {
591       if (unlikely (!lookup[start].second->add_new_record (c, bitmap_size_context, &lookup, this, &start, &records)))
592       {
593 	// Discard any leftover pushes to the serializer from successful records.
594 	for (unsigned int i = 0; i < records.length; i++)
595 	  c->serializer->pop_discard ();
596 	return_trace (false);
597       }
598     }
599 
600     /* Workaround to ensure offset ordering is from least to greatest when
601      * resolving links. */
602     hb_vector_t<hb_serialize_context_t::objidx_t> objidxs;
603     for (unsigned int i = 0; i < records.length; i++)
604       objidxs.push (c->serializer->pop_pack ());
605     for (unsigned int i = 0; i < records.length; i++)
606     {
607       IndexSubtableRecord* record = c->serializer->embed (records[i]);
608       if (unlikely (!record)) return_trace (false);
609       c->serializer->add_link (record->offsetToSubtable, objidxs[records.length - 1 - i]);
610     }
611     return_trace (true);
612   }
613 
614   public:
find_tableOT::IndexSubtableArray615   const IndexSubtableRecord* find_table (hb_codepoint_t glyph, unsigned int numTables) const
616   {
617     for (unsigned int i = 0; i < numTables; ++i)
618     {
619       unsigned int firstGlyphIndex = indexSubtablesZ[i].firstGlyphIndex;
620       unsigned int lastGlyphIndex = indexSubtablesZ[i].lastGlyphIndex;
621       if (firstGlyphIndex <= glyph && glyph <= lastGlyphIndex)
622 	return &indexSubtablesZ[i];
623     }
624     return nullptr;
625   }
626 
627   protected:
628   UnsizedArrayOf<IndexSubtableRecord>	indexSubtablesZ;
629 };
630 
631 struct BitmapSizeTable
632 {
633   friend struct CBLC;
634   friend struct CBDT;
635 
sanitizeOT::BitmapSizeTable636   bool sanitize (hb_sanitize_context_t *c, const void *base) const
637   {
638     TRACE_SANITIZE (this);
639     return_trace (c->check_struct (this) &&
640 		  hb_barrier () &&
641 		  indexSubtableArrayOffset.sanitize (c, base, numberOfIndexSubtables) &&
642 		  horizontal.sanitize (c) &&
643 		  vertical.sanitize (c));
644   }
645 
646   const IndexSubtableRecord *
find_tableOT::BitmapSizeTable647   find_table (hb_codepoint_t glyph, const void *base, const void **out_base) const
648   {
649     *out_base = &(base+indexSubtableArrayOffset);
650     return (base+indexSubtableArrayOffset).find_table (glyph, numberOfIndexSubtables);
651   }
652 
653   bool
subsetOT::BitmapSizeTable654   subset (hb_subset_context_t *c, const void *base,
655 	  const char *cbdt, unsigned int cbdt_length,
656 	  hb_vector_t<char> *cbdt_prime /* INOUT */) const
657   {
658     TRACE_SUBSET (this);
659     auto *out_table = c->serializer->embed (this);
660     if (unlikely (!out_table)) return_trace (false);
661 
662     cblc_bitmap_size_subset_context_t bitmap_size_context;
663     bitmap_size_context.cbdt = cbdt;
664     bitmap_size_context.cbdt_length = cbdt_length;
665     bitmap_size_context.cbdt_prime = cbdt_prime;
666     bitmap_size_context.size = indexTablesSize;
667     bitmap_size_context.num_tables = numberOfIndexSubtables;
668     bitmap_size_context.start_glyph = 1;
669     bitmap_size_context.end_glyph = 0;
670 
671     if (!out_table->indexSubtableArrayOffset.serialize_subset (c,
672 							       indexSubtableArrayOffset,
673 							       base,
674 							       &bitmap_size_context))
675       return_trace (false);
676     if (!bitmap_size_context.size ||
677 	!bitmap_size_context.num_tables ||
678 	bitmap_size_context.start_glyph > bitmap_size_context.end_glyph)
679       return_trace (false);
680 
681     out_table->indexTablesSize = bitmap_size_context.size;
682     out_table->numberOfIndexSubtables = bitmap_size_context.num_tables;
683     out_table->startGlyphIndex = bitmap_size_context.start_glyph;
684     out_table->endGlyphIndex = bitmap_size_context.end_glyph;
685     return_trace (true);
686   }
687 
688   protected:
689   NNOffset32To<IndexSubtableArray>
690 			indexSubtableArrayOffset;
691   HBUINT32		indexTablesSize;
692   HBUINT32		numberOfIndexSubtables;
693   HBUINT32		colorRef;
694   SBitLineMetrics	horizontal;
695   SBitLineMetrics	vertical;
696   HBGlyphID16		startGlyphIndex;
697   HBGlyphID16		endGlyphIndex;
698   HBUINT8		ppemX;
699   HBUINT8		ppemY;
700   HBUINT8		bitDepth;
701   HBINT8		flags;
702   public:
703   DEFINE_SIZE_STATIC (48);
704 };
705 
706 
707 /*
708  * Glyph Bitmap Data Formats.
709  */
710 
711 struct GlyphBitmapDataFormat17
712 {
713   SmallGlyphMetrics	glyphMetrics;
714   Array32Of<HBUINT8>	data;
715   public:
716   DEFINE_SIZE_ARRAY (9, data);
717 };
718 
719 struct GlyphBitmapDataFormat18
720 {
721   BigGlyphMetrics	glyphMetrics;
722   Array32Of<HBUINT8>	data;
723   public:
724   DEFINE_SIZE_ARRAY (12, data);
725 };
726 
727 struct GlyphBitmapDataFormat19
728 {
729   Array32Of<HBUINT8>	data;
730   public:
731   DEFINE_SIZE_ARRAY (4, data);
732 };
733 
734 struct CBLC
735 {
736   friend struct CBDT;
737 
738   static constexpr hb_tag_t tableTag = HB_OT_TAG_CBLC;
739 
sanitizeOT::CBLC740   bool sanitize (hb_sanitize_context_t *c) const
741   {
742     TRACE_SANITIZE (this);
743     return_trace (c->check_struct (this) &&
744 		  hb_barrier () &&
745 		  likely (version.major == 2 || version.major == 3) &&
746 		  hb_barrier () &&
747 		  sizeTables.sanitize (c, this));
748   }
749 
750   static bool
sink_cbdtOT::CBLC751   sink_cbdt (hb_subset_context_t *c, hb_vector_t<char>* cbdt_prime)
752   {
753     hb_blob_t *cbdt_prime_blob = hb_blob_create (cbdt_prime->arrayZ,
754 						 cbdt_prime->length,
755 						 HB_MEMORY_MODE_WRITABLE,
756 						 cbdt_prime->arrayZ,
757 						 hb_free);
758     cbdt_prime->init ();  // Leak arrayZ to the blob.
759     bool ret = c->plan->add_table (HB_OT_TAG_CBDT, cbdt_prime_blob);
760     hb_blob_destroy (cbdt_prime_blob);
761     return ret;
762   }
763 
764   bool
subset_size_tableOT::CBLC765   subset_size_table (hb_subset_context_t *c, const BitmapSizeTable& table,
766 		     const char *cbdt /* IN */, unsigned int cbdt_length,
767 		     CBLC *cblc_prime /* INOUT */, hb_vector_t<char> *cbdt_prime /* INOUT */) const
768   {
769     TRACE_SUBSET (this);
770     cblc_prime->sizeTables.len++;
771 
772     auto snap = c->serializer->snapshot ();
773     auto cbdt_prime_len = cbdt_prime->length;
774 
775     if (!table.subset (c, this, cbdt, cbdt_length, cbdt_prime))
776     {
777       cblc_prime->sizeTables.len--;
778       c->serializer->revert (snap);
779       cbdt_prime->shrink (cbdt_prime_len);
780       return_trace (false);
781     }
782     return_trace (true);
783   }
784 
785   // Implemented in cc file as it depends on definition of CBDT.
786   HB_INTERNAL bool subset (hb_subset_context_t *c) const;
787 
788   protected:
choose_strikeOT::CBLC789   const BitmapSizeTable &choose_strike (hb_font_t *font) const
790   {
791     unsigned count = sizeTables.len;
792     if (unlikely (!count))
793       return Null (BitmapSizeTable);
794 
795     unsigned int requested_ppem = hb_max (font->x_ppem, font->y_ppem);
796     if (!requested_ppem)
797       requested_ppem = 1<<30; /* Choose largest strike. */
798     unsigned int best_i = 0;
799     unsigned int best_ppem = hb_max (sizeTables[0].ppemX, sizeTables[0].ppemY);
800 
801     for (unsigned int i = 1; i < count; i++)
802     {
803       unsigned int ppem = hb_max (sizeTables[i].ppemX, sizeTables[i].ppemY);
804       if ((requested_ppem <= ppem && ppem < best_ppem) ||
805 	  (requested_ppem > best_ppem && ppem > best_ppem))
806       {
807 	best_i = i;
808 	best_ppem = ppem;
809       }
810     }
811 
812     return sizeTables[best_i];
813   }
814 
815   protected:
816   FixedVersion<>		version;
817   Array32Of<BitmapSizeTable>	sizeTables;
818   public:
819   DEFINE_SIZE_ARRAY (8, sizeTables);
820 };
821 
822 struct CBDT
823 {
824   static constexpr hb_tag_t tableTag = HB_OT_TAG_CBDT;
825 
826   struct accelerator_t
827   {
accelerator_tOT::CBDT::accelerator_t828     accelerator_t (hb_face_t *face)
829     {
830       this->cblc = hb_sanitize_context_t ().reference_table<CBLC> (face);
831       this->cbdt = hb_sanitize_context_t ().reference_table<CBDT> (face);
832 
833       upem = hb_face_get_upem (face);
834     }
~accelerator_tOT::CBDT::accelerator_t835     ~accelerator_t ()
836     {
837       this->cblc.destroy ();
838       this->cbdt.destroy ();
839     }
840 
841     bool
get_extentsOT::CBDT::accelerator_t842     get_extents (hb_font_t *font, hb_codepoint_t glyph, hb_glyph_extents_t *extents, bool scale = true) const
843     {
844       const void *base;
845       const BitmapSizeTable &strike = this->cblc->choose_strike (font);
846       const IndexSubtableRecord *subtable_record = strike.find_table (glyph, cblc, &base);
847       if (!subtable_record || !strike.ppemX || !strike.ppemY)
848 	return false;
849 
850       if (subtable_record->get_extents (extents, base, scale))
851 	return true;
852 
853       unsigned int image_offset = 0, image_length = 0, image_format = 0;
854       if (!subtable_record->get_image_data (glyph, base, &image_offset, &image_length, &image_format))
855 	return false;
856 
857       unsigned int cbdt_len = cbdt.get_length ();
858       if (unlikely (image_offset > cbdt_len || cbdt_len - image_offset < image_length))
859 	return false;
860 
861       switch (image_format)
862       {
863       case 17: {
864 	if (unlikely (image_length < GlyphBitmapDataFormat17::min_size))
865 	  return false;
866 	auto &glyphFormat17 = StructAtOffset<GlyphBitmapDataFormat17> (this->cbdt, image_offset);
867 	glyphFormat17.glyphMetrics.get_extents (font, extents, scale);
868 	break;
869       }
870       case 18: {
871 	if (unlikely (image_length < GlyphBitmapDataFormat18::min_size))
872 	  return false;
873 	auto &glyphFormat18 = StructAtOffset<GlyphBitmapDataFormat18> (this->cbdt, image_offset);
874 	glyphFormat18.glyphMetrics.get_extents (font, extents, scale);
875 	break;
876       }
877       default: return false; /* TODO: Support other image formats. */
878       }
879 
880       /* Convert to font units. */
881       if (scale)
882       {
883 	float x_scale = upem / (float) strike.ppemX;
884 	float y_scale = upem / (float) strike.ppemY;
885 	extents->x_bearing = roundf (extents->x_bearing * x_scale);
886 	extents->y_bearing = roundf (extents->y_bearing * y_scale);
887 	extents->width = roundf (extents->width * x_scale);
888 	extents->height = roundf (extents->height * y_scale);
889       }
890 
891       return true;
892     }
893 
894     hb_blob_t*
reference_pngOT::CBDT::accelerator_t895     reference_png (hb_font_t *font, hb_codepoint_t glyph) const
896     {
897       const void *base;
898       const BitmapSizeTable &strike = this->cblc->choose_strike (font);
899       const IndexSubtableRecord *subtable_record = strike.find_table (glyph, cblc, &base);
900       if (!subtable_record || !strike.ppemX || !strike.ppemY)
901 	return hb_blob_get_empty ();
902 
903       unsigned int image_offset = 0, image_length = 0, image_format = 0;
904       if (!subtable_record->get_image_data (glyph, base, &image_offset, &image_length, &image_format))
905 	return hb_blob_get_empty ();
906 
907       unsigned int cbdt_len = cbdt.get_length ();
908       if (unlikely (image_offset > cbdt_len || cbdt_len - image_offset < image_length))
909 	return hb_blob_get_empty ();
910 
911       switch (image_format)
912       {
913       case 17:
914       {
915 	if (unlikely (image_length < GlyphBitmapDataFormat17::min_size))
916 	  return hb_blob_get_empty ();
917 	auto &glyphFormat17 = StructAtOffset<GlyphBitmapDataFormat17> (this->cbdt, image_offset);
918 	return hb_blob_create_sub_blob (cbdt.get_blob (),
919 					image_offset + GlyphBitmapDataFormat17::min_size,
920 					glyphFormat17.data.len);
921       }
922       case 18:
923       {
924 	if (unlikely (image_length < GlyphBitmapDataFormat18::min_size))
925 	  return hb_blob_get_empty ();
926 	auto &glyphFormat18 = StructAtOffset<GlyphBitmapDataFormat18> (this->cbdt, image_offset);
927 	return hb_blob_create_sub_blob (cbdt.get_blob (),
928 					image_offset + GlyphBitmapDataFormat18::min_size,
929 					glyphFormat18.data.len);
930       }
931       case 19:
932       {
933 	if (unlikely (image_length < GlyphBitmapDataFormat19::min_size))
934 	  return hb_blob_get_empty ();
935 	auto &glyphFormat19 = StructAtOffset<GlyphBitmapDataFormat19> (this->cbdt, image_offset);
936 	return hb_blob_create_sub_blob (cbdt.get_blob (),
937 					image_offset + GlyphBitmapDataFormat19::min_size,
938 					glyphFormat19.data.len);
939       }
940       default: return hb_blob_get_empty (); /* TODO: Support other image formats. */
941       }
942     }
943 
has_dataOT::CBDT::accelerator_t944     bool has_data () const { return cbdt.get_length (); }
945 
paint_glyphOT::CBDT::accelerator_t946     bool paint_glyph (hb_font_t *font, hb_codepoint_t glyph, hb_paint_funcs_t *funcs, void *data) const
947     {
948       hb_glyph_extents_t extents;
949       hb_glyph_extents_t pixel_extents;
950       hb_blob_t *blob = reference_png (font, glyph);
951 
952       if (unlikely (blob == hb_blob_get_empty ()))
953         return false;
954 
955       if (unlikely (!hb_font_get_glyph_extents (font, glyph, &extents)))
956         return false;
957 
958       if (unlikely (!get_extents (font, glyph, &pixel_extents, false)))
959         return false;
960 
961       bool ret = funcs->image (data,
962 			       blob,
963 			       pixel_extents.width, -pixel_extents.height,
964 			       HB_PAINT_IMAGE_FORMAT_PNG,
965 			       font->slant_xy,
966 			       &extents);
967 
968       hb_blob_destroy (blob);
969       return ret;
970     }
971 
972     private:
973     hb_blob_ptr_t<CBLC> cblc;
974     hb_blob_ptr_t<CBDT> cbdt;
975 
976     unsigned int upem;
977   };
978 
sanitizeOT::CBDT979   bool sanitize (hb_sanitize_context_t *c) const
980   {
981     TRACE_SANITIZE (this);
982     return_trace (c->check_struct (this) &&
983 		  hb_barrier () &&
984 		  likely (version.major == 2 || version.major == 3));
985   }
986 
987   protected:
988   FixedVersion<>		version;
989   UnsizedArrayOf<HBUINT8>	dataZ;
990   public:
991   DEFINE_SIZE_ARRAY (4, dataZ);
992 };
993 
994 inline bool
subset(hb_subset_context_t * c) const995 CBLC::subset (hb_subset_context_t *c) const
996 {
997   TRACE_SUBSET (this);
998 
999   // Use a vector as a secondary buffer as the tables need to be built in parallel.
1000   hb_vector_t<char> cbdt_prime;
1001 
1002   auto *cblc_prime = c->serializer->start_embed<CBLC> ();
1003   if (unlikely (!c->serializer->extend_min (cblc_prime))) return_trace (false);
1004   cblc_prime->version = version;
1005 
1006   hb_blob_t* cbdt_blob = hb_sanitize_context_t ().reference_table<CBDT> (c->plan->source);
1007   unsigned int cbdt_length;
1008   CBDT* cbdt = (CBDT *) hb_blob_get_data (cbdt_blob, &cbdt_length);
1009   if (unlikely (cbdt_length < CBDT::min_size))
1010   {
1011     hb_blob_destroy (cbdt_blob);
1012     return_trace (false);
1013   }
1014   _copy_data_to_cbdt (&cbdt_prime, cbdt, CBDT::min_size);
1015 
1016   for (const BitmapSizeTable& table : + sizeTables.iter ())
1017     subset_size_table (c, table, (const char *) cbdt, cbdt_length, cblc_prime, &cbdt_prime);
1018 
1019   hb_blob_destroy (cbdt_blob);
1020 
1021   return_trace (CBLC::sink_cbdt (c, &cbdt_prime));
1022 }
1023 
1024 struct CBDT_accelerator_t : CBDT::accelerator_t {
CBDT_accelerator_tOT::CBDT_accelerator_t1025   CBDT_accelerator_t (hb_face_t *face) : CBDT::accelerator_t (face) {}
1026 };
1027 
1028 
1029 } /* namespace OT */
1030 
1031 #endif /* OT_COLOR_CBDT_CBDT_HH */
1032