node-av 6.2.0-beta.25 → 6.2.0-beta.27

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/api/audio-frame-buffer.d.ts +368 -22
  3. package/dist/api/audio-frame-buffer.js +687 -100
  4. package/dist/api/audio-frame-buffer.js.map +1 -1
  5. package/dist/api/demuxer.d.ts +7 -3
  6. package/dist/api/demuxer.js +19 -7
  7. package/dist/api/demuxer.js.map +1 -1
  8. package/dist/api/encoder.d.ts +40 -3
  9. package/dist/api/encoder.js +61 -23
  10. package/dist/api/encoder.js.map +1 -1
  11. package/dist/api/fmp4-stream.d.ts +103 -3
  12. package/dist/api/fmp4-stream.js +151 -28
  13. package/dist/api/fmp4-stream.js.map +1 -1
  14. package/dist/api/index.d.ts +1 -1
  15. package/dist/api/index.js.map +1 -1
  16. package/dist/api/io-stream.js +21 -6
  17. package/dist/api/io-stream.js.map +1 -1
  18. package/dist/api/muxer.d.ts +275 -7
  19. package/dist/api/muxer.js +569 -62
  20. package/dist/api/muxer.js.map +1 -1
  21. package/dist/api/rtp-stream.d.ts +19 -2
  22. package/dist/api/rtp-stream.js +62 -15
  23. package/dist/api/rtp-stream.js.map +1 -1
  24. package/dist/api/scaler.d.ts +19 -4
  25. package/dist/api/scaler.js +21 -6
  26. package/dist/api/scaler.js.map +1 -1
  27. package/dist/api/utilities/packet-age-watchdog.d.ts +198 -0
  28. package/dist/api/utilities/packet-age-watchdog.js +594 -0
  29. package/dist/api/utilities/packet-age-watchdog.js.map +1 -0
  30. package/dist/lib/binding.d.ts +9 -1
  31. package/dist/lib/binding.js +13 -0
  32. package/dist/lib/binding.js.map +1 -1
  33. package/dist/lib/format-context.d.ts +7 -0
  34. package/dist/lib/format-context.js +7 -0
  35. package/dist/lib/format-context.js.map +1 -1
  36. package/dist/lib/frame.d.ts +6 -2
  37. package/dist/lib/frame.js +11 -3
  38. package/dist/lib/frame.js.map +1 -1
  39. package/dist/lib/native-types.d.ts +3 -1
  40. package/package.json +12 -12
package/README.md CHANGED
@@ -532,7 +532,7 @@ NodeAV provides direct bindings to FFmpeg's C APIs, which work with raw memory p
532
532
  NodeAV works inside `worker_threads`, with two caveats:
533
533
 
534
534
  - **Prefer graceful shutdown over `worker.terminate()`.** Terminating a worker while native calls are in flight is mitigated (pending completions are dropped safely instead of aborting), but a termination that lands exactly inside a running synchronous native call can still abort the process — a limitation of Node-API error handling during isolate teardown. Signal the worker to close its NodeAV resources and exit on its own. For test runners, process isolation (e.g. vitest `pool: 'forks'`) is the most robust choice.
535
- - **Async operations share the libuv thread pool** (default: 4 threads, process-wide across all workers). A custom IO read callback that never settles parks one pool thread until it resolves; enough of them stall every async NodeAV operation in the entire process. Make custom IO callbacks always settle (return `null` for EOF, throw on error), and raise `UV_THREADPOOL_SIZE` when running many parallel live inputs.
535
+ - **Async operations share the libuv thread pool** (default: 4 threads, process-wide across all workers). A custom IO read callback that never settles parks one pool thread until it resolves or its input is closed or interrupted (a closing `Demuxer` or an exiting process or worker fails it with `AVERROR_EXIT`); enough of them stall every async NodeAV operation in the entire process. Make custom IO callbacks always settle (return `null` for EOF, throw on error), and raise `UV_THREADPOOL_SIZE` when running many parallel live inputs.
536
536
 
537
537
  ## Electron
538
538
 
@@ -1,6 +1,47 @@
1
1
  import { Frame } from '../lib/frame.js';
2
2
  import type { AVSampleFormat } from '../constants/index.js';
