@automovie/ingest 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/README.md +9 -29
  2. package/lib/AUTOMOVIE_GLTF_MOTION_INTERPRETATION_PROFILE.d.ts +4 -1
  3. package/lib/AUTOMOVIE_GLTF_MOTION_INTERPRETATION_PROFILE.js +4 -1
  4. package/lib/AUTOMOVIE_GLTF_MOTION_INTERPRETATION_PROFILE.js.map +1 -1
  5. package/lib/AUTO_MOVIE_EXTERNAL_MODEL_INGEST_PROFILES.d.ts +4 -1
  6. package/lib/AUTO_MOVIE_EXTERNAL_MODEL_INGEST_PROFILES.js +4 -1
  7. package/lib/AUTO_MOVIE_EXTERNAL_MODEL_INGEST_PROFILES.js.map +1 -1
  8. package/lib/adoptAutoMovieExternalMotion.d.ts +21 -11
  9. package/lib/adoptAutoMovieExternalMotion.js +26 -12
  10. package/lib/adoptAutoMovieExternalMotion.js.map +1 -1
  11. package/lib/audio/admitProductionTtsReceipt.d.ts +25 -0
  12. package/lib/audio/admitProductionTtsReceipt.js +166 -0
  13. package/lib/audio/admitProductionTtsReceipt.js.map +1 -0
  14. package/lib/audio/decodeProductionAudioAsset.d.ts +42 -14
  15. package/lib/audio/decodeProductionAudioAsset.js +53 -30
  16. package/lib/audio/decodeProductionAudioAsset.js.map +1 -1
  17. package/lib/audio/index.d.ts +1 -0
  18. package/lib/audio/index.js +1 -0
  19. package/lib/audio/index.js.map +1 -1
  20. package/lib/audio/resampleProductionAudio.d.ts +22 -0
  21. package/lib/audio/resampleProductionAudio.js +103 -0
  22. package/lib/audio/resampleProductionAudio.js.map +1 -0
  23. package/lib/decodeAutoMoviePpmImage.d.ts +10 -18
  24. package/lib/decodeAutoMoviePpmImage.js +10 -18
  25. package/lib/decodeAutoMoviePpmImage.js.map +1 -1
  26. package/lib/font/TrueTypeByteReader.d.ts +34 -0
  27. package/lib/font/TrueTypeByteReader.js +67 -0
  28. package/lib/font/TrueTypeByteReader.js.map +1 -0
  29. package/lib/font/decodeAutoMovieTrueTypeFont.d.ts +31 -0
  30. package/lib/font/decodeAutoMovieTrueTypeFont.js +168 -0
  31. package/lib/font/decodeAutoMovieTrueTypeFont.js.map +1 -0
  32. package/lib/font/index.d.ts +1 -0
  33. package/lib/font/index.js +18 -0
  34. package/lib/font/index.js.map +1 -0
  35. package/lib/font/readTrueTypeCharacterMap.d.ts +23 -0
  36. package/lib/font/readTrueTypeCharacterMap.js +98 -0
  37. package/lib/font/readTrueTypeCharacterMap.js.map +1 -0
  38. package/lib/font/readTrueTypeGlyphOutline.d.ts +45 -0
  39. package/lib/font/readTrueTypeGlyphOutline.js +275 -0
  40. package/lib/font/readTrueTypeGlyphOutline.js.map +1 -0
  41. package/lib/font/readTrueTypeKerning.d.ts +19 -0
  42. package/lib/font/readTrueTypeKerning.js +63 -0
  43. package/lib/font/readTrueTypeKerning.js.map +1 -0
  44. package/lib/font/readTrueTypeNames.d.ts +20 -0
  45. package/lib/font/readTrueTypeNames.js +75 -0
  46. package/lib/font/readTrueTypeNames.js.map +1 -0
  47. package/lib/humanoidSkeleton.d.ts +28 -15
  48. package/lib/humanoidSkeleton.js +28 -15
  49. package/lib/humanoidSkeleton.js.map +1 -1
  50. package/lib/index.d.ts +1 -0
  51. package/lib/index.js +1 -0
  52. package/lib/index.js.map +1 -1
  53. package/lib/ingestDocument.d.ts +25 -12
  54. package/lib/ingestDocument.js +25 -12
  55. package/lib/ingestDocument.js.map +1 -1
  56. package/lib/inspectAutoMovieExternalModelBytes.d.ts +24 -12
  57. package/lib/inspectAutoMovieExternalModelBytes.js +24 -12
  58. package/lib/inspectAutoMovieExternalModelBytes.js.map +1 -1
  59. package/lib/internal/IAccessorSource.d.ts +11 -8
  60. package/lib/internal/IExternalModelAccessorReader.d.ts +1 -8
  61. package/lib/internal/IHumanoidSlot.d.ts +9 -10
  62. package/lib/internal/IParsedContainer.d.ts +10 -8
  63. package/lib/internal/SHAPE_COMPONENTS.d.ts +4 -1
  64. package/lib/internal/SHAPE_COMPONENTS.js +4 -1
  65. package/lib/internal/SHAPE_COMPONENTS.js.map +1 -1
  66. package/lib/internal/accessorElementByteLength.d.ts +1 -11
  67. package/lib/internal/accessorElementByteLength.js +1 -11
  68. package/lib/internal/accessorElementByteLength.js.map +1 -1
  69. package/lib/internal/accessorReader.d.ts +5 -9
  70. package/lib/internal/accessorReader.js +5 -9
  71. package/lib/internal/accessorReader.js.map +1 -1
  72. package/lib/internal/accessorValues.d.ts +10 -10
  73. package/lib/internal/accessorValues.js +10 -10
  74. package/lib/internal/collectExternalResources.d.ts +1 -11
  75. package/lib/internal/collectExternalResources.js +1 -11
  76. package/lib/internal/collectExternalResources.js.map +1 -1
  77. package/lib/internal/compareCodeUnits.d.ts +1 -11
  78. package/lib/internal/compareCodeUnits.js +1 -11
  79. package/lib/internal/compareCodeUnits.js.map +1 -1
  80. package/lib/internal/composeLocalTransform.d.ts +13 -10
  81. package/lib/internal/composeLocalTransform.js +13 -10
  82. package/lib/internal/composeLocalTransform.js.map +1 -1
  83. package/lib/internal/decodeDataUri.d.ts +4 -9
  84. package/lib/internal/decodeDataUri.js +4 -9
  85. package/lib/internal/decodeDataUri.js.map +1 -1
  86. package/lib/internal/decodeGlb.d.ts +1 -11
  87. package/lib/internal/decodeGlb.js +1 -11
  88. package/lib/internal/decodeGlb.js.map +1 -1
  89. package/lib/internal/decodeJson.d.ts +1 -11
  90. package/lib/internal/decodeJson.js +10 -12
  91. package/lib/internal/decodeJson.js.map +1 -1
  92. package/lib/internal/fileExtension.d.ts +2 -9
  93. package/lib/internal/fileExtension.js +2 -9
  94. package/lib/internal/fileExtension.js.map +1 -1
  95. package/lib/internal/finiteTuple.d.ts +4 -9
  96. package/lib/internal/finiteTuple.js +4 -9
  97. package/lib/internal/finiteTuple.js.map +1 -1
  98. package/lib/internal/gltfHumanoidBones.d.ts +5 -9
  99. package/lib/internal/gltfHumanoidBones.js +5 -9
  100. package/lib/internal/gltfHumanoidBones.js.map +1 -1
  101. package/lib/internal/humanoidBoneOfName.d.ts +7 -9
  102. package/lib/internal/humanoidBoneOfName.js +7 -9
  103. package/lib/internal/humanoidBoneOfName.js.map +1 -1
  104. package/lib/internal/inspectExternalModelHierarchy.d.ts +1 -11
  105. package/lib/internal/inspectExternalModelHierarchy.js +1 -11
  106. package/lib/internal/inspectExternalModelHierarchy.js.map +1 -1
  107. package/lib/internal/inspectExternalMotion.d.ts +8 -9
  108. package/lib/internal/inspectExternalMotion.js +8 -9
  109. package/lib/internal/inspectExternalMotion.js.map +1 -1
  110. package/lib/internal/inspectExternalMotionNodes.d.ts +6 -9
  111. package/lib/internal/inspectExternalMotionNodes.js +6 -9
  112. package/lib/internal/inspectExternalMotionNodes.js.map +1 -1
  113. package/lib/internal/integerIndex.d.ts +1 -11
  114. package/lib/internal/integerIndex.js +1 -11
  115. package/lib/internal/integerIndex.js.map +1 -1
  116. package/lib/internal/integerIndices.d.ts +1 -11
  117. package/lib/internal/integerIndices.js +1 -11
  118. package/lib/internal/integerIndices.js.map +1 -1
  119. package/lib/internal/nonNegativeInteger.d.ts +1 -11
  120. package/lib/internal/nonNegativeInteger.js +1 -11
  121. package/lib/internal/nonNegativeInteger.js.map +1 -1
  122. package/lib/internal/object.d.ts +1 -11
  123. package/lib/internal/object.js +1 -11
  124. package/lib/internal/object.js.map +1 -1
  125. package/lib/internal/optionalArray.d.ts +1 -11
  126. package/lib/internal/optionalArray.js +1 -11
  127. package/lib/internal/optionalArray.js.map +1 -1
  128. package/lib/internal/optionalObject.d.ts +1 -11
  129. package/lib/internal/optionalObject.js +1 -11
  130. package/lib/internal/optionalObject.js.map +1 -1
  131. package/lib/internal/optionalStringArray.d.ts +1 -11
  132. package/lib/internal/optionalStringArray.js +1 -11
  133. package/lib/internal/optionalStringArray.js.map +1 -1
  134. package/lib/internal/positiveInteger.d.ts +1 -11
  135. package/lib/internal/positiveInteger.js +1 -11
  136. package/lib/internal/positiveInteger.js.map +1 -1
  137. package/lib/internal/readMotionAccessor.d.ts +5 -9
  138. package/lib/internal/readMotionAccessor.js +5 -9
  139. package/lib/internal/readMotionAccessor.js.map +1 -1
  140. package/lib/internal/requiredArray.d.ts +1 -11
  141. package/lib/internal/requiredArray.js +1 -11
  142. package/lib/internal/requiredArray.js.map +1 -1
  143. package/lib/internal/uniqueStrings.d.ts +1 -11
  144. package/lib/internal/uniqueStrings.js +1 -11
  145. package/lib/internal/uniqueStrings.js.map +1 -1
  146. package/lib/internal/validNodeIndex.d.ts +1 -11
  147. package/lib/internal/validNodeIndex.js +1 -11
  148. package/lib/internal/validNodeIndex.js.map +1 -1
  149. package/lib/internal/validateAccessorRange.d.ts +6 -9
  150. package/lib/internal/validateAccessorRange.js +6 -9
  151. package/lib/internal/validateAccessorRange.js.map +1 -1
  152. package/lib/internal/validateHumanoidSkinning.d.ts +8 -10
  153. package/lib/internal/validateHumanoidSkinning.js +8 -10
  154. package/lib/internal/validateHumanoidSkinning.js.map +1 -1
  155. package/lib/internal/validatePayloadClosure.d.ts +8 -9
  156. package/lib/internal/validatePayloadClosure.js +8 -9
  157. package/lib/internal/validatePayloadClosure.js.map +1 -1
  158. package/lib/internal/validateSparseAccessor.d.ts +6 -9
  159. package/lib/internal/validateSparseAccessor.js +6 -9
  160. package/lib/internal/validateSparseAccessor.js.map +1 -1
  161. package/lib/internal/vrmHumanoidBones.d.ts +7 -9
  162. package/lib/internal/vrmHumanoidBones.js +12 -10
  163. package/lib/internal/vrmHumanoidBones.js.map +1 -1
  164. package/lib/isAutoMovieExternalModelIngestProfile.d.ts +4 -10
  165. package/lib/isAutoMovieExternalModelIngestProfile.js +4 -10
  166. package/lib/isAutoMovieExternalModelIngestProfile.js.map +1 -1
  167. package/package.json +7 -7
  168. package/src/AUTOMOVIE_GLTF_MOTION_INTERPRETATION_PROFILE.ts +4 -1
  169. package/src/AUTO_MOVIE_EXTERNAL_MODEL_INGEST_PROFILES.ts +4 -1
  170. package/src/adoptAutoMovieExternalMotion.ts +26 -12
  171. package/src/audio/admitProductionTtsReceipt.ts +262 -0
  172. package/src/audio/decodeProductionAudioAsset.ts +54 -39
  173. package/src/audio/index.ts +1 -0
  174. package/src/audio/resampleProductionAudio.ts +114 -0
  175. package/src/decodeAutoMoviePpmImage.ts +10 -18
  176. package/src/font/TrueTypeByteReader.ts +80 -0
  177. package/src/font/decodeAutoMovieTrueTypeFont.ts +217 -0
  178. package/src/font/index.ts +1 -0
  179. package/src/font/readTrueTypeCharacterMap.ts +115 -0
  180. package/src/font/readTrueTypeGlyphOutline.ts +375 -0
  181. package/src/font/readTrueTypeKerning.ts +73 -0
  182. package/src/font/readTrueTypeNames.ts +74 -0
  183. package/src/humanoidSkeleton.ts +28 -15
  184. package/src/index.ts +1 -0
  185. package/src/ingestDocument.ts +25 -12
  186. package/src/inspectAutoMovieExternalModelBytes.ts +24 -12
  187. package/src/internal/IAccessorSource.ts +11 -8
  188. package/src/internal/IExternalModelAccessorReader.ts +1 -8
  189. package/src/internal/IHumanoidSlot.ts +9 -10
  190. package/src/internal/IParsedContainer.ts +10 -8
  191. package/src/internal/SHAPE_COMPONENTS.ts +4 -1
  192. package/src/internal/accessorElementByteLength.ts +1 -11
  193. package/src/internal/accessorReader.ts +5 -9
  194. package/src/internal/accessorValues.ts +10 -10
  195. package/src/internal/collectExternalResources.ts +1 -11
  196. package/src/internal/compareCodeUnits.ts +1 -11
  197. package/src/internal/composeLocalTransform.ts +13 -10
  198. package/src/internal/decodeDataUri.ts +4 -9
  199. package/src/internal/decodeGlb.ts +1 -11
  200. package/src/internal/decodeJson.ts +10 -12
  201. package/src/internal/fileExtension.ts +2 -9
  202. package/src/internal/finiteTuple.ts +4 -9
  203. package/src/internal/gltfHumanoidBones.ts +5 -9
  204. package/src/internal/humanoidBoneOfName.ts +7 -9
  205. package/src/internal/inspectExternalModelHierarchy.ts +1 -11
  206. package/src/internal/inspectExternalMotion.ts +8 -9
  207. package/src/internal/inspectExternalMotionNodes.ts +6 -9
  208. package/src/internal/integerIndex.ts +1 -11
  209. package/src/internal/integerIndices.ts +1 -11
  210. package/src/internal/nonNegativeInteger.ts +1 -11
  211. package/src/internal/object.ts +1 -11
  212. package/src/internal/optionalArray.ts +1 -11
  213. package/src/internal/optionalObject.ts +1 -11
  214. package/src/internal/optionalStringArray.ts +1 -11
  215. package/src/internal/positiveInteger.ts +1 -11
  216. package/src/internal/readMotionAccessor.ts +5 -9
  217. package/src/internal/requiredArray.ts +1 -11
  218. package/src/internal/uniqueStrings.ts +1 -11
  219. package/src/internal/validNodeIndex.ts +1 -11
  220. package/src/internal/validateAccessorRange.ts +6 -9
  221. package/src/internal/validateHumanoidSkinning.ts +8 -10
  222. package/src/internal/validatePayloadClosure.ts +8 -9
  223. package/src/internal/validateSparseAccessor.ts +6 -9
  224. package/src/internal/vrmHumanoidBones.ts +12 -10
  225. package/src/isAutoMovieExternalModelIngestProfile.ts +4 -10
