summaryrefslogtreecommitdiffstats
path: root/gfx/ots/src/cpal.cc
blob: b20088900c9e2789bc9c02613de36b7344cba1ef (plain)
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
// Copyright (c) 2022 The OTS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cpal.h"
#include "name.h"

// CPAL - Color Palette Table
// http://www.microsoft.com/typography/otspec/cpal.htm

#define TABLE_NAME "CPAL"

namespace {

// Caller has sized the colorRecords array, so we know how much to try and read.
bool ParseColorRecordsArray(const ots::Font* font,
                            const uint8_t* data, size_t length,
                            std::vector<uint32_t>* colorRecords)
{
  ots::Buffer subtable(data, length);

  for (auto& color : *colorRecords) {
    if (!subtable.ReadU32(&color)) {
      return OTS_FAILURE_MSG("Failed to read color record");
    }
  }

  return true;
}

// Caller has sized the paletteTypes array, so we know how much to try and read.
bool ParsePaletteTypesArray(const ots::Font* font,
                            const uint8_t* data, size_t length,
                            std::vector<uint32_t>* paletteTypes)
{
  ots::Buffer subtable(data, length);

  constexpr uint32_t USABLE_WITH_LIGHT_BACKGROUND = 0x0001;
  constexpr uint32_t USABLE_WITH_DARK_BACKGROUND = 0x0002;
  constexpr uint32_t RESERVED = ~(USABLE_WITH_LIGHT_BACKGROUND | USABLE_WITH_DARK_BACKGROUND);

  for (auto& type : *paletteTypes) {
    if (!subtable.ReadU32(&type)) {
      return OTS_FAILURE_MSG("Failed to read palette type");
    }
    if (type & RESERVED) {
      // Should we treat this as failure? For now, just a warning; seems unlikely
      // to be dangerous.
      OTS_WARNING("Invalid (reserved) palette type flags %08x", type);
      type &= ~RESERVED;
    }
  }

  return true;
}

// Caller has sized the labels array, so we know how much to try and read.
bool ParseLabelsArray(const ots::Font* font,
                      const uint8_t* data, size_t length,
                      std::vector<uint16_t>* labels,
                      const char* labelType)
{
  ots::Buffer subtable(data, length);

  auto* name = static_cast<ots::OpenTypeNAME*>(font->GetTypedTable(OTS_TAG_NAME));
  if (!name) {
    return OTS_FAILURE_MSG("Required name table missing");
  }

  for (auto& nameID : *labels) {
    if (!subtable.ReadU16(&nameID)) {
      return OTS_FAILURE_MSG("Failed to read %s label ID", labelType);
    }
    if (nameID != 0xffff) {
      if (!name->IsValidNameId(nameID)) {
        OTS_WARNING("Label ID %u for %s missing from name table", nameID, labelType);
        nameID = 0xffff;
      }
    }
  }

  return true;
}

}  // namespace