3
3
  import type { ChannelLayout } from '../lib/types.js';
4
+ /**
5
+ * Options for {@link AudioFrameBuffer.create}.
6
+ */
7
+ export interface AudioFrameBufferOptions {
8
+ /**
9
+ * Where the timestamps of the output frames come from.
10
+ *
11
+ * With `'input'` the output keeps the timing of the pushed frames, as described
12
+ * for {@link AudioFrameBuffer}. With `'samples'` input timestamps are ignored and
13
+ * the output is counted from 0 by its samples, in the time base of the pushed
14
+ * frames; use it for input whose timestamps are unusable.
15
+ *
16
+ * @default 'input'
17
+ */
18
+ timestamps?: 'input' | 'samples';
19
+ /**
20
+ * Largest gap in seconds that is filled with silence.
21
+ *
22
+ * A larger gap restarts the output timeline at the new timestamp, so it shows up
23
+ * as a timestamp jump instead. Real-time outputs such as RTP are better served by
24
+ * `0`: a filled gap is only written once the input resumes and then goes out as a
25
+ * burst of late packets, while receivers handle a timestamp gap like packet loss.
26
+ * Gaps of up to one output frame are filled either way, because a restart pads the
27
+ * current output frame with silence to its end. The silence is generated while
28
+ * pulling and takes no memory, but a long fill comes out in one go once the input
29
+ * resumes.
30
+ *
31
+ * @default 1
32
+ */
33
+ maxGapFill?: number;
34
+ }
35
+ /**
36
+ * Check the options of an audio frame buffer.
37
+ *
38
+ * @param options - Options to check
39
+ *
40
+ * @throws {RangeError} If an option is out of range
41
+ *
42
+ * @internal
43
+ */
44
+ export declare function assertAudioFrameBufferOptions(options: AudioFrameBufferOptions): void;
4
45
  /**
5
46
  * Audio frame buffering utility for encoders with fixed frame size requirements.
6
47
  *
@@ -8,6 +49,16 @@ import type { ChannelLayout } from '../lib/types.js';
8
49
  * of samples (frame_size). This class buffers incoming frames and outputs frames
9
50
  * with exactly the required size.
10
51
  *
52
+ * Output frames keep the input timing: each carries the timestamp of its first
53
+ * sample, in the time base of the pushed frames, and counts on by samples while the
54
+ * input is continuous. Deviations of up to 20 ms count as continuous, and larger ones
55
+ * only once they persist over 0.2 s of input, so jitter and single frames with a wrong
56
+ * timestamp leave the audio untouched. A persistent gap of up to a second is then
57
+ * filled with silence and an overlap of up to a second is dropped, which keeps the
58
+ * audio contiguous and in sync; a larger jump restarts the timeline at the new
59
+ * timestamp on the next frame boundary. Frames without a timestamp or time base
60
+ * continue the previous one.
61
+ *
11
62
  * Uses FFmpeg's AVAudioFifo internally for efficient sample buffering.
12
63
  *
13
64
  * @example
@@ -41,17 +92,37 @@ import type { ChannelLayout } from '../lib/types.js';
41
92
  * tail.free();
42
93
  * }
43
94
  * ```
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * // Real-time output: input gaps become timestamp jumps instead of silence
99
+ * using buffer = AudioFrameBuffer.create(960, AV_SAMPLE_FMT_FLT, 48000, 'mono', 1, { maxGapFill: 0 });
100
+ * ```
44
101
  */