@@ -0,0 +1,262 @@
1
+ import {
2
+ autoMovieRenderDigest,
3
+ canonicalizeAutoMovieJson,
4
+ digestAutoMovieBytes,
5
+ } from "@automovie/engine";
6
+ import type {
7
+ IAutoMovieAdmitProductionTtsReceipt,
8
+ IAutoMovieDecodedProductionAudioAsset,
9
+ IAutoMovieProductionPhonemeChunk,
10
+ IAutoMovieProductionTtsReceipt,
11
+ } from "@automovie/interface";
12
+
13
+ import { decodeProductionAudioAsset } from "./decodeProductionAudioAsset";
14
+ import { resampleProductionAudio } from "./resampleProductionAudio";
15
+
16
+ /**
17
+ * Admit one generated line's receipt against its line and its bytes, and decode
18
+ * the line at the requested rate.
19
+ *
20
+ * The receipt is parsed as UTF-8 JSON and must be a version 7 receipt whose
21
+ * required fields carry their declared types. It is refused, naming the field,
22
+ * when its `line` or `text` differs from the line; when the WAVE file is not
23
+ * mono 32-bit IEEE float at `sourceSampleRate`; when `sourceSamples` differs
24
+ * from the file's sample count; when `pcmDigest` differs from the SHA-256 of
25
+ * the file's samples as little-endian Float32 bytes; when a phoneme chunk is
26
+ * empty, leaves `[0, sourceSamples]`, or overlaps or precedes the previous
27
+ * chunk; and when `cacheKey` differs from the digest recomputed from `text`,
28
+ * `model`, `modelRevision`, `conditioning` and `inferenceArguments`. Refusals
29
+ * throw `Dialogue receipt "<path>" [<field>] <message>`; WAVE container
30
+ * refusals keep the decoder's own form.
31
+ *
32
+ * Ingest owns this admission because it reads external media bytes, and engine,
33
+ * which ingest depends on, cannot call it.
34
+ *
35
+ * @param props The line, its WAVE and receipt bytes with their paths, and the
36
+ * output rate.
37
+ * @returns The admitted receipt and the line's samples at `props.sampleRate`.
38
+ */
39
+ export function admitProductionTtsReceipt(
40
+ props: IAutoMovieAdmitProductionTtsReceipt.IProps,
41
+ ): IAutoMovieAdmitProductionTtsReceipt.IResult {
42
+ const fail: (field: string, message: string) => never = (
43
+ field: string,
44
+ message: string,
45
+ ): never => {
46
+ throw new Error(
47
+ `Dialogue receipt "${props.receiptPath}" [${field}] ${message}`,
48
+ );
49
+ };
50
+ const receipt: IAutoMovieProductionTtsReceipt = parseReceipt(
51
+ props.receipt,
52
+ fail,
53
+ );
54
+ if (receipt.line !== props.line.id)
55
+ fail(
56
+ "line",
57
+ `belongs to line "${receipt.line}", not to line "${props.line.id}".`,
58
+ );
59
+ if (receipt.text !== props.line.text)
60
+ fail(
61
+ "text",
62
+ `records the text ${JSON.stringify(receipt.text)}, but line "${props.line.id}" says ${JSON.stringify(props.line.text)}.`,
63
+ );
64
+
65
+ // The file is decoded at its own rate, so the samples read are its bytes.
66
+ const native: IAutoMovieDecodedProductionAudioAsset =
67
+ decodeProductionAudioAsset({
68
+ path: props.pcmPath,
69
+ bytes: props.pcm,
70
+ sampleRate: receipt.sourceSampleRate,
71
+ });
72
+ if (
73
+ native.sourceFormat.encoding !== "float-f32le" ||
74
+ native.sourceChannels !== 1 ||
75
+ native.sourceSampleRate !== receipt.sourceSampleRate
76
+ )
77
+ fail(
78
+ "sourceSampleRate",
79
+ `requires "${props.pcmPath}" to be mono 32-bit float at ${receipt.sourceSampleRate} Hz, but it is ${native.sourceChannels}-channel ${native.sourceFormat.encoding} at ${native.sourceSampleRate} Hz.`,
80
+ );
81
+ if (native.sourceFrames !== receipt.sourceSamples)
82
+ fail(
83
+ "sourceSamples",
84
+ `records ${receipt.sourceSamples} samples, but "${props.pcmPath}" holds ${native.sourceFrames}.`,
85
+ );
86
+ const bytes: Uint8Array = new Uint8Array(native.samples.length * 4);
87
+ const view: DataView = new DataView(bytes.buffer);
88
+ native.samples.forEach((sample: number, index: number): void =>
89
+ view.setFloat32(index * 4, sample, true),
90
+ );
91
+ const digest: string = digestAutoMovieBytes(bytes);
92
+ if (digest !== receipt.pcmDigest)
93
+ fail(
94
+ "pcmDigest",
95
+ `records ${receipt.pcmDigest}, but the samples of "${props.pcmPath}" digest to ${digest}.`,
96
+ );
97
+
98
+ let previousEnd: number = 0;
99
+ receipt.phonemeChunks?.forEach(
100
+ (chunk: IAutoMovieProductionPhonemeChunk, index: number): void => {
101
+ if (
102
+ Number.isSafeInteger(chunk.startSample) === false ||
103
+ Number.isSafeInteger(chunk.endSample) === false ||
104
+ chunk.startSample < previousEnd ||
105
+ chunk.endSample <= chunk.startSample ||
106
+ chunk.endSample > receipt.sourceSamples ||
107
+ chunk.phonemes.trim().length === 0
108
+ )
109
+ fail(
110
+ `phonemeChunks[${index}]`,
111
+ `spans samples ${chunk.startSample} to ${chunk.endSample} with phonemes ${JSON.stringify(chunk.phonemes)}; a chunk carries phonemes over a nonempty interval inside [0, ${receipt.sourceSamples}] that starts at or after the previous chunk's end ${previousEnd}.`,
112
+ );
113
+ previousEnd = chunk.endSample;
114
+ },
115
+ );
116
+
117
+ const cacheKey: string = autoMovieRenderDigest(
118
+ canonicalizeAutoMovieJson([
119
+ receipt.text,
120
+ receipt.model,
121
+ receipt.modelRevision,
122
+ receipt.conditioning,
123
+ receipt.inferenceArguments,
124
+ ]),
125
+ );
126
+ if (cacheKey !== receipt.cacheKey)
127
+ fail(
128
+ "cacheKey",
129
+ `records ${receipt.cacheKey}, but its request recomputes to ${cacheKey}.`,
130
+ );
131
+
132
+ const resampling: boolean = receipt.sourceSampleRate !== props.sampleRate;
133
+ return {
134
+ receipt,
135
+ audio: {
136
+ ...native,
137
+ processing: {
138
+ ...native.processing,
139
+ kind: resampling ? "resample" : "copy",
140
+ outputSampleRate: props.sampleRate,
141
+ },
142
+ samples: resampling
143
+ ? resampleProductionAudio(
144
+ native.samples,
145
+ receipt.sourceSampleRate,
146
+ props.sampleRate,
147
+ )
148
+ : native.samples,
149
+ },
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Parse the receipt bytes and check the type of every field admission reads or
155
+ * the receipt requires.
156
+ */
157
+ const parseReceipt: (
158
+ bytes: Uint8Array,
159
+ fail: (field: string, message: string) => never,
160
+ ) => IAutoMovieProductionTtsReceipt = (
161
+ bytes: Uint8Array,
162
+ fail: (field: string, message: string) => never,
163
+ ): IAutoMovieProductionTtsReceipt => {
164
+ let value: unknown;
165
+ try {
166
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
167
+ } catch (cause) {
168
+ return fail(
169
+ "json",
170
+ `is not UTF-8 JSON: ${cause instanceof Error ? cause.message : String(cause)}`,
171
+ );
172
+ }
173
+ if (typeof value !== "object" || value === null || Array.isArray(value))
174
+ return fail("json", "is not a JSON object.");
175
+ const record: Record<string, unknown> = value as Record<string, unknown>;
176
+ if (record.version !== 7)
177
+ fail(
178
+ "version",
179
+ `is version ${JSON.stringify(record.version)}; only version 7 receipts are admitted, and an older receipt lacks the text and inference arguments its line needs, so record the line again.`,
180
+ );
181
+ for (const field of [
182
+ "line",
183
+ "text",
184
+ "cacheKey",
185
+ "model",
186
+ "modelRevision",
187
+ "generatedAt",
188
+ "pcmDigest",
189
+ ])
190
+ if (typeof record[field] !== "string" || record[field] === "")
191
+ fail(field, "must be a nonempty string.");
192
+ for (const field of ["sourceSampleRate", "sourceSamples"]) {
193
+ const count: unknown = record[field];
194
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count <= 0)
195
+ fail(field, "must be a positive safe integer.");
196
+ }
197
+ const conditioning: unknown = record.conditioning;
198
+ const mode: unknown =
199
+ typeof conditioning === "object" && conditioning !== null
200
+ ? (conditioning as Record<string, unknown>).mode
201
+ : undefined;
202
+ const voice: unknown =
203
+ mode === "voice"
204
+ ? (conditioning as Record<string, unknown>).voice
205
+ : mode === "reference-audio"
206
+ ? (conditioning as Record<string, unknown>).referenceDigest
207
+ : undefined;
208
+ if (typeof voice !== "string" || voice === "")
209
+ fail(
210
+ "conditioning",
211
+ 'must be { mode: "voice", voice } or { mode: "reference-audio", referenceDigest } with a nonempty string.',
212
+ );
213
+ const argumentsRecord: unknown = record.inferenceArguments;
214
+ if (
215
+ typeof argumentsRecord !== "object" ||
216
+ argumentsRecord === null ||
217
+ Array.isArray(argumentsRecord) ||
218
+ Object.values(argumentsRecord).some(
219
+ (argument: unknown): boolean =>
220
+ typeof argument !== "string" &&
221
+ typeof argument !== "boolean" &&
222
+ (typeof argument !== "number" || Number.isFinite(argument) === false),
223
+ )
224
+ )
225
+ fail(
226
+ "inferenceArguments",
227
+ "must be an object of string, finite number and boolean values.",
228
+ );
229
+ if (
230
+ typeof record.generatorProvenance !== "object" ||
231
+ record.generatorProvenance === null
232
+ )
233
+ fail("generatorProvenance", "must be an object.");
234
+ if (Array.isArray(record.runtimeAssets) === false)
235
+ fail("runtimeAssets", "must be an array.");
236
+ if (
237
+ record.phonemeChunks !== undefined &&
238
+ (Array.isArray(record.phonemeChunks) === false ||
239
+ record.phonemeChunks.some(
240
+ (chunk: unknown): boolean =>
241
+ typeof chunk !== "object" ||
242
+ chunk === null ||
243
+ typeof (chunk as Record<string, unknown>).phonemes !== "string",
244
+ ))
245
+ )
246
+ fail(
247
+ "phonemeChunks",
248
+ "must be an array of { phonemes, startSample, endSample } records.",
249
+ );
250
+ const aligner: unknown = record.aligner;
251
+ if (
252
+ aligner !== undefined &&
253
+ (typeof aligner !== "object" ||
254
+ aligner === null ||
255
+ typeof (aligner as Record<string, unknown>).model !== "string" ||
256
+ typeof (aligner as Record<string, unknown>).revision !== "string")
257
+ )
258
+ fail("aligner", "must be { model, revision } with string values.");
259
+
260
+ // Every field read above has its declared type, so the record is the receipt.
261
+ return record as unknown as IAutoMovieProductionTtsReceipt;
262
+ };
@@ -1,28 +1,58 @@
1
1
  import type { IAutoMovieDecodedProductionAudioAsset } from "@automovie/interface";
2
2
 
3
+ import { resampleProductionAudio } from "./resampleProductionAudio";
4
+
3
5
  /**
4
- * Decode one complete supported RIFF/WAVE file into finite mono samples at a requested rate.
6
+ * Decode one complete supported RIFF/WAVE file into finite mono samples at a
7
+ * requested rate.
5
8
  *
6
- * The parser walks the RIFF chunks by id, requires the declared RIFF extent, `nBlockAlign`, and `nAvgBytesPerSec` to agree with the format fields, and refuses a duplicate `fmt ` or `data` chunk, an odd chunk without its pad byte, and terminal bytes too short for a chunk header. An extensible header follows the Microsoft WAVEFORMATEXTENSIBLE contract (https://learn.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible): "The cbSize member must be at least 22", `wValidBitsPerSample` "can be any value not exceeding the container size", "the channels specified in dwChannelMask must be present in the prescribed order (from least significant bit up)" with SPEAKER_FRONT_LEFT `0x1`, SPEAKER_FRONT_RIGHT `0x2`, and SPEAKER_FRONT_CENTER `0x4`, and "the number of bits set in dwChannelMask should be the same as the number of channels". The SubFormat is admitted only when every byte after its leading 16-bit tag equals the `xxxxxxxx-0000-0010-8000-00aa00389b71` template that Ksmedia.h's `IS_VALID_WAVEFORMATEX_GUID` compares (https://learn.microsoft.com/en-us/windows-hardware/drivers/audio/converting-between-format-tags-and-subformat-guids), so a vendor GUID whose low word happens to read as PCM is not decoded as PCM.
9
+ * The parser walks the RIFF chunks by id, requires the declared RIFF extent,
10
+ * `nBlockAlign`, and `nAvgBytesPerSec` to agree with the format fields, and
11
+ * refuses a duplicate `fmt ` or `data` chunk, an odd chunk without its pad
12
+ * byte, and terminal bytes too short for a chunk header. An extensible header
13
+ * follows the Microsoft WAVEFORMATEXTENSIBLE contract
14
+ * (https://learn.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible):
15
+ * "The cbSize member must be at least 22", `wValidBitsPerSample` "can be any
16
+ * value not exceeding the container size", "the channels specified in
17
+ * dwChannelMask must be present in the prescribed order (from least significant
18
+ * bit up)" with SPEAKER_FRONT_LEFT `0x1`, SPEAKER_FRONT_RIGHT `0x2`, and
19
+ * SPEAKER_FRONT_CENTER `0x4`, and "the number of bits set in dwChannelMask
20
+ * should be the same as the number of channels". The SubFormat is admitted only
21
+ * when every byte after its leading 16-bit tag equals the
22
+ * `xxxxxxxx-0000-0010-8000-00aa00389b71` template that Ksmedia.h's
23
+ * `IS_VALID_WAVEFORMATEX_GUID` compares
24
+ * (https://learn.microsoft.com/en-us/windows-hardware/drivers/audio/converting-between-format-tags-and-subformat-guids),
25
+ * so a vendor GUID whose low word happens to read as PCM is not decoded as
26
+ * PCM.
7
27
  *
8
- * The supported subset is deliberately narrow: 16-bit PCM in a 16-bit container, 32-bit IEEE float in a 32-bit container, mono front-center, and stereo front-left/front-right. A legal declaration outside it, such as 20 valid bits in a 24-bit container or a front-left/front-center pair, is refused as unsupported by field rather than misread as the nearest supported layout. Every decoded sample is checked finite before the mono fold and before any resampling, so a NaN or infinity in one channel refuses the whole asset at its frame and channel instead of averaging into a plausible number.
28
+ * The supported subset is deliberately narrow: 16-bit PCM in a 16-bit
29
+ * container, 32-bit IEEE float in a 32-bit container, mono front-center, and
30
+ * stereo front-left/front-right. A legal declaration outside it, such as 20
31
+ * valid bits in a 24-bit container or a front-left/front-center pair, is
32
+ * refused as unsupported by field rather than misread as the nearest supported
33
+ * layout. Every decoded sample is checked finite before the mono fold and
34
+ * before any resampling, so a NaN or infinity in one channel refuses the whole
35
+ * asset at its frame and channel instead of averaging into a plausible number.
9
36
  *
10
- * PCM codes scale by 1/32768, so -32768 reads as exactly -1 and 32767 just under 1. Stereo folds to the mean of its two channels. A source at another rate is resampled by linear interpolation between neighboring source samples, holding the last sample past the end, to `round(frames * rate / sourceRate)` samples, which may round to zero for a short source and a low target rate. No low-pass filter runs first, so downsampling a source with content above the target Nyquist frequency aliases it.
37
+ * PCM codes scale by 1/32768, so -32768 reads as exactly -1 and 32767 just
38
+ * under 1. Stereo folds to the mean of its two channels. A source at another
39
+ * rate is converted by band-limited windowed-sinc interpolation with fixed
40
+ * coefficients (`resampleProductionAudio`, after Smith and Gossett, ICASSP
41
+ * 1984) to `round(frames * rate / sourceRate)` samples, which may round to zero
42
+ * for a short source and a low target rate; its low-pass leaves no images when
43
+ * upsampling and folds no alias when downsampling.
11
44
  *
12
- * Field admission refusals throw `Audio asset "<path>" [<reason>] <message>`, where the reason names the field, such as `riff-size`, `block-align`, or `unsupported-wave-layout`. Buffer size follows source frames and the requested rate ratio; this function imposes no product memory budget, so platform allocation errors may propagate outside that refusal format.
45
+ * Field admission refusals throw `Audio asset "<path>" [<reason>] <message>`,
46
+ * where the reason names the field, such as `riff-size`, `block-align`, or
47
+ * `unsupported-wave-layout`. Buffer size follows source frames and the
48
+ * requested rate ratio; this function imposes no product memory budget, so
49
+ * platform allocation errors may propagate outside that refusal format.
13
50
  *
14
51
  * @param props.path Asset path, used only in refusal messages.
15
52
  * @param props.bytes Complete file bytes; they are only read.
16
- * @param props.sampleRate Output rate in samples per second; a positive safe integer.
53
+ * @param props.sampleRate Output rate in samples per second; a positive safe
54
+ * integer.
17
55
  * @returns The source facts as declared and new mono samples the caller owns.
18
- *
19
- * @evidence contracts/development/implementation.md#principled-implementation Chunks are found by id in RIFF order with the even-byte pad rule, the format fields are checked against WAVEFORMATEXTENSIBLE's own consistency rules and the KSDATAFORMAT GUID template, samples scale by 1/32768 or read as IEEE floats, and resampling is two-tap linear interpolation; that interpolation has no anti-alias filter, which the documentation states as the remaining limitation when a source is downsampled.
20
- * @evidence contracts/development/implementation.md#clear-and-simple-structure One linear pass validates the container, a second folds frames to mono, and a third resamples only when the rates differ; private refusal, chunk and hex helpers keep WAVE parsing local, while production speech probes consume the public decoder's format facts and mono samples.
21
- * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No file, path or rate is special-cased: every unsupported declaration throws with a field-named reason instead of decoding as the nearest supported layout, and the only constants are the WAVE format tags, speaker masks and GUID tail the Microsoft contract defines.
22
- * @evidence contracts/development/common.md#meaningful-documentation The documentation cites the WAVEFORMATEXTENSIBLE rules it enforces, lists the supported subset, gives the PCM scale, stereo fold, resampled length and aliasing limitation, and states the refusal message shape and parameter units.
23
- * @evidence contracts/development/implementation.md#efficient-algorithms Time follows RIFF chunk headers, source frames times channels and output samples; storage follows source and output frames, each encoded sample is read once through one DataView, and the mono buffer becomes the result when rates match.
24
- * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work The decoder is a pure function of one call's bytes and rate and coordinates no work across requests; any caching of decoded assets would belong to its caller.
25
- * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The call owns source-frame mono storage and, on resampling, rate-ratio-sized output storage; no product memory budget bounds a requested allocation. Temporary buffers become collectable on return/throw, the returned buffer transfers to its caller, and no raw bytes, handles or tasks are retained.
26
56
  */
27
57
  export const decodeProductionAudioAsset: (
28
58
  props: IAutoMovieDecodedProductionAudioAsset.IProps,
@@ -289,7 +319,7 @@ export const decodeProductionAudioAsset: (
289
319
  }
290
320
  const resampling: boolean = sourceSampleRate !== props.sampleRate;
291
321
  const samples: Float32Array = resampling
292
- ? resampleMono(mono, sourceSampleRate, props.sampleRate)
322
+ ? resampleProductionAudio(mono, sourceSampleRate, props.sampleRate)
293
323
  : mono;
294
324
  return {
295
325
  sourceSampleRate,
@@ -357,7 +387,11 @@ const SUBFORMAT_TAIL: Uint8Array = Uint8Array.from([
357
387
  0x71,
358
388
  ]);
359
389
 
360
- /** Throw the decoder's refusal. The explicit function type on the constant is what lets TypeScript narrow after a statement call, so callers need no non-null assertion. */
390
+ /**
391
+ * Throw the decoder's refusal. The explicit function type on the constant is
392
+ * what lets TypeScript narrow after a statement call, so callers need no
393
+ * non-null assertion.
394
+ */
361
395
  const fail: (asset: string, reason: string, message: string) => never = (
362
396
  asset: string,
363
397
  reason: string,
@@ -366,28 +400,6 @@ const fail: (asset: string, reason: string, message: string) => never = (
366
400
  throw new Error(`Audio asset "${asset}" [${reason}] ${message}`);
367
401
  };
368
402
 
369
- const resampleMono: (
370
- source: Float32Array,
371
- from: number,
372
- to: number,
373
- ) => Float32Array = (
374
- source: Float32Array,
375
- from: number,
376
- to: number,
377
- ): Float32Array => {
378
- const length: number = Math.round((source.length * to) / from);
379
- const output: Float32Array = new Float32Array(length);
380
- const step: number = from / to;
381
- for (let index: number = 0; index < length; ++index) {
382
- const position: number = index * step;
383
- const left: number = Math.floor(position);
384
- const right: number = Math.min(source.length - 1, left + 1);
385
- const weight: number = position - left;
386
- output[index] = source[left]! * (1 - weight) + source[right]! * weight;
387
- }
388
- return output;
389
- };
390
-
391
403
  const asciiTag: (bytes: Uint8Array, offset: number) => string = (
392
404
  bytes: Uint8Array,
393
405
  offset: number,
@@ -403,7 +415,10 @@ const asciiTag: (bytes: Uint8Array, offset: number) => string = (
403
415
  const leadingHex: (bytes: Uint8Array) => string = (bytes: Uint8Array): string =>
404
416
  `0x${hexBytes(bytes, 0, 4)}`;
405
417
 
406
- /** Canonical GUID text: the first three fields are little-endian in the file, the last two are byte strings. */
418
+ /**
419
+ * Canonical GUID text: the first three fields are little-endian in the file,
420
+ * the last two are byte strings.
421
+ */
407
422
  const waveGuid: (bytes: Uint8Array) => string = (bytes: Uint8Array): string =>
408
423
  `${hexBytes(bytes, 3, -1)}-${hexBytes(bytes, 5, 3)}-${hexBytes(bytes, 7, 5)}-${hexBytes(bytes, 8, 10)}-${hexBytes(bytes, 10, 16)}`;
409
424
 
@@ -1 +1,2 @@
1
+ export * from "./admitProductionTtsReceipt";
1
2
  export * from "./decodeProductionAudioAsset";
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Convert mono samples from one rate to another by band-limited interpolation
3
+ * (Smith and Gossett, "A flexible sampling-rate conversion method", ICASSP
4
+ * 1984).
5
+ *
6
+ * Output sample `i` sits at input position `t = i × from / to` and is the sum
7
+ * of the input samples within `ZERO_CROSSINGS` zero crossings of a
8
+ * windowed-sinc low-pass centred on `t`. The low-pass cuts at `ROLLOFF` of the
9
+ * lower of the two Nyquist frequencies, so upsampling leaves no spectral images
10
+ * and downsampling folds no content back below the new Nyquist frequency. The
11
+ * kernel is read from one fixed table by linear interpolation between its
12
+ * entries, so equal inputs give equal samples on every platform. Samples before
13
+ * the first and after the last input sample are zero. The output holds
14
+ * `round(source.length × to / from)` samples, which may be zero for a short
15
+ * source and a low target rate.
16
+ *
17
+ * @param source Mono input samples at `from` samples per second; only read.
18
+ * @param from Input rate, a positive safe integer.
19
+ * @param to Output rate, a positive safe integer.
20
+ * @returns New mono samples at `to` samples per second, rounded to Float32.
21
+ */
22
+ export function resampleProductionAudio(
23
+ source: Float32Array,
24
+ from: number,
25
+ to: number,
26
+ ): Float32Array {
27
+ const length: number = Math.round((source.length * to) / from);
28
+ const output: Float32Array = new Float32Array(length);
29
+
30
+ // The kernel's argument is in units of the low-pass's zero-crossing spacing.
31
+ // Downsampling stretches that spacing over more input samples and scales the
32
+ // kernel down by the same factor, so its DC gain stays one at either rate.
33
+ const scale: number = Math.min(1, to / from) * ROLLOFF;
34
+ const reach: number = Math.ceil(ZERO_CROSSINGS / scale);
35
+ for (let index: number = 0; index < length; ++index) {
36
+ const position: number = (index * from) / to;
37
+ const centre: number = Math.floor(position);
38
+ let sum: number = 0;
39
+ for (
40
+ let input: number = Math.max(0, centre - reach);
41
+ input <= Math.min(source.length - 1, centre + reach);
42
+ ++input
43
+ ) {
44
+ const distance: number = Math.abs(position - input) * scale;
45
+ if (distance >= ZERO_CROSSINGS) continue;
46
+ const at: number = distance * TABLE_DENSITY;
47
+ const entry: number = Math.floor(at);
48
+ const weight: number =
49
+ KERNEL[entry]! + (at - entry) * (KERNEL[entry + 1]! - KERNEL[entry]!);
50
+ sum += source[input]! * weight;
51
+ }
52
+ output[index] = sum * scale;
53
+ }
54
+ return output;
55
+ }
56
+
57
+ /**
58
+ * Zero crossings of the sinc on each side of the centre. With `ROLLOFF` and the
59
+ * Kaiser window below, the filter spans `2 × 32 / 0.9 ≈ 71` input samples when
60
+ * upsampling, which gives a transition band of about 0.44 rad per input sample
61
+ * by Kaiser's design formula `Δω = (A − 8) / (2.285 M)` (Oppenheim and Schafer,
62
+ * Discrete-Time Signal Processing, 3rd ed., §7.6): 1.7 kHz at a 24 kHz source.
63
+ */
64
+ const ZERO_CROSSINGS: number = 32;
65
+
66
+ /**
67
+ * Cutoff as a fraction of the lower Nyquist frequency. At 0.9 the transition
68
+ * band of a 24 kHz source runs from about 9.95 to 11.65 kHz, so speech up to 10
69
+ * kHz passes and the first image of any passband tone lies in the stopband.
70
+ */
71
+ const ROLLOFF: number = 0.9;
72
+
73
+ /** Kaiser window stopband attenuation in dB, the design target `A`. */
74
+ const STOPBAND_DB: number = 80;
75
+
76
+ /**
77
+ * Kernel table entries per zero crossing; Smith and Gossett interpolate
78
+ * linearly between them.
79
+ */
80
+ const TABLE_DENSITY: number = 512;
81
+
82
+ /** Modified Bessel function of the first kind, order zero, by its power series. */
83
+ const besselI0: (x: number) => number = (x: number): number => {
84
+ let sum: number = 1;
85
+ let term: number = 1;
86
+ for (let k: number = 1; term > sum * 1e-21; ++k) {
87
+ term *= (x / (2 * k)) * (x / (2 * k));
88
+ sum += term;
89
+ }
90
+ return sum;
91
+ };
92
+
93
+ /**
94
+ * The windowed sinc `sinc(u) × I0(β √(1 − (u/Z)²)) / I0(β)` at `u = i /
95
+ * TABLE_DENSITY`, for `u` from 0 to `ZERO_CROSSINGS`, followed by one zero so
96
+ * the last interpolation step ends at the window's edge. `β = 0.1102 (A − 8.7)`
97
+ * is Kaiser's shape for an attenuation `A` above 50 dB (Oppenheim and Schafer,
98
+ * §7.6.1).
99
+ */
100
+ const KERNEL: Float64Array = ((): Float64Array => {
101
+ const beta: number = 0.1102 * (STOPBAND_DB - 8.7);
102
+ const entries: number = ZERO_CROSSINGS * TABLE_DENSITY;
103
+ const table: Float64Array = new Float64Array(entries + 2);
104
+ const norm: number = besselI0(beta);
105
+ for (let index: number = 0; index <= entries; ++index) {
106
+ const u: number = index / TABLE_DENSITY;
107
+ const sinc: number = u === 0 ? 1 : Math.sin(Math.PI * u) / (Math.PI * u);
108
+ const ratio: number = u / ZERO_CROSSINGS;
109
+ table[index] =
110
+ (sinc * besselI0(beta * Math.sqrt(Math.max(0, 1 - ratio * ratio)))) /
111
+ norm;
112
+ }
113
+ return table;
114
+ })();
@@ -4,24 +4,16 @@ import type {
4
4
  } from "@automovie/interface";
5
5
 
6
6
  /**
7
- * Decode one raw P6 RGB8 image under an explicitly supplied transfer convention.
8
- * This codec processes bytes without importing glTF SDK objects. The package's
9
- * main entry also exposes SDK-backed operations with their own declaration dependencies.
10
- * The initial subset admits maxval 255, comments before numeric header tokens
11
- * and exactly one whitespace byte between maxval and raster. It rejects P3,
12
- * 16-bit samples, image sequences and trailing bytes. A raster byte that happens
13
- * to be whitespace or '#' is pixel data and is never skipped.
14
- * Netpbm normally specifies BT.709; sRGB is its documented common variation.
15
- * The decoder preserves samples without performing colour conversion.
16
- * See https://netpbm.sourceforge.net/doc/ppm.html.
17
- *
18
- * @evidence contracts/development/implementation.md#principled-implementation The documented P6 header and exact RGB raster length determine decoding; explicit transfer metadata avoids relabeling standard BT.709 samples as sRGB. Pixel/header budgets are validated before the detached output allocation.
19
- * @evidence contracts/development/implementation.md#clear-and-simple-structure This renderer-free byte codec performs only admission and RGB extraction; capture calibration, foreground observation and source publication remain with their owners.
20
- * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No header repair, ignored trailing image, post-header whitespace skipping, unsupported maxval rescaling or implicit colour conversion changes fixed bytes.
21
- * @evidence contracts/development/common.md#meaningful-documentation States the admitted P6 subset, comments, delimiter/raster distinction, detached ownership, transfer declaration, unsupported variants and budget refusal.
22
- * @evidence contracts/development/implementation.md#efficient-algorithms Parsing costs O(H) for admitted header bytes and one O(P) RGB copy for P pixels; maxHeaderBytes and maxPixels bound both populations before allocation.
23
- * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Each synchronous call decodes caller-supplied fixed bytes once and defines no cross-request cache.
24
- * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The caller owns one detached RGB8 result; borrowed source bytes and constant header scratch are released from the call without handles or global retention.
7
+ * Decode one raw P6 RGB8 image under an explicitly supplied transfer
8
+ * convention. This codec processes bytes without importing glTF SDK objects.
9
+ * The package's main entry also exposes SDK-backed operations with their own
10
+ * declaration dependencies. The initial subset admits maxval 255, comments
11
+ * before numeric header tokens and exactly one whitespace byte between maxval
12
+ * and raster. It rejects P3, 16-bit samples, image sequences and trailing
13
+ * bytes. A raster byte that happens to be whitespace or '#' is pixel data and
14
+ * is never skipped. Netpbm normally specifies BT.709; sRGB is its documented
15
+ * common variation. The decoder preserves samples without performing colour
16
+ * conversion. See https://netpbm.sourceforge.net/doc/ppm.html.
25
17
  */
26
18
  export function decodeAutoMoviePpmImage(
27
19
  bytes: Uint8Array,
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Bounds-checked big-endian reads over one font's bytes, as the Open Font
3
+ * Format stores every field (ISO/IEC 14496-22, section 4.2).
4
+ *
5
+ * Every read names the table it serves, so an offset or a length that leaves
6
+ * the bytes refuses with that table's name instead of reading past the buffer
7
+ * or returning `undefined`. The reader borrows the bytes and copies nothing.
8
+ */
9
+ export class TrueTypeByteReader {
10
+ /** The borrowed font bytes. */
11
+ private readonly bytes: Uint8Array;
12
+
13
+ /** Big-endian view over the borrowed bytes. */
14
+ private readonly view: DataView;
15
+
16
+ /** Borrow the font bytes for the life of one decode. */
17
+ public constructor(bytes: Uint8Array) {
18
+ this.bytes = bytes;
19
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
20
+ }
21
+
22
+ /**
23
+ * Refuse unless `[offset, offset + size)` lies inside the bytes.
24
+ *
25
+ * @throws {Error} The span leaves the bytes; the message names `what`.
26
+ */
27
+ public require(offset: number, size: number, what: string): void {
28
+ if (
29
+ !Number.isSafeInteger(offset) ||
30
+ !Number.isSafeInteger(size) ||
31
+ offset < 0 ||
32
+ size < 0 ||
33
+ offset + size > this.bytes.byteLength
34
+ )
35
+ throw new Error(
36
+ `TrueType ${what} at byte ${offset} with length ${size} lies outside the ${this.bytes.byteLength} font bytes`,
37
+ );
38
+ }
39
+
40
+ /** Unsigned 8-bit integer. */
41
+ public u8(offset: number, what: string): number {
42
+ this.require(offset, 1, what);
43
+ return this.view.getUint8(offset);
44
+ }
45
+
46
+ /** Signed 8-bit integer. */
47
+ public i8(offset: number, what: string): number {
48
+ this.require(offset, 1, what);
49
+ return this.view.getInt8(offset);
50
+ }
51
+
52
+ /** Unsigned 16-bit big-endian integer. */
53
+ public u16(offset: number, what: string): number {
54
+ this.require(offset, 2, what);
55
+ return this.view.getUint16(offset, false);
56
+ }
57
+
58
+ /** Signed 16-bit big-endian integer. */
59
+ public i16(offset: number, what: string): number {
60
+ this.require(offset, 2, what);
61
+ return this.view.getInt16(offset, false);
62
+ }
63
+
64
+ /** Unsigned 32-bit big-endian integer. */
65
+ public u32(offset: number, what: string): number {
66
+ this.require(offset, 4, what);
67
+ return this.view.getUint32(offset, false);
68
+ }
69
+
70
+ /** Four-byte tag read as ASCII, such as a table name or an `sfnt` version tag. */
71
+ public tag(offset: number, what: string): string {
72
+ this.require(offset, 4, what);
73
+ return String.fromCharCode(
74
+ this.view.getUint8(offset),
75
+ this.view.getUint8(offset + 1),
76
+ this.view.getUint8(offset + 2),
77
+ this.view.getUint8(offset + 3),
78
+ );
79
+ }
80
+ }