alpha2 0.4.4 → 0.4.6

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.
@@ -71,6 +71,15 @@ export declare function colorMetadataFromVideoColorSpace(space: VideoColorSpaceI
71
71
  * of a source whose color the project declares, are the engine's either way.
72
72
  */
73
73
  export type VideoConversion = "engine" | "browser";
74
+ /**
75
+ * A frame with no planar YUV format the engine reads: an opaque frame (a hardware frame the
76
+ * browser does not map to the CPU, `format` null) or an RGB one. Reading it again cannot help;
77
+ * decoding it again in software can.
78
+ */
79
+ export declare class NonPlanarVideoFrameError extends Error {
80
+ readonly format: VideoPixelFormat | null;
81
+ constructor(format: VideoPixelFormat | null);
82
+ }
74
83
  /** Whether `frame` has a planar format the engine converts (`copyPlanarYuvFrame` can copy it). */
75
84
  export declare function isPlanarVideoFrame(frame: VideoFrame): boolean;
76
85
  /** Whether a decoded frame's own color space says it is HDR. */
@@ -103,9 +112,10 @@ export declare class PlanarCopyPool {
103
112
  * CPU-readable planar format (a hardware frame the browser will not map) is
104
113
  * refused rather than converted by the browser.
105
114
  *
106
- * `frame` is closed whether the copy succeeds or not. Rejects when the frame
107
- * has no planar format the engine reads or no visible rectangle, or when
108
- * `copyTo` fails.
115
+ * `frame` is closed whether the copy succeeds or not. Rejects with
116
+ * {@link NonPlanarVideoFrameError} when the frame has no planar format the
117
+ * engine reads, and otherwise when it has no visible rectangle or `copyTo`
118
+ * fails.
109
119
  *
110
120
  * With `pool`, the copy's `data` is a buffer from it, which the caller gives back with
111
121
  * {@link PlanarCopyPool.release} after uploading; a failed copy gives it back itself.
@@ -114,7 +124,8 @@ export declare function copyPlanarYuvFrame(frame: VideoFrame, declared: ColorMet
114
124
  /**
115
125
  * {@link copyPlanarYuvFrame} without closing `frame`: the caller owns it whether the copy succeeds
116
126
  * or not, so a frame whose planes the browser could not read back can be read again. Rejects as
117
- * {@link copyPlanarYuvFrame} does; with `pool`, a failed copy gives its buffer back.
127
+ * {@link copyPlanarYuvFrame} does, with {@link NonPlanarVideoFrameError} for a frame no read can
128
+ * copy; with `pool`, a failed copy gives its buffer back.
118
129
  *
119
130
  * @internal For `FrameSupply`.
120
131
  */
@@ -78,6 +78,19 @@ export function colorMetadataFromVideoColorSpace(space) {
78
78
  transfer,
79
79
  };
80
80
  }
81
+ /**
82
+ * A frame with no planar YUV format the engine reads: an opaque frame (a hardware frame the
83
+ * browser does not map to the CPU, `format` null) or an RGB one. Reading it again cannot help;
84
+ * decoding it again in software can.
85
+ */
86
+ export class NonPlanarVideoFrameError extends Error {
87
+ format;
88
+ constructor(format) {
89
+ super(`frame has no planar YUV format the engine reads (${format ?? "opaque"}); decode HDR sources, and sources whose color the project declares, in software`);
90
+ this.name = "NonPlanarVideoFrameError";
91
+ this.format = format;
92
+ }
93
+ }
81
94
  /** Whether `frame` has a planar format the engine converts (`copyPlanarYuvFrame` can copy it). */
82
95
  export function isPlanarVideoFrame(frame) {
83
96
  return frame.format !== null && PLANAR_FORMATS.has(frame.format);
@@ -137,9 +150,10 @@ export class PlanarCopyPool {
137
150
  * CPU-readable planar format (a hardware frame the browser will not map) is
138
151
  * refused rather than converted by the browser.
139
152
  *
140
- * `frame` is closed whether the copy succeeds or not. Rejects when the frame
141
- * has no planar format the engine reads or no visible rectangle, or when
142
- * `copyTo` fails.
153
+ * `frame` is closed whether the copy succeeds or not. Rejects with
154
+ * {@link NonPlanarVideoFrameError} when the frame has no planar format the
155
+ * engine reads, and otherwise when it has no visible rectangle or `copyTo`
156
+ * fails.
143
157
  *
144
158
  * With `pool`, the copy's `data` is a buffer from it, which the caller gives back with
145
159
  * {@link PlanarCopyPool.release} after uploading; a failed copy gives it back itself.
@@ -155,15 +169,15 @@ export async function copyPlanarYuvFrame(frame, declared, identity = {}, pool) {
155
169
  /**
156
170
  * {@link copyPlanarYuvFrame} without closing `frame`: the caller owns it whether the copy succeeds
157
171
  * or not, so a frame whose planes the browser could not read back can be read again. Rejects as
158
- * {@link copyPlanarYuvFrame} does; with `pool`, a failed copy gives its buffer back.
172
+ * {@link copyPlanarYuvFrame} does, with {@link NonPlanarVideoFrameError} for a frame no read can
173
+ * copy; with `pool`, a failed copy gives its buffer back.
159
174
  *
160
175
  * @internal For `FrameSupply`.
161
176
  */
162
177
  export async function readPlanarYuvFrame(frame, declared, identity = {}, pool) {
163
178
  const format = frame.format;
164
- if (format === null || !isPlanarVideoFrame(frame)) {
165
- throw new Error(`frame has no planar YUV format the engine reads (${format ?? "opaque"}); decode HDR sources, and sources whose color the project declares, in software`);
166
- }
179
+ if (format === null || !isPlanarVideoFrame(frame))
180
+ throw new NonPlanarVideoFrameError(format);
167
181
  const visible = frame.visibleRect;
168
182
  if (!visible)
169
183
  throw new Error("frame has no visible rectangle");
package/dist/layout.d.ts CHANGED
@@ -9,7 +9,8 @@
9
9
  * tuple the sides object, an `[x, y]` tuple a vector. Lengths are written as the document writes
10
10
  * them: a number is a fraction of the picture's shorter side, `"12px"` pixels of the project
11
11
  * canvas, `"50%"` a percent of the parent's content box. Text style (`font_family`, `font_size`,
12
- * `color`, `line_height`, `text_align`, `outline`) may be set on any box and is inherited. Its
12
+ * `font_weight`, `color`, `line_height`, `letter_spacing`, `text_align`, `outline`) may be set on
13
+ * any box and is inherited. Its
13
14
  * output is a plain document that `validateProject` accepts; a CSS value string it cannot read
14
15
  * throws, with the parser's message.
15
16
  */
@@ -41,6 +42,16 @@ export interface NodeBounds {
41
42
  readonly overflow: boolean;
42
43
  /** A text node's line count; `null` for other nodes. */
43
44
  readonly lineCount: number | null;
45
+ /**
46
+ * A text node's first and last lines' alphabetic baselines, as fractions of the picture's height:
47
+ * its content box's top plus its text's baselines. `null` for other nodes and empty text.
48
+ */
49
+ readonly baselines: Baselines | null;
50
+ }
51
+ /** Where a text's first and last lines' alphabetic baselines lie, y as a fraction of the height. */
52
+ export interface Baselines {
53
+ readonly first: number;
54
+ readonly last: number;
44
55
  }
45
56
  /** Where every node of a layout lies, the root first, in document order. */
46
57
  export interface LayoutBounds {
@@ -87,8 +98,12 @@ export type Offset = string | readonly [Size, Size] | {
87
98
  export interface TextStyleProps {
88
99
  readonly font_family?: string;
89
100
  readonly font_size?: Value<Size>;
101
+ /** The weight the family's faces are matched by, in `[1, 1000]`. Not animated. */
102
+ readonly font_weight?: number;
90
103
  readonly color?: Color;
91
104
  readonly line_height?: number;
105
+ /** Space after each character, as a fraction of the font size, in `[-0.5, 1]`. Not animated. */
106
+ readonly letter_spacing?: number;
92
107
  readonly text_align?: TextAlign;
93
108
  readonly outline?: TextOutline;
94
109
  }
package/dist/layout.js CHANGED
@@ -9,7 +9,8 @@
9
9
  * tuple the sides object, an `[x, y]` tuple a vector. Lengths are written as the document writes
10
10
  * them: a number is a fraction of the picture's shorter side, `"12px"` pixels of the project
11
11
  * canvas, `"50%"` a percent of the parent's content box. Text style (`font_family`, `font_size`,
12
- * `color`, `line_height`, `text_align`, `outline`) may be set on any box and is inherited. Its
12
+ * `font_weight`, `color`, `line_height`, `letter_spacing`, `text_align`, `outline`) may be set on
13
+ * any box and is inherited. Its
13
14
  * output is a plain document that `validateProject` accepts; a CSS value string it cannot read
14
15
  * throws, with the parser's message.
15
16
  */
@@ -298,14 +298,29 @@ export declare function videoEncoderLatencyMode(codec: "avc" | "hevc" | "vp9" |
298
298
  * The rate this browser encodes `codec` audio of a project at `sampleRate` with, by the rule a
299
299
  * native host follows: the project rate when the browser's encoder takes it, else the lowest rate
300
300
  * the codec carries above it that the encoder takes, else the highest below it; `null` when the
301
- * encoder takes none. Pass it to {@link MediabunnySink} as `audioSampleRate`, so every project
302
- * rate exports where the browser encodes the codec at all.
301
+ * encoder takes none. AAC is encoded at the MPEG-4 rates only, the ones a native host's FFmpeg
302
+ * `aac` encoder takes, and an AAC encoder that accepts a rate but puts out another (Safari's above
303
+ * 48 kHz) does not take it. Pass it to {@link MediabunnySink} as `audioSampleRate`, so every
304
+ * project rate exports where the browser encodes the codec at all.
303
305
  */
304
306
  export declare function audioEncoderSampleRate(codec: "aac" | "opus", options: {
305
307
  readonly sampleRate: number;
306
308
  readonly numberOfChannels: number;
307
309
  readonly bitrate: number;
308
310
  }): Promise<number | null>;
311
+ /**
312
+ * The frames of priming this browser's AAC-LC encoder puts before the audio it is given at
313
+ * `sampleRate` with `numberOfChannels`. WebCodecs stamps the first chunk with the first input's
314
+ * time although the decoded audio starts with the encoder's delay (2112 frames on Chrome's and
315
+ * Safari's macOS encoders), and does not say how long that is. Measured once per configuration by
316
+ * encoding a noise burst and finding it in what the browser's decoder makes of it; 0 where either
317
+ * fails.
318
+ */
319
+ export declare function aacEncoderDelay(options: {
320
+ readonly sampleRate: number;
321
+ readonly numberOfChannels: number;
322
+ readonly bitrate: number;
323
+ }): Promise<number>;
309
324
  /** What a finished {@link MediabunnySink} produced. */
310
325
  export type ExportOutput = {
311
326
  readonly kind: "stream";
@@ -1321,14 +1321,16 @@ const ENCODER_SAMPLE_RATES = {
1321
1321
  * The rate this browser encodes `codec` audio of a project at `sampleRate` with, by the rule a
1322
1322
  * native host follows: the project rate when the browser's encoder takes it, else the lowest rate
1323
1323
  * the codec carries above it that the encoder takes, else the highest below it; `null` when the
1324
- * encoder takes none. Pass it to {@link MediabunnySink} as `audioSampleRate`, so every project
1325
- * rate exports where the browser encodes the codec at all.
1324
+ * encoder takes none. AAC is encoded at the MPEG-4 rates only, the ones a native host's FFmpeg
1325
+ * `aac` encoder takes, and an AAC encoder that accepts a rate but puts out another (Safari's above
1326
+ * 48 kHz) does not take it. Pass it to {@link MediabunnySink} as `audioSampleRate`, so every
1327
+ * project rate exports where the browser encodes the codec at all.
1326
1328
  */
1327
1329
  export async function audioEncoderSampleRate(codec, options) {
1328
1330
  const rate = options.sampleRate;
1329
1331
  const carried = ENCODER_SAMPLE_RATES[codec];
1330
1332
  const candidates = new Set([
1331
- rate,
1333
+ ...(codec === "opus" || carried.includes(rate) ? [rate] : []),
1332
1334
  ...carried.filter((candidate) => candidate > rate),
1333
1335
  ...carried.filter((candidate) => candidate < rate).reverse(),
1334
1336
  ]);
@@ -1337,12 +1339,240 @@ export async function audioEncoderSampleRate(codec, options) {
1337
1339
  numberOfChannels: options.numberOfChannels,
1338
1340
  sampleRate: candidate,
1339
1341
  quality: new Quality({ bitrate: options.bitrate }),
1342
+ ...(codec === "aac" ? { fullCodecString: AAC_CODEC_STRING } : {}),
1340
1343
  }).catch(() => false);
1341
- if (supported)
1344
+ if (!supported)
1345
+ continue;
1346
+ if (codec === "opus")
1347
+ return candidate;
1348
+ const { rate: putOut } = await probeAacEncoder({
1349
+ ...options,
1350
+ sampleRate: candidate,
1351
+ });
1352
+ if (putOut === undefined || putOut === candidate)
1342
1353
  return candidate;
1343
1354
  }
1344
1355
  return null;
1345
1356
  }
1357
+ /**
1358
+ * The AAC profile {@link MediabunnySink} encodes at every rate: AAC-LC, as a native host's FFmpeg
1359
+ * `aac` encoder does, where mediabunny would pick HE-AAC at 24 kHz and below.
1360
+ */
1361
+ const AAC_CODEC_STRING = "mp4a.40.2";
1362
+ /** The frames in one AAC-LC frame. */
1363
+ const AAC_FRAME_FRAMES = 1_024;
1364
+ /**
1365
+ * The rates AAC's two-byte `AudioSpecificConfig` names by index (ISO/IEC 14496-3,
1366
+ * `samplingFrequencyIndex`).
1367
+ */
1368
+ const AAC_SAMPLING_FREQUENCIES = [
1369
+ 96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000,
1370
+ 12_000, 11_025, 8_000, 7_350,
1371
+ ];
1372
+ /**
1373
+ * AAC-LC's two-byte `AudioSpecificConfig`; undefined for a rate without an index or a channel
1374
+ * count without a channel configuration (7, or more than 8).
1375
+ */
1376
+ function aacLcAudioSpecificConfig(sampleRate, numberOfChannels) {
1377
+ const frequency = AAC_SAMPLING_FREQUENCIES.indexOf(sampleRate);
1378
+ const channels = numberOfChannels === 8 ? 7 : numberOfChannels <= 6 ? numberOfChannels : 0;
1379
+ if (frequency < 0 || channels < 1)
1380
+ return undefined;
1381
+ return new Uint8Array([
1382
+ (2 << 3) | (frequency >> 1),
1383
+ ((frequency & 1) << 7) | (channels << 3),
1384
+ ]);
1385
+ }
1386
+ /** The low-passed noise burst an AAC delay probe encodes, in frames. */
1387
+ const AAC_DELAY_PROBE_FRAMES = 2_048;
1388
+ /** The longest delay a probe looks for, in frames; the silence after the burst is this long. */
1389
+ const AAC_DELAY_MAX_FRAMES = 8_192;
1390
+ /** How long a delay probe has to encode and decode the burst. */
1391
+ const AAC_DELAY_PROBE_TIMEOUT_MS = 1_500;
1392
+ /** How closely the decoded audio must match the burst at the lag found for it to count. */
1393
+ const AAC_DELAY_MIN_CORRELATION = 0.5;
1394
+ const aacProbes = new Map();
1395
+ /**
1396
+ * The frames of priming this browser's AAC-LC encoder puts before the audio it is given at
1397
+ * `sampleRate` with `numberOfChannels`. WebCodecs stamps the first chunk with the first input's
1398
+ * time although the decoded audio starts with the encoder's delay (2112 frames on Chrome's and
1399
+ * Safari's macOS encoders), and does not say how long that is. Measured once per configuration by
1400
+ * encoding a noise burst and finding it in what the browser's decoder makes of it; 0 where either
1401
+ * fails.
1402
+ */
1403
+ export async function aacEncoderDelay(options) {
1404
+ return (await probeAacEncoder(options)).delay;
1405
+ }
1406
+ /**
1407
+ * This browser's AAC-LC encoder at `sampleRate` with `numberOfChannels`, probed once per
1408
+ * configuration: the rate of the stream it puts out and its priming ({@link aacEncoderDelay}).
1409
+ */
1410
+ function probeAacEncoder(options) {
1411
+ const config = {
1412
+ codec: AAC_CODEC_STRING,
1413
+ sampleRate: options.sampleRate,
1414
+ numberOfChannels: options.numberOfChannels,
1415
+ bitrate: options.bitrate,
1416
+ };
1417
+ const key = JSON.stringify(config);
1418
+ let probe = aacProbes.get(key);
1419
+ if (probe === undefined) {
1420
+ probe = measureAacEncoder(config);
1421
+ aacProbes.set(key, probe);
1422
+ }
1423
+ return probe;
1424
+ }
1425
+ async function measureAacEncoder(config) {
1426
+ if (typeof AudioEncoder === "undefined" ||
1427
+ typeof AudioDecoder === "undefined")
1428
+ return { delay: 0 };
1429
+ let encoder;
1430
+ let decoder;
1431
+ let timer;
1432
+ const timedOut = new Promise((resolve) => {
1433
+ timer = setTimeout(() => resolve("timeout"), AAC_DELAY_PROBE_TIMEOUT_MS);
1434
+ });
1435
+ try {
1436
+ if (!(await AudioEncoder.isConfigSupported(config)).supported)
1437
+ return { delay: 0 };
1438
+ let failed = false;
1439
+ const chunks = [];
1440
+ let decoderConfig;
1441
+ encoder = new AudioEncoder({
1442
+ output: (chunk, metadata) => {
1443
+ chunks.push(chunk);
1444
+ decoderConfig ??= metadata?.decoderConfig;
1445
+ },
1446
+ error: () => (failed = true),
1447
+ });
1448
+ encoder.configure(config);
1449
+ // The burst follows a frame of silence, which Safari's encoder drops as it drops the first
1450
+ // frame of any input (see `#encodeAudio`).
1451
+ const probe = aacDelayProbe();
1452
+ const frames = AAC_FRAME_FRAMES + AAC_DELAY_PROBE_FRAMES + AAC_DELAY_MAX_FRAMES;
1453
+ const planar = new Float32Array(frames * config.numberOfChannels);
1454
+ for (let channel = 0; channel < config.numberOfChannels; channel += 1)
1455
+ planar.set(probe, channel * frames + AAC_FRAME_FRAMES);
1456
+ const input = new AudioData({
1457
+ format: "f32-planar",
1458
+ sampleRate: config.sampleRate,
1459
+ numberOfFrames: frames,
1460
+ numberOfChannels: config.numberOfChannels,
1461
+ timestamp: 0,
1462
+ data: planar,
1463
+ });
1464
+ try {
1465
+ encoder.encode(input);
1466
+ }
1467
+ finally {
1468
+ input.close();
1469
+ }
1470
+ if ((await Promise.race([encoder.flush(), timedOut])) === "timeout")
1471
+ return { delay: 0 };
1472
+ if (failed || decoderConfig === undefined)
1473
+ return { delay: 0 };
1474
+ const rate = decoderConfig.sampleRate;
1475
+ if (rate !== config.sampleRate)
1476
+ return { rate, delay: 0 };
1477
+ const planes = [];
1478
+ decoder = new AudioDecoder({
1479
+ output: (audio) => {
1480
+ try {
1481
+ if (audio.sampleRate !== config.sampleRate)
1482
+ failed = true;
1483
+ const plane = new Float32Array(audio.numberOfFrames);
1484
+ audio.copyTo(plane, { planeIndex: 0, format: "f32-planar" });
1485
+ planes.push(plane);
1486
+ }
1487
+ finally {
1488
+ audio.close();
1489
+ }
1490
+ },
1491
+ error: () => (failed = true),
1492
+ });
1493
+ // Safari's encoder describes its stream with a whole `ES_Descriptor`, which its own decoder
1494
+ // refuses (mediabunny rewrites it the same way in the file).
1495
+ const description = aacLcAudioSpecificConfig(config.sampleRate, config.numberOfChannels);
1496
+ decoder.configure(description === undefined
1497
+ ? decoderConfig
1498
+ : { ...decoderConfig, codec: AAC_CODEC_STRING, description });
1499
+ for (const chunk of chunks)
1500
+ decoder.decode(chunk);
1501
+ if ((await Promise.race([decoder.flush(), timedOut])) === "timeout")
1502
+ return { rate, delay: 0 };
1503
+ if (failed)
1504
+ return { rate, delay: 0 };
1505
+ const decoded = new Float32Array(planes.reduce((sum, plane) => sum + plane.length, 0));
1506
+ let offset = 0;
1507
+ for (const plane of planes) {
1508
+ decoded.set(plane, offset);
1509
+ offset += plane.length;
1510
+ }
1511
+ const lag = strongestLag(decoded, probe);
1512
+ return {
1513
+ rate,
1514
+ delay: lag === null ? 0 : Math.max(0, lag - AAC_FRAME_FRAMES),
1515
+ };
1516
+ }
1517
+ catch {
1518
+ return { delay: 0 };
1519
+ }
1520
+ finally {
1521
+ clearTimeout(timer);
1522
+ for (const coder of [encoder, decoder]) {
1523
+ try {
1524
+ if (coder?.state !== "closed")
1525
+ coder?.close();
1526
+ }
1527
+ catch {
1528
+ // Already closed by its own failure.
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+ /** The probe's burst: noise, low-passed so a lossy codec keeps most of it. */
1534
+ function aacDelayProbe() {
1535
+ const probe = new Float32Array(AAC_DELAY_PROBE_FRAMES);
1536
+ let seed = 1;
1537
+ let smoothed = 0;
1538
+ for (let index = 0; index < probe.length; index += 1) {
1539
+ seed = (Math.imul(seed, 1_103_515_245) + 12_345) >>> 0;
1540
+ smoothed += 0.5 * ((seed / 2 ** 32) * 2 - 1 - smoothed);
1541
+ probe[index] = 0.5 * smoothed;
1542
+ }
1543
+ return probe;
1544
+ }
1545
+ /**
1546
+ * The lag of `decoded` at which it matches `probe` best (normalized cross-correlation), up to the
1547
+ * probe's leading frame of silence and {@link AAC_DELAY_MAX_FRAMES}; null when no lag matches it
1548
+ * closely enough.
1549
+ */
1550
+ function strongestLag(decoded, probe) {
1551
+ let probeEnergy = 0;
1552
+ for (const value of probe)
1553
+ probeEnergy += value * value;
1554
+ // Sum of squares of `decoded` before each index, for each window's energy.
1555
+ const energy = new Float64Array(decoded.length + 1);
1556
+ for (let index = 0; index < decoded.length; index += 1)
1557
+ energy[index + 1] = energy[index] + decoded[index] * decoded[index];
1558
+ const lags = Math.min(AAC_FRAME_FRAMES + AAC_DELAY_MAX_FRAMES, decoded.length - probe.length);
1559
+ let best = null;
1560
+ let bestCorrelation = AAC_DELAY_MIN_CORRELATION;
1561
+ for (let lag = 0; lag <= lags; lag += 1) {
1562
+ const windowEnergy = energy[lag + probe.length] - energy[lag];
1563
+ if (windowEnergy <= 0)
1564
+ continue;
1565
+ let sum = 0;
1566
+ for (let index = 0; index < probe.length; index += 1)
1567
+ sum += decoded[lag + index] * probe[index];
1568
+ const correlation = sum / Math.sqrt(probeEnergy * windowEnergy);
1569
+ if (correlation > bestCorrelation) {
1570
+ bestCorrelation = correlation;
1571
+ best = lag;
1572
+ }
1573
+ }
1574
+ return best;
1575
+ }
1346
1576
  /**
1347
1577
  * Project-rate blocks converted to an encoder's rate with the engine's converter, as a native
1348
1578
  * host's AAC input converts them: outputs from the first block's start on, each made once the
@@ -1478,6 +1708,12 @@ export class MediabunnySink {
1478
1708
  /** When the encoder last put a frame out, or was given one while it owed none. */
1479
1709
  #progressAt = 0;
1480
1710
  #audio;
1711
+ #audioCodec;
1712
+ #audioBitrate;
1713
+ /** The AAC encoder's priming, in frames at the encoder's rate: see {@link aacEncoderDelay}. */
1714
+ #audioDelay;
1715
+ /** Whether the AAC encoder was given its leading frame of silence: see `#encodeAudio`. */
1716
+ #audioLeadWritten = false;
1481
1717
  #audioRate;
1482
1718
  #audioResampler;
1483
1719
  #audioConverter;
@@ -1570,10 +1806,15 @@ export class MediabunnySink {
1570
1806
  if (rate !== undefined && (!Number.isSafeInteger(rate) || rate <= 0))
1571
1807
  throw new RangeError("audioSampleRate must be a positive integer");
1572
1808
  this.#audioRate = rate;
1809
+ this.#audioCodec = options.audioCodec;
1810
+ this.#audioBitrate = options.audioBitrate;
1573
1811
  this.#audioResampler = options.audioResampler;
1574
1812
  this.#audio = new AudioSampleSource({
1575
1813
  codec: options.audioCodec,
1576
1814
  quality: new Quality({ bitrate: options.audioBitrate }),
1815
+ ...(options.audioCodec === "aac"
1816
+ ? { fullCodecString: AAC_CODEC_STRING }
1817
+ : {}),
1577
1818
  });
1578
1819
  }
1579
1820
  if (!this.#hasVideo && this.#audio === undefined)
@@ -1800,6 +2041,29 @@ export class MediabunnySink {
1800
2041
  }
1801
2042
  /** Encodes planar `channels` starting at sample `startSample` of a `sampleRate` stream. */
1802
2043
  async #encodeAudio(channels, startSample, sampleRate) {
2044
+ if (this.#audio === undefined)
2045
+ throw new Error("audio track is not configured");
2046
+ // AAC's priming goes before the output's zero, where the muxer trims it (an MP4 or MOV edit
2047
+ // list, negative Matroska block times), so the audio starts with the video; Opus states its
2048
+ // own in its header.
2049
+ let delay = 0;
2050
+ if (this.#audioCodec === "aac" && this.#audioBitrate !== undefined) {
2051
+ delay = await (this.#audioDelay ??= aacEncoderDelay({
2052
+ sampleRate,
2053
+ numberOfChannels: channels.length,
2054
+ bitrate: this.#audioBitrate,
2055
+ }));
2056
+ // Safari's encoder drops the first frame of its input: give it a frame of silence, before
2057
+ // zero with the priming, ahead of the audio.
2058
+ if (!this.#audioLeadWritten) {
2059
+ this.#audioLeadWritten = true;
2060
+ await this.#addAudio(channels.map(() => new Float32Array(AAC_FRAME_FRAMES)), startSample - AAC_FRAME_FRAMES - delay, sampleRate);
2061
+ }
2062
+ }
2063
+ await this.#addAudio(channels, startSample - delay, sampleRate);
2064
+ }
2065
+ /** Gives the audio encoder planar `channels` at sample `startSample` of a `sampleRate` stream. */
2066
+ async #addAudio(channels, startSample, sampleRate) {
1803
2067
  if (this.#audio === undefined)
1804
2068
  throw new Error("audio track is not configured");
1805
2069
  const frames = channels[0]?.length ?? 0;
package/dist/project.d.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * Timeline values are integer ticks at {@link TICKS_PER_SECOND}. Ranges are
15
15
  * half-open: `[start, end)`.
16
16
  */
17
- import type { Animated, Easing, FrameRate, Insets, Interpolation, LayoutOffset, LayoutSize, MediaTime, Paint, Project, Rgba } from "./generated/project-schema.js";
17
+ import type { Animated, Easing, FrameRate, Insets, Interpolation, LayoutOffset, LayoutSize, MediaTime, Paint, Project, Rgba, VisualProperties } from "./generated/project-schema.js";
18
18
  import { MAX_JSON_DEPTH } from "./json-text.js";
19
19
  export * from "./generated/project-schema.js";
20
20
  /** The deepest nesting of arrays and objects the engine reads in a project (serde_json's limit). */
@@ -157,7 +157,7 @@ type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
157
157
  * returns for a `Project`. Lengths and grid values keep the CSS spelling they were written in.
158
158
  */
159
159
  export type Canonical<T> = CanonicalValue<Exclude<T, null | undefined>> | Extract<T, null | undefined>;
160
- type CanonicalValue<T> = [T] extends [never] ? never : Same<T, Rgba> extends true ? RgbaObject : Same<T, Paint> extends true ? CanonicalPaint : Same<T, Insets> extends true ? CanonicalInsets : Same<T, LayoutOffset> extends true ? CanonicalOffset : CanonicalPart<T>;
160
+ type CanonicalValue<T> = [T] extends [never] ? never : Same<T, Rgba> extends true ? RgbaObject : Same<T, Paint> extends true ? CanonicalPaint : Same<T, Insets> extends true ? CanonicalInsets : Same<T, LayoutOffset> extends true ? CanonicalOffset : Same<T, VisualProperties> extends true ? CanonicalPart<Required<VisualProperties>> : CanonicalPart<T>;
161
161
  type CanonicalPart<T> = T extends string | number | boolean | bigint ? T : {
162
162
  readonly [K in keyof T]: Canonical<T[K]>;
163
163
  };
@@ -204,6 +204,17 @@ export type LintOwner = {
204
204
  readonly type: "cue";
205
205
  readonly track: string;
206
206
  readonly index: number;
207
+ }
208
+ /** A composition's node, whose settings are keyed in composition time. */
209
+ | {
210
+ readonly type: "composition_node";
211
+ readonly composition: string;
212
+ readonly node: string;
213
+ }
214
+ /** A generated source, whose shapes or layout tree is keyed in its picture's time. */
215
+ | {
216
+ readonly type: "source";
217
+ readonly source: string;
207
218
  };
208
219
  /** The shapes generator a shape {@link LintIssue} is about. */
209
220
  export type ShapeLintOwner = {
@@ -223,7 +234,10 @@ export type LintIssue =
223
234
  {
224
235
  readonly kind: "unreached_keyframe";
225
236
  readonly owner: LintOwner;
226
- /** Such as `visual.opacity` or `masks[0].feather`. */
237
+ /**
238
+ * Such as `visual.opacity` or `masks[0].feather` on a clip, `effect.params.radius` on a
239
+ * composition node, or `items[0].transform.opacity` on a generated source.
240
+ */
227
241
  readonly property: string;
228
242
  readonly time: number;
229
243
  }
@@ -285,7 +299,10 @@ export interface LintBinding {
285
299
  * A valid project's non-fatal diagnostics, computed by the engine's own
286
300
  * `Project::lint`, in a fixed order: unused sources, then shapes generators
287
301
  * (sources', then composition nodes'), then HDR sources, then each track's
288
- * clips, transitions, and cues.
302
+ * clips, transitions, and cues, then compositions' nodes, then generated
303
+ * sources' trees. A keyframe is checked in its own time: a clip's in timeline
304
+ * time, a composition node's in the composition time the clips that show it
305
+ * map to, a generated source's in the picture time its clips' time maps reach.
289
306
  *
290
307
  * Diagnostics never block a load or an export; they flag what is probably a
291
308
  * mistake in a project the engine accepts.