45
102
  export declare class AudioFrameBuffer implements Disposable {
46
103
  private fifo;
47
104
  private frame;
48
105
  private frameSize;
49
- private sampleFormat;
50
106
  private channels;
107
+ private sampleStride;
51
108
  private staging;
52
109
  private stagingPlanes;
53
- private nextPts;
54
- private firstFramePts;
110
+ private silenceValue;
111
+ private sampleTimeBase;
112
+ private timeBase;
113
+ private countsInSamples;
114
+ private followInput;
115
+ private tolerance;
116
+ private confirmSamples;
117
+ private maxFill;
118
+ private maxTrim;
119
+ private headIndex;
120
+ private tailIndex;
121
+ private segments;
122
+ private silence;
123
+ private timed;
124
+ private trimPending;
125
+ private deviation;
55
126
  /**
56
127
  * @param fifo - Underlying AudioFifo instance
57
128
  *
@@ -63,6 +134,8 @@ export declare class AudioFrameBuffer implements Disposable {
63
134
  *
64
135
  * @param channelLayout - Channel layout
65
136
  *
137
+ * @param options - Timing options
138
+ *
66
139
  * @internal
67
140
  */
68
141
  private constructor();
@@ -79,18 +152,24 @@ export declare class AudioFrameBuffer implements Disposable {
79
152
  *
80
153
  * @param channels - Number of audio channels
81
154
  *
155
+ * @param options - Timing options
156
+ *
82
157
  * @returns Configured audio frame buffer
83
158
  *
159
+ * @throws {RangeError} If an option is out of range
160
+ *
84
161
  * @example
85
162
  * ```typescript
86
163
  * // For Opus encoder at 48kHz with 20ms frames
87
164
  * const buffer = AudioFrameBuffer.create(960, AV_SAMPLE_FMT_FLT, 48000, 'mono', 1);
88
165
  * ```
89
166
  */
90
- static create(frameSize: number, sampleFormat: AVSampleFormat, sampleRate: number, channelLayout: ChannelLayout, channels: number): AudioFrameBuffer;
167
+ static create(frameSize: number, sampleFormat: AVSampleFormat, sampleRate: number, channelLayout: ChannelLayout, channels: number, options?: AudioFrameBufferOptions): AudioFrameBuffer;
91
168
  /**
92
169
  * Get number of samples currently in buffer.
93
170
  *
171
+ * Includes silence inserted for gaps in the input.
172
+ *
94
173
  * @returns Number of buffered samples
95
174
  *
96
175
  * @example
@@ -102,7 +181,7 @@ export declare class AudioFrameBuffer implements Disposable {
102
181
  /**
103
182
  * Check if a complete frame is available.
104
183
  *
105
- * Returns true if the FIFO contains at least frameSize samples.
184
+ * Returns true if the buffer holds at least frameSize samples.
106
185
  *
107
186
  * @returns True if a full frame can be pulled
108
187
  *
@@ -121,8 +200,23 @@ export declare class AudioFrameBuffer implements Disposable {
121
200
  * The frame's samples are added to the internal FIFO.
122
201
  * Call hasFrame() and pull() to retrieve fixed-size output frames.
123
202
  *
203
+ * The first frame with a valid time base fixes the time base of the output frames.
204
+ * When the frame timestamps deviate from the buffered samples by more than 20 ms
205
+ * over at least 0.2 s of input (and 3 frames), a gap is filled with silence (up to
206
+ * `maxGapFill`) and an overlap of up to 1 s is dropped from the input; a larger jump
207
+ * restarts the timeline at the new timestamp after padding the current output frame
208
+ * with silence. The frames that arrive until then still continue the previous
209
+ * timeline. Each such correction is a short dropout or cut in the audio: input whose
210
+ * timestamps drift against its sample count, such as a capture device stamped from
211
+ * the system clock, gets one per 20 ms of drift, which keeps it within about 20 ms
212
+ * of its timestamps.
213
+ *
124
214
  * @param frame - Audio frame to buffer
125
215
  *
216
+ * @throws {Error} If the frame is not an audio frame
217
+ *
218
+ * @throws {FFmpegError} If the samples cannot be written to the FIFO
219
+ *
126
220
  * @example
127
221
  * ```typescript
128
222
  * await buffer.push(filterFrame);
@@ -137,9 +231,14 @@ export declare class AudioFrameBuffer implements Disposable {
137
231
  *
138
232
  * The frame's samples are added to the internal FIFO.
139
233
  * Call hasFrame() and pullSync() to retrieve fixed-size output frames.
234
+ * Timestamps are handled as in push().
140
235
  *
141
236
  * @param frame - Audio frame to buffer
142
237
  *
238
+ * @throws {Error} If the frame is not an audio frame
239
+ *
240
+ * @throws {FFmpegError} If the samples cannot be written to the FIFO
241
+ *
143
242
  * @example
144
243
  * ```typescript
145
244
  * buffer.pushSync(filterFrame);
@@ -151,12 +250,15 @@ export declare class AudioFrameBuffer implements Disposable {
151
250
  /**
152
251
  * Pull a fixed-size audio frame from the buffer asynchronously.
153
252
  *
154
- * Reads exactly frameSize samples from the FIFO and returns a cloned Frame.
253
+ * Reads exactly frameSize samples from the FIFO and returns a cloned Frame
254
+ * stamped with the timestamp of its first sample.
155
255
  * Returns null if not enough samples are available.
156
256
  * Reuses internal frame buffer for efficiency (like Decoder does).
157
257
  *
158
258
  * @returns Audio frame with exactly frameSize samples, or null if insufficient samples
159
259
  *
260
+ * @throws {FFmpegError} If the FIFO cannot be read or the frame cannot be filled
261
+ *
160
262
  * @throws {Error} If frame cloning fails (out of memory)
161
263
  *
162
264
  * @example
@@ -174,12 +276,15 @@ export declare class AudioFrameBuffer implements Disposable {
174
276
  * Pull a fixed-size audio frame from the buffer synchronously.
175
277
  * Synchronous version of pull.
176
278
  *
177
- * Reads exactly frameSize samples from the FIFO and returns a cloned Frame.
279
+ * Reads exactly frameSize samples from the FIFO and returns a cloned Frame
280
+ * stamped with the timestamp of its first sample.
178
281
  * Returns null if not enough samples are available.
179
282
  * Reuses internal frame buffer for efficiency (like Decoder does).
180
283
  *
181
284
  * @returns Audio frame with exactly frameSize samples, or null if insufficient samples
182
285
  *
286
+ * @throws {FFmpegError} If the FIFO cannot be read or the frame cannot be filled
287
+ *
183
288
  * @throws {Error} If frame cloning fails (out of memory)
184
289
  *
185
290
  * @example
@@ -201,10 +306,13 @@ export declare class AudioFrameBuffer implements Disposable {
201
306
  * Intended for end-of-stream flushing only - without it the tail (up to
202
307
  * frameSize - 1 samples) would be dropped. Returns null if the buffer is
203
308
  * empty, or while a complete frame is still available (drain those with
204
- * pull() first).
309
+ * pull() first). The padding counts as audio, so frames pushed afterwards are
310
+ * timed after it.
205
311
  *
206
312
  * @returns Silence-padded audio frame with frameSize samples, or null if nothing to drain
207
313
  *
314
+ * @throws {FFmpegError} If the FIFO cannot be read or the frame cannot be filled
315
+ *
208
316
  * @throws {Error} If frame cloning fails (out of memory)
209
317
  *
210
318
  * @example
@@ -231,6 +339,8 @@ export declare class AudioFrameBuffer implements Disposable {
231
339
  *
232
340
  * @returns Silence-padded audio frame with frameSize samples, or null if nothing to drain
233
341
  *
342
+ * @throws {FFmpegError} If the FIFO cannot be read or the frame cannot be filled
343
+ *
234
344
  * @throws {Error} If frame cloning fails (out of memory)
235
345
  *
236
346
  * @example
@@ -247,17 +357,262 @@ export declare class AudioFrameBuffer implements Disposable {
247
357
  */
248
358
  pullPartialSync(): Frame | null;
249
359
  /**
250
- * Fill the staged sample range [fromSample, frameSize) with silence.
360
+ * Reset the buffer, discarding all buffered samples.
361
+ *
362
+ * The next pushed frame starts a new timeline, and its time base becomes
363
+ * the output time base.
364
+ *
365
+ * @example
366
+ * ```typescript
367
+ * buffer.reset();
368
+ * ```
369
+ */
370
+ reset(): void;
371
+ /**
372
+ * Decide how a pushed frame continues the buffered samples.
373
+ *
374
+ * The only place that moves the write position: it records the silence before the
375
+ * frame and accounts for the samples the caller then writes, so the position always
376
+ * runs ahead of the buffered samples by exactly the writes still in flight.
377
+ *
378
+ * @param frame - Audio frame about to be written
379
+ *
380
+ * @param nbSamples - Number of samples in the frame
381
+ *
382
+ * @returns Samples to drop from the head of the frame
383
+ *
384
+ * @internal
385
+ */
386
+ private planPush;
387
+ /**
388
+ * Append silence at the write position.
389
+ *
390
+ * Silence only exists as a run of sample indices and is generated while pulling, so
391
+ * a long gap costs neither a buffer of its size nor a FIFO grown to hold it (an
392
+ * AVAudioFifo never shrinks again).
393
+ *
394
+ * @param samples - Number of silent samples
395
+ *
396
+ * @internal
397
+ */
398
+ private addSilence;
399
+ /**
400
+ * Anchor the timeline at the first frame that carries a timestamp.
401
+ *
402
+ * @param pts - Timestamp of the frame in the output time base
403
+ *
404
+ * @returns Silence to write before the frame
405
+ *
406
+ * @internal
407
+ */
408
+ private anchorInput;
409
+ /**
410
+ * Compare a frame's timestamp with the buffered samples and compensate a persistent deviation.
411
+ *
412
+ * Within the tolerance the frame counts on by samples. A larger deviation is only
413
+ * acted on once it has lasted over enough input in the same direction: jitter and
414
+ * frames with a wrong timestamp come and go, while gaps, overlaps and clock steps
415
+ * persist. The correction is the median deviation of that run, so jitter on top of
416
+ * a real step does not leak into it.
417
+ *
418
+ * @param pts - Timestamp of the frame in the output time base
419
+ *
420
+ * @param nbSamples - Number of samples in the frame
421
+ *
422
+ * @returns Silence to write before the frame
423
+ *
424
+ * @internal
425
+ */
426
+ private trackInput;
427
+ /**
428
+ * Apply a confirmed deviation to the timeline.
429
+ *
430
+ * A gap is filled with silence and an overlap is dropped from the input, which keeps
431
+ * the output contiguous and on its frame grid. Beyond their limits the timeline
432
+ * restarts at the frame's timestamp instead.
433
+ *
434
+ * @param offset - Deviation of the frame in the output time base
435
+ *
436
+ * @param expected - Timestamp the frame would have without the deviation
437
+ *
438
+ * @returns Silence to write before the frame
439
+ *
440
+ * @internal
441
+ */
442
+ private compensate;
443
+ /**
444
+ * Start a new segment at the next output frame boundary.
445
+ *
446
+ * Every output frame then lies within one segment, so its timestamp stays well
447
+ * defined; the current partial frame is padded with silence to get there.
448
+ *
449
+ * @param pts - Timestamp of the frame about to be written
450
+ *
451
+ * @returns Silence to write before the frame
452
+ *
453
+ * @internal
454
+ */
455
+ private restart;
456
+ /**
457
+ * Fix the output time base from the first pushed frame.
458
+ *
459
+ * Frames without a valid time base leave the output counting samples (1/sample_rate).
460
+ *
461
+ * @param frame - First pushed frame
462
+ *
463
+ * @returns Output time base
464
+ *
465
+ * @internal
466
+ */
467
+ private lockTimeBase;
468
+ /**
469
+ * Read a frame's timestamp in the output time base.
251
470
  *
252
- * Follows av_samples_set_silence() semantics: unsigned 8-bit formats use 0x80
253
- * as the silence value, every other format uses 0. Planar frames carry one
254
- * channel per plane; packed frames interleave all channels in plane 0.
471
+ * @param frame - Pushed frame
472
+ *
473
+ * @returns Timestamp, or AV_NOPTS_VALUE if the frame has no timestamp or time base
474
+ *
475
+ * @internal
476
+ */
477
+ private inputPts;
478
+ /**
479
+ * Timestamp of the next sample to pull.
480
+ *
481
+ * Drops segments the head has reached the end of first, so the head lies in the first one.
482
+ *
483
+ * @returns Timestamp in the output time base
484
+ *
485
+ * @internal
486
+ */
487
+ private headPts;
488
+ /**
489
+ * Timestamp right after the last buffered sample.
490
+ *
491
+ * @returns Timestamp in the output time base
492
+ *
493
+ * @internal
494
+ */
495
+ private tailPts;
496
+ /**
497
+ * Treat the silence padding of a partial frame as written audio.
498
+ *
499
+ * @internal
500
+ */
501
+ private advanceTailToHead;
502
+ /**
503
+ * Realign the write position with the FIFO after a failed write.
504
+ *
505
+ * @internal
506
+ */
507
+ private resyncTail;
508
+ /**
509
+ * Number of samples that can be pulled: buffered samples plus the silence between them.
510
+ *
511
+ * Stops at the first silence run that lies behind a write still in flight.
512
+ *
513
+ * @returns Number of samples available from the read position
514
+ *
515
+ * @internal
516
+ */
517
+ private available;
518
+ /**
519
+ * Split the next samples to pull into FIFO reads and silence.
520
+ *
521
+ * @param count - Number of samples to pull
522
+ *
523
+ * @returns Parts in pull order
524
+ *
525
+ * @internal
526
+ */
527
+ private readRuns;
528
+ /**
529
+ * Read the next samples into the head of the staging buffer.
530
+ *
531
+ * @param count - Number of samples to read
532
+ *
533
+ * @throws {FFmpegError} If the FIFO cannot be read
534
+ *
535
+ * @internal
536
+ */
537
+ private readStaging;
538
+ /**
539
+ * Read the next samples into the head of the staging buffer synchronously.
540
+ * Synchronous version of readStaging.
541
+ *
542
+ * @param count - Number of samples to read
543
+ *
544
+ * @throws {FFmpegError} If the FIFO cannot be read
545
+ *
546
+ * @internal
547
+ */
548
+ private readStagingSync;
549
+ /**
550
+ * Staging planes starting at a sample offset.
551
+ *
552
+ * @param offset - First sample to write to
553
+ *
554
+ * @returns Plane buffers for a FIFO read
555
+ *
556
+ * @internal
557
+ */
558
+ private stagingAt;
559
+ /**
560
+ * Convert a sample count to output time base ticks.
561
+ *
562
+ * @param samples - Number of samples
563
+ *
564
+ * @returns Duration in the output time base
565
+ *
566
+ * @internal
567
+ */
568
+ private ticks;
569
+ /**
570
+ * Convert output time base ticks to a sample count.
571
+ *
572
+ * @param ticks - Duration in the output time base
573
+ *
574
+ * @returns Number of samples (rounded)
575
+ *
576
+ * @internal
577
+ */
578
+ private samples;
579
+ /**
580
+ * Plane buffers of a pushed frame, starting at a sample offset.
581
+ *
582
+ * @param frame - Pushed frame
583
+ *
584
+ * @param skip - Samples to leave out at the head
585
+ *
586
+ * @returns Plane buffers to write to the FIFO
587
+ *
588
+ * @internal
589
+ */
590
+ private inputPlanes;
591
+ /**
592
+ * Stamp the reusable frame, advance the read position by one frame and hand out a clone.
593
+ *
594
+ * @param pts - Timestamp of the frame's first sample
595
+ *
596
+ * @returns Cloned output frame
597
+ *
598
+ * @throws {Error} If frame cloning fails (out of memory)
599
+ *
600
+ * @internal
601
+ */
602
+ private emitFrame;
603
+ /**
604
+ * Fill the staged sample range [fromSample, toSample) with silence.
605
+ *
606
+ * Planar frames carry one channel per plane; packed frames interleave all
607
+ * channels in plane 0.
255
608
  *
256
609
  * @param fromSample - First sample index to silence
257
610
  *
611
+ * @param toSample - Sample index after the last one to silence
612
+ *
258
613
  * @internal
259
614
  */
260
- private padWithSilence;
615
+ private fillSilence;
261
616
  /**
262
617
  * Copy the staged samples into the reusable frame.
263
618
  *
@@ -269,15 +624,6 @@ export declare class AudioFrameBuffer implements Disposable {
269
624
  * @internal
270
625
  */
271
626
  private commitStaging;
272
- /**
273
- * Reset the buffer, discarding all buffered samples.
274
- *
275
- * @example
276
- * ```typescript
277
- * buffer.reset();
278
- * ```
279
- */
280
- reset(): void;
281
627
  /**
282
628
  * Free the buffer and all resources.
283
629
  *