namespace ots {

bool OpenTypeCPAL::Parse(const uint8_t *data, size_t length) {
  Font *font = GetFont();
  Buffer table(data, length);

  // Header fields common to versions 0 and 1. These are recomputed
  // from the array sizes during serialization.
  uint16_t numPalettes;
  uint16_t numColorRecords;
  uint32_t colorRecordsArrayOffset;

  if (!table.ReadU16(&this->version) ||
      !table.ReadU16(&this->num_palette_entries) ||
      !table.ReadU16(&numPalettes) ||
      !table.ReadU16(&numColorRecords) ||
      !table.ReadU32(&colorRecordsArrayOffset)) {
    return Error("Failed to read CPAL table header");
  }

  if (this->version > 1) {
    return Error("Unknown CPAL table version %u", this->version);
  }

  if (!this->num_palette_entries || !numPalettes || !numColorRecords) {
    return Error("Empty CPAL is not valid");
  }

  if (this->num_palette_entries > numColorRecords) {
    return Error("Not enough color records for a complete palette");
  }

  uint32_t headerSize = 4 * sizeof(uint16_t) + sizeof(uint32_t) +
      numPalettes * sizeof(uint16_t);

  // uint16_t colorRecordIndices[numPalettes]
  this->colorRecordIndices.resize(numPalettes);
  for (auto& colorRecordIndex : this->colorRecordIndices) {
    if (!table.ReadU16(&colorRecordIndex)) {
      return Error("Failed to read color record index");
    }
    if (colorRecordIndex > numColorRecords - this->num_palette_entries) {
      return Error("Palette overflows color records array");
    }
  }

  uint32_t paletteTypesArrayOffset = 0;
  uint32_t paletteLabelsArrayOffset = 0;
  uint32_t paletteEntryLabelsArrayOffset = 0;
  if (this->version == 1) {
    if (!table.ReadU32(&paletteTypesArrayOffset) ||
        !table.ReadU32(&paletteLabelsArrayOffset) ||
        !table.ReadU32(&paletteEntryLabelsArrayOffset)) {
      return Error("Failed to read CPAL v.1 table header");
    }
    headerSize += 3 * sizeof(uint32_t);
  }

  // The following arrays may occur in any order, as they're independently referenced
  // by offsets in the header.

  if (colorRecordsArrayOffset < headerSize || colorRecordsArrayOffset >= length) {
    return Error("Bad color records array offset in table header");
  }
  this->colorRecords.resize(numColorRecords);
  if (!ParseColorRecordsArray(font, data + colorRecordsArrayOffset, length - colorRecordsArrayOffset,
                              &this->colorRecords)) {
    return Error("Failed to parse color records array");
  }

  if (paletteTypesArrayOffset) {
    if (paletteTypesArrayOffset < headerSize || paletteTypesArrayOffset >= length) {
      return Error("Bad palette types array offset in table header");
    }
    this->paletteTypes.resize(numPalettes);
    if (!ParsePaletteTypesArray(font, data + paletteTypesArrayOffset, length - paletteTypesArrayOffset,
                                &this->paletteTypes)) {
      return Error("Failed to parse palette types array");
    }
  }

  if (paletteLabelsArrayOffset) {
    if (paletteLabelsArrayOffset < headerSize || paletteLabelsArrayOffset >= length) {
      return Error("Bad palette labels array offset in table header");
    }
    this->paletteLabels.resize(numPalettes);
    if (!ParseLabelsArray(font, data + paletteLabelsArrayOffset, length - paletteLabelsArrayOffset,
                          &this->paletteLabels, "palette")) {
      return Error("Failed to parse palette labels array");
    }
  }

  if (paletteEntryLabelsArrayOffset) {
    if (paletteEntryLabelsArrayOffset < headerSize || paletteEntryLabelsArrayOffset >= length) {
      return Error("Bad palette entry labels array offset in table header");
    }
    this->paletteEntryLabels.resize(this->num_palette_entries);
    if (!ParseLabelsArray(font, data + paletteEntryLabelsArrayOffset, length - paletteEntryLabelsArrayOffset,
                          &this->paletteEntryLabels, "palette entry")) {
      return Error("Failed to parse palette entry labels array");
    }
  }

  return true;
}

bool OpenTypeCPAL::Serialize(OTSStream *out) {
  uint16_t numPalettes = this->colorRecordIndices.size();
  uint16_t numColorRecords = this->colorRecords.size();

#ifndef NDEBUG
  off_t start = out->Tell();
#endif

  size_t colorRecordsArrayOffset = 4 * sizeof(uint16_t) + sizeof(uint32_t) +
      numPalettes * sizeof(uint16_t);
  if (this->version == 1) {
    colorRecordsArrayOffset += 3 * sizeof(uint32_t);
  }

  size_t totalLen = colorRecordsArrayOffset + numColorRecords * sizeof(uint32_t);

  if (!out->WriteU16(this->version) ||
      !out->WriteU16(this->num_palette_entries) ||
      !out->WriteU16(numPalettes) ||
      !out->WriteU16(numColorRecords) ||
      !out->WriteU32(colorRecordsArrayOffset)) {
    return Error("Failed to write CPAL header");
  }

  for (auto i : this->colorRecordIndices) {
    if (!out->WriteU16(i)) {
      return Error("Failed to write color record indices");
    }
  }

  if (this->version == 1) {
    size_t paletteTypesArrayOffset = 0;
    if (!this->paletteTypes.empty()) {
      assert(paletteTypes.size() == numPalettes);
      paletteTypesArrayOffset = totalLen;
      totalLen += numPalettes * sizeof(uint32_t);
    }

    size_t paletteLabelsArrayOffset = 0;
    if (!this->paletteLabels.empty()) {
      assert(paletteLabels.size() == numPalettes);
      paletteLabelsArrayOffset = totalLen;
      totalLen += numPalettes * sizeof(uint16_t);
    }

    size_t paletteEntryLabelsArrayOffset = 0;
    if (!this->paletteEntryLabels.empty()) {
      assert(paletteEntryLabels.size() == this->num_palette_entries);
      paletteEntryLabelsArrayOffset = totalLen;
      totalLen += this->num_palette_entries * sizeof(uint16_t);
    }

    if (!out->WriteU32(paletteTypesArrayOffset) ||
        !out->WriteU32(paletteLabelsArrayOffset) ||
        !out->WriteU32(paletteEntryLabelsArrayOffset)) {
      return Error("Failed to write CPAL v.1 header");
    }
  }

  for (auto i : this->colorRecords) {
    if (!out->WriteU32(i)) {
      return Error("Failed to write color records");
    }
  }

  if (this->version == 1) {
    for (auto i : this->paletteTypes) {
      if (!out->WriteU32(i)) {
        return Error("Failed to write palette types");
      }
    }

    for (auto i : this->paletteLabels) {
      if (!out->WriteU16(i)) {
        return Error("Failed to write palette labels");
      }
    }

    for (auto i : this->paletteEntryLabels) {
      if (!out->WriteU16(i)) {
        return Error("Failed to write palette entry labels");
      }
    }
  }

  assert(size_t(out->Tell() - start) == totalLen);

  return true;
}

}  // namespace ots

#undef TABLE_NAME