narrator-ts 0.1.0 → 0.1.1

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.
package/README.md CHANGED
@@ -78,6 +78,24 @@ fields. `npm run say` with no arguments prints them.
78
78
 
79
79
  Every tool under `tools/` takes `--help`.
80
80
 
81
+ ## AROS resource export
82
+
83
+ Create the versioned IFF resource consumed by AROS `translator.library`,
84
+ `narrator.device`, and `speech.device`:
85
+
86
+ ```sh
87
+ npm run export:aros -- -o speech.iff
88
+ npm run export:aros -- -o speech.iff \
89
+ --translator data/translator-33.2.json \
90
+ --voice data/narrator-33.2.json
91
+ npm run export:aros -- -o speech-resource.c --format c
92
+ ```
93
+
94
+ The first command uses the redistributable reference tables. The second uses
95
+ locally extracted authentic tables; the resulting file has the same legal
96
+ status as those inputs and should not be redistributed.
97
+ The C form contains the identical IFF payload as a byte array for ROM builds.
98
+
81
99
  ## Status
82
100
 
83
101
  | | |
@@ -0,0 +1,39 @@
1
+ /**
2
+ * AROS Narrator resource interchange.
3
+ *
4
+ * The file is an ordinary big-endian IFF FORM. `LTRS` holds the compact
5
+ * letter-to-sound table and `NVOI` the subset of a voice consumed by AROS's
6
+ * bounded narrator engine. Unknown chunks can be skipped by older readers.
7
+ */
8
+ import type { VoiceData } from '../narrator/voice.js';
9
+ import type { TranslatorTables } from '../translator/types.js';
10
+ export declare const AROS_RESOURCE_FORM = "NARR";
11
+ export declare const AROS_RESOURCE_VERSION = 1;
12
+ declare const VOICE_COLUMNS: readonly ["f1", "f2", "f3", "a1", "a2", "a3", "voicing", "mouth"];
13
+ declare const ALT_VOICE_COLUMNS: readonly ["f1", "f2", "f3"];
14
+ export interface ArosResourceInput {
15
+ translator?: TranslatorTables;
16
+ voice?: VoiceData;
17
+ }
18
+ export interface ArosVoiceTables {
19
+ names: string[];
20
+ attrs: number[];
21
+ params: Record<(typeof VOICE_COLUMNS)[number], number[]>;
22
+ paramsAlt: Record<(typeof ALT_VOICE_COLUMNS)[number], number[]>;
23
+ stressed: number[];
24
+ unstressed: number[];
25
+ fricatives: number[][];
26
+ }
27
+ export interface DecodedArosResource {
28
+ version: number;
29
+ metadata: Record<string, unknown>;
30
+ translator?: TranslatorTables;
31
+ voice?: ArosVoiceTables;
32
+ }
33
+ /** Encode free or extracted tables as the AROS deployment resource. */
34
+ export declare function encodeArosResource(input: ArosResourceInput): Uint8Array;
35
+ /** Emit the same IFF bytes as a C array for ROM or built-in resource use. */
36
+ export declare function emitArosCResource(input: ArosResourceInput, symbol?: string): string;
37
+ /** Decode and validate an AROS resource, primarily for tools and tests. */
38
+ export declare function decodeArosResource(bytes: Uint8Array): DecodedArosResource;
39
+ export {};
@@ -0,0 +1,282 @@
1
+ /**
2
+ * AROS Narrator resource interchange.
3
+ *
4
+ * The file is an ordinary big-endian IFF FORM. `LTRS` holds the compact
5
+ * letter-to-sound table and `NVOI` the subset of a voice consumed by AROS's
6
+ * bounded narrator engine. Unknown chunks can be skipped by older readers.
7
+ */
8
+ export const AROS_RESOURCE_FORM = 'NARR';
9
+ export const AROS_RESOURCE_VERSION = 1;
10
+ const VOICE_COLUMNS = [
11
+ 'f1', 'f2', 'f3', 'a1', 'a2', 'a3', 'voicing', 'mouth',
12
+ ];
13
+ const ALT_VOICE_COLUMNS = ['f1', 'f2', 'f3'];
14
+ class Writer {
15
+ bytes = [];
16
+ u8(value) {
17
+ if (!Number.isInteger(value) || value < 0 || value > 0xff)
18
+ throw new RangeError(`not a byte: ${value}`);
19
+ this.bytes.push(value);
20
+ }
21
+ u16(value) {
22
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff)
23
+ throw new RangeError(`not a u16: ${value}`);
24
+ this.bytes.push(value >>> 8, value & 0xff);
25
+ }
26
+ u32(value) {
27
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff)
28
+ throw new RangeError(`not a u32: ${value}`);
29
+ this.bytes.push((value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff);
30
+ }
31
+ raw(values) {
32
+ for (let i = 0; i < values.length; i++)
33
+ this.u8(values[i]);
34
+ }
35
+ id(value) {
36
+ if (value.length !== 4)
37
+ throw new RangeError(`IFF ID must have four characters: ${value}`);
38
+ for (const c of value)
39
+ this.u8(c.charCodeAt(0));
40
+ }
41
+ latin8(value) {
42
+ if (value.length > 0xff)
43
+ throw new RangeError('string is too long');
44
+ this.u8(value.length);
45
+ for (const c of value) {
46
+ const code = c.charCodeAt(0);
47
+ if (code > 0xff)
48
+ throw new RangeError(`not Latin-1: ${JSON.stringify(c)}`);
49
+ this.u8(code);
50
+ }
51
+ }
52
+ finish() { return Uint8Array.from(this.bytes); }
53
+ }
54
+ class Reader {
55
+ bytes;
56
+ at = 0;
57
+ constructor(bytes) {
58
+ this.bytes = bytes;
59
+ }
60
+ need(count) {
61
+ if (this.at + count > this.bytes.length)
62
+ throw new RangeError('truncated AROS speech resource');
63
+ }
64
+ u8() { this.need(1); return this.bytes[this.at++]; }
65
+ u16() { return (this.u8() << 8) | this.u8(); }
66
+ u32() { return ((this.u8() * 0x1000000) + (this.u8() << 16) + (this.u8() << 8) + this.u8()) >>> 0; }
67
+ latin8() {
68
+ const n = this.u8();
69
+ this.need(n);
70
+ let out = '';
71
+ for (let i = 0; i < n; i++)
72
+ out += String.fromCharCode(this.u8());
73
+ return out;
74
+ }
75
+ vector(count) {
76
+ this.need(count);
77
+ const out = Array.from(this.bytes.subarray(this.at, this.at + count));
78
+ this.at += count;
79
+ return out;
80
+ }
81
+ done() { return this.at === this.bytes.length; }
82
+ }
83
+ function concat(parts) {
84
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
85
+ let at = 0;
86
+ for (const part of parts) {
87
+ out.set(part, at);
88
+ at += part.length;
89
+ }
90
+ return out;
91
+ }
92
+ function chunk(id, payload) {
93
+ const w = new Writer();
94
+ w.id(id);
95
+ w.u32(payload.length);
96
+ w.raw(payload);
97
+ if (payload.length & 1)
98
+ w.u8(0);
99
+ return w.finish();
100
+ }
101
+ function translatorChunk(data) {
102
+ if (data.classes.length !== 128 || data.buckets.length !== 28)
103
+ throw new RangeError('invalid translator table shape');
104
+ const w = new Writer();
105
+ w.u16(data.classes.length);
106
+ for (const value of data.classes)
107
+ w.u16(value);
108
+ w.latin8(data.wildcards);
109
+ w.u8(data.vowels.length);
110
+ for (const vowel of data.vowels)
111
+ w.latin8(vowel);
112
+ w.u16(data.buckets.length);
113
+ for (const bucket of data.buckets) {
114
+ w.u16(bucket.length);
115
+ for (const [left, match, right, out, term] of bucket) {
116
+ w.latin8(left);
117
+ w.latin8(match);
118
+ w.latin8(right);
119
+ w.latin8(out);
120
+ if (term.length !== 1)
121
+ throw new RangeError('translator rule terminator must be one byte');
122
+ w.u8(term.charCodeAt(0));
123
+ }
124
+ }
125
+ return w.finish();
126
+ }
127
+ function padded(values, count) {
128
+ const out = new Array(count).fill(0);
129
+ if (values)
130
+ for (let i = 0; i < Math.min(values.length, count); i++)
131
+ out[i] = values[i];
132
+ return out;
133
+ }
134
+ function voiceChunk(data) {
135
+ const count = data.names.length;
136
+ if (count === 0 || count > 0xffff)
137
+ throw new RangeError('invalid voice name count');
138
+ const w = new Writer();
139
+ w.u16(count);
140
+ for (const name of data.names) {
141
+ if (name.length > 2)
142
+ throw new RangeError(`phoneme name is longer than two bytes: ${name}`);
143
+ w.u8(name.charCodeAt(0) || 0);
144
+ w.u8(name.charCodeAt(1) || 0);
145
+ }
146
+ for (const value of padded(data.attrs, count))
147
+ w.u32(value);
148
+ for (const name of VOICE_COLUMNS.slice(0, 3))
149
+ w.raw(padded(data.params[name], count));
150
+ for (const name of ALT_VOICE_COLUMNS)
151
+ w.raw(padded(data.paramsAlt[name], count));
152
+ for (const name of VOICE_COLUMNS.slice(3))
153
+ w.raw(padded(data.params[name], count));
154
+ w.raw(padded(data.stressed, count));
155
+ w.raw(padded(data.unstressed, count));
156
+ const fricativeLength = data.fricatives[0]?.length ?? 0;
157
+ w.u16(data.fricatives.length);
158
+ w.u16(fricativeLength);
159
+ for (const table of data.fricatives) {
160
+ if (table.length !== fricativeLength)
161
+ throw new RangeError('fricative tables have unequal lengths');
162
+ w.raw(table);
163
+ }
164
+ return w.finish();
165
+ }
166
+ /** Encode free or extracted tables as the AROS deployment resource. */
167
+ export function encodeArosResource(input) {
168
+ if (!input.translator && !input.voice)
169
+ throw new RangeError('resource contains no tables');
170
+ const version = new Writer();
171
+ version.u32(AROS_RESOURCE_VERSION);
172
+ const meta = new TextEncoder().encode(JSON.stringify({
173
+ format: 'AROS Narrator Resource',
174
+ translator: input.translator && { version: input.translator.version, source: input.translator.source },
175
+ voice: input.voice && { version: input.voice.version, source: input.voice.source },
176
+ }));
177
+ const chunks = [chunk('VERS', version.finish()), chunk('META', meta)];
178
+ if (input.translator)
179
+ chunks.push(chunk('LTRS', translatorChunk(input.translator)));
180
+ if (input.voice)
181
+ chunks.push(chunk('NVOI', voiceChunk(input.voice)));
182
+ const body = concat(chunks);
183
+ const head = new Writer();
184
+ head.id('FORM');
185
+ head.u32(body.length + 4);
186
+ head.id(AROS_RESOURCE_FORM);
187
+ return concat([head.finish(), body]);
188
+ }
189
+ /** Emit the same IFF bytes as a C array for ROM or built-in resource use. */
190
+ export function emitArosCResource(input, symbol = 'sc_speech_resource') {
191
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(symbol))
192
+ throw new RangeError(`invalid C symbol: ${symbol}`);
193
+ const bytes = encodeArosResource(input);
194
+ const rows = [];
195
+ for (let at = 0; at < bytes.length; at += 12) {
196
+ rows.push(` ${Array.from(bytes.subarray(at, at + 12), (b) => `0x${b.toString(16).padStart(2, '0')}`).join(', ')},`);
197
+ }
198
+ return [
199
+ '/* Generated by narrator-ts; do not edit. */',
200
+ '#include <stddef.h>',
201
+ '#include <stdint.h>',
202
+ '',
203
+ `const uint8_t ${symbol}[] = {`,
204
+ ...rows,
205
+ '};',
206
+ `const size_t ${symbol}_length = sizeof(${symbol});`,
207
+ '',
208
+ ].join('\n');
209
+ }
210
+ function chunksFrom(bytes) {
211
+ if (bytes.length < 12)
212
+ throw new RangeError('truncated IFF FORM');
213
+ const ascii = (at) => String.fromCharCode(...bytes.subarray(at, at + 4));
214
+ const u32 = (at) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(at);
215
+ if (ascii(0) !== 'FORM' || ascii(8) !== AROS_RESOURCE_FORM || u32(4) + 8 !== bytes.length)
216
+ throw new RangeError('not an AROS Narrator IFF resource');
217
+ const chunks = new Map();
218
+ for (let at = 12; at < bytes.length;) {
219
+ if (at + 8 > bytes.length)
220
+ throw new RangeError('truncated IFF chunk');
221
+ const id = ascii(at), size = u32(at + 4), start = at + 8, end = start + size;
222
+ if (end > bytes.length)
223
+ throw new RangeError('truncated IFF chunk payload');
224
+ chunks.set(id, bytes.subarray(start, end));
225
+ at = end + (size & 1);
226
+ }
227
+ return chunks;
228
+ }
229
+ function decodeTranslator(bytes) {
230
+ const r = new Reader(bytes);
231
+ const classes = Array.from({ length: r.u16() }, () => r.u16());
232
+ const wildcards = r.latin8();
233
+ const vowels = Array.from({ length: r.u8() }, () => r.latin8());
234
+ const buckets = [];
235
+ const bucketCount = r.u16();
236
+ for (let b = 0; b < bucketCount; b++) {
237
+ const rules = [];
238
+ const count = r.u16();
239
+ for (let i = 0; i < count; i++)
240
+ rules.push([r.latin8(), r.latin8(), r.latin8(), r.latin8(), String.fromCharCode(r.u8())]);
241
+ buckets.push(rules);
242
+ }
243
+ if (!r.done())
244
+ throw new RangeError('trailing translator data');
245
+ return { version: 'resource', source: 'IFF LTRS', classes, wildcards, vowels, buckets };
246
+ }
247
+ function decodeVoice(bytes) {
248
+ const r = new Reader(bytes), count = r.u16();
249
+ const names = Array.from({ length: count }, () => {
250
+ const a = r.u8(), b = r.u8();
251
+ return String.fromCharCode(a, b).replace(/\0+$/, '');
252
+ });
253
+ const attrs = Array.from({ length: count }, () => r.u32());
254
+ const params = {};
255
+ for (const name of VOICE_COLUMNS.slice(0, 3))
256
+ params[name] = r.vector(count);
257
+ const paramsAlt = {};
258
+ for (const name of ALT_VOICE_COLUMNS)
259
+ paramsAlt[name] = r.vector(count);
260
+ for (const name of VOICE_COLUMNS.slice(3))
261
+ params[name] = r.vector(count);
262
+ const stressed = r.vector(count), unstressed = r.vector(count);
263
+ const fricativeCount = r.u16(), fricativeLength = r.u16();
264
+ const fricatives = Array.from({ length: fricativeCount }, () => r.vector(fricativeLength));
265
+ if (!r.done())
266
+ throw new RangeError('trailing voice data');
267
+ return { names, attrs, params, paramsAlt, stressed, unstressed, fricatives };
268
+ }
269
+ /** Decode and validate an AROS resource, primarily for tools and tests. */
270
+ export function decodeArosResource(bytes) {
271
+ const chunks = chunksFrom(bytes);
272
+ const versionBytes = chunks.get('VERS');
273
+ if (!versionBytes || versionBytes.length !== 4)
274
+ throw new RangeError('missing resource version');
275
+ const version = new DataView(versionBytes.buffer, versionBytes.byteOffset, 4).getUint32(0);
276
+ if (version !== AROS_RESOURCE_VERSION)
277
+ throw new RangeError(`unsupported resource version ${version}`);
278
+ const metadata = JSON.parse(new TextDecoder().decode(chunks.get('META') ?? new Uint8Array()));
279
+ const translator = chunks.has('LTRS') ? decodeTranslator(chunks.get('LTRS')) : undefined;
280
+ const voice = chunks.has('NVOI') ? decodeVoice(chunks.get('NVOI')) : undefined;
281
+ return { version, metadata, translator, voice };
282
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narrator-ts",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "TypeScript reimplementation of the Amiga narrator.device and translator.library",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,9 +27,14 @@
27
27
  },
28
28
  "scripts": {
29
29
  "build": "tsc -p tsconfig.json",
30
+ "typecheck": "tsc --noEmit",
31
+ "release": "npm version",
32
+ "preversion": "npm run typecheck && npm test",
33
+ "postversion": "git push --follow-tags",
30
34
  "prepublishOnly": "npm run build && npm test",
31
35
  "test": "vitest run",
32
36
  "test:watch": "vitest",
37
+ "export:aros": "vite-node tools/export-aros.ts --",
33
38
  "say": "vite-node tools/say.ts --",
34
39
  "oracle:build": "bash tools/fetch-musashi.sh && make -C tools/oracle"
35
40
  },
@@ -49,6 +54,10 @@
49
54
  "types": "./dist/translator/index.d.ts",
50
55
  "default": "./dist/translator/index.js"
51
56
  },
57
+ "./aros-resource": {
58
+ "types": "./dist/aros-resource/index.d.ts",
59
+ "default": "./dist/aros-resource/index.js"
60
+ },
52
61
  "./reference/nrl-table.json": "./reference/nrl-table.json",
53
62
  "./reference/voice-free.json": "./reference/voice-free.json",
54
63
  "./package.json": "./package.json"