node-av 3.0.5 → 3.1.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.
@@ -0,0 +1,656 @@
1
+ import { RTCRtpCodecParameters, RtpPacket } from 'werift';
2
+ import type { AVCodecID, AVHWDeviceType } from '../constants/constants.js';
3
+ /**
4
+ * Codec information for WebRTC streaming.
5
+ *
6
+ * Contains RTP codec parameters and FFmpeg codec IDs for video and audio streams.
7
+ * Used for codec negotiation in WebRTC peer connections.
8
+ */
9
+ export interface WebRTCCodecInfo {
10
+ /**
11
+ * Video codec configuration.
12
+ * Combines RTP parameters (mimeType, clockRate, etc.) with FFmpeg codec ID.
13
+ */
14
+ video: Partial<RTCRtpCodecParameters> & {
15
+ codecId: AVCodecID;
16
+ };
17
+ /**
18
+ * Optional audio codec configuration.
19
+ * Combines RTP parameters (mimeType, clockRate, channels) with FFmpeg codec ID.
20
+ */
21
+ audio?: Partial<RTCRtpCodecParameters> & {
22
+ codecId: AVCodecID;
23
+ };
24
+ }
25
+ /**
26
+ * Options for configuring WebRTC streaming.
27
+ */
28
+ export interface WebRTCStreamOptions {
29
+ /**
30
+ * Callback invoked for each video RTP packet.
31
+ * Use this to send packets to your WebRTC implementation.
32
+ *
33
+ * @param packet - Serialized RTP packet ready for transmission
34
+ */
35
+ onVideoPacket?: (packet: RtpPacket) => void;
36
+ /**
37
+ * Callback invoked for each audio RTP packet.
38
+ * Use this to send packets to your WebRTC implementation.
39
+ *
40
+ * @param packet - Serialized RTP packet ready for transmission
41
+ */
42
+ onAudioPacket?: (packet: RtpPacket) => void;
43
+ /**
44
+ * Maximum transmission unit (MTU) size in bytes.
45
+ * RTP packets will be fragmented to fit within this size.
46
+ *
47
+ * @default 1200
48
+ */
49
+ mtu?: number;
50
+ /**
51
+ * Hardware acceleration configuration.
52
+ *
53
+ * - `'auto'` - Automatically detect and use available hardware acceleration
54
+ * - Object with deviceType - Manually specify hardware acceleration type
55
+ *
56
+ * @default { deviceType: AV_HWDEVICE_TYPE_NONE }
57
+ */
58
+ hardware?: 'auto' | {
59
+ deviceType: AVHWDeviceType;
60
+ device?: string;
61
+ options?: Record<string, string>;
62
+ };
63
+ }
64
+ /**
65
+ * High-level WebRTC streaming with automatic codec detection and transcoding.
66
+ *
67
+ * Provides library-agnostic RTP streaming for WebRTC applications.
68
+ * Automatically detects input codecs and transcodes non-WebRTC-compatible formats.
69
+ * Handles video (H.264, H.265, VP8, VP9) and audio (Opus, PCMA, PCMU) codecs.
70
+ * Supports hardware acceleration for video transcoding.
71
+ * Essential component for building WebRTC streaming servers without direct WebRTC library coupling.
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * import { WebRTCStream } from 'node-av/api';
76
+ *
77
+ * // Create stream with RTP packet callbacks
78
+ * const stream = await WebRTCStream.create('rtsp://camera.local/stream', {
79
+ * mtu: 1200,
80
+ * hardware: 'auto',
81
+ * onVideoPacket: (rtp) => {
82
+ * // Send RTP packet to WebRTC peer connection
83
+ * videoTrack.writeRtp(rtp);
84
+ * },
85
+ * onAudioPacket: (rtp) => {
86
+ * audioTrack.writeRtp(rtp);
87
+ * }
88
+ * });
89
+ *
90
+ * // Get detected codecs for SDP negotiation
91
+ * const codecs = stream.getCodecs();
92
+ * console.log('Video:', codecs.video.mimeType);
93
+ * console.log('Audio:', codecs.audio?.mimeType);
94
+ *
95
+ * // Start streaming
96
+ * await stream.start();
97
+ * ```
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * // Stream with hardware acceleration
102
+ * import { AV_HWDEVICE_TYPE_CUDA } from 'node-av/constants';
103
+ *
104
+ * const stream = await WebRTCStream.create('video.mp4', {
105
+ * hardware: {
106
+ * deviceType: AV_HWDEVICE_TYPE_CUDA,
107
+ * device: '/dev/nvidia0'
108
+ * },
109
+ * onVideoPacket: (rtp) => sendToWebRTC(rtp)
110
+ * });
111
+ *
112
+ * await stream.start();
113
+ * stream.stop();
114
+ * stream.dispose();
115
+ * ```
116
+ *
117
+ * @see {@link WebRTCSession} For complete WebRTC session management with werift
118
+ * @see {@link MediaInput} For input media handling
119
+ * @see {@link HardwareContext} For GPU acceleration
120
+ */
121
+ export declare class WebRTCStream implements Disposable {
122
+ private input;
123
+ private codecInfo;
124
+ private options;
125
+ private videoOutput;
126
+ private audioOutput;
127
+ private hardwareContext;
128
+ private videoDecoder;
129
+ private videoEncoder;
130
+ private audioDecoder;
131
+ private audioFilter;
132
+ private audioEncoder;
133
+ private streamActive;
134
+ /**
135
+ * @param input - Media input source
136
+ *
137
+ * @param options - Stream configuration options
138
+ *
139
+ * Use {@link create} factory method
140
+ *
141
+ * @internal
142
+ */
143
+ private constructor();
144
+ /**
145
+ * Create a WebRTC stream from a media source.
146
+ *
147
+ * Opens the input media, detects video and audio codecs, and prepares
148
+ * transcoding pipelines for non-WebRTC-compatible formats.
149
+ * Automatically configures H.264 encoding for unsupported video codecs
150
+ * and Opus encoding for unsupported audio codecs.
151
+ *
152
+ * @param inputUrl - Media source URL (RTSP, file path, HTTP, etc.)
153
+ *
154
+ * @param options - Stream configuration options
155
+ *
156
+ * @returns Configured WebRTC stream instance
157
+ *
158
+ * @throws {Error} If no video stream found in input
159
+ *
160
+ * @throws {FFmpegError} If input cannot be opened
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * // Stream from RTSP camera
165
+ * const stream = await WebRTCStream.create('rtsp://camera.local/stream', {
166
+ * mtu: 1200,
167
+ * onVideoPacket: (rtp) => videoTrack.writeRtp(rtp),
168
+ * onAudioPacket: (rtp) => audioTrack.writeRtp(rtp)
169
+ * });
170
+ * ```
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * // Stream file with auto hardware acceleration
175
+ * const stream = await WebRTCStream.create('video.mp4', {
176
+ * hardware: 'auto'
177
+ * });
178
+ * ```
179
+ */
180
+ static create(inputUrl: string, options?: WebRTCStreamOptions): Promise<WebRTCStream>;
181
+ /**
182
+ * Get detected codec information for SDP negotiation.
183
+ *
184
+ * Returns RTP codec parameters and FFmpeg codec IDs for video and audio.
185
+ * Use this information to configure WebRTC peer connections with matching codecs.
186
+ *
187
+ * @returns Codec configuration for video and audio streams
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * const stream = await WebRTCStream.create('input.mp4');
192
+ * const codecs = stream.getCodecs();
193
+ *
194
+ * console.log('Video codec:', codecs.video.mimeType);
195
+ * console.log('Audio codec:', codecs.audio?.mimeType);
196
+ * ```
197
+ */
198
+ getCodecs(): WebRTCCodecInfo;
199
+ /**
200
+ * Start streaming media to RTP packets.
201
+ *
202
+ * Begins the media processing pipeline, reading packets from input,
203
+ * transcoding if necessary, and invoking RTP packet callbacks.
204
+ * Automatically handles video and audio streams in parallel.
205
+ * Flushes all buffers at the end of stream.
206
+ * This method blocks until streaming completes or {@link stop} is called.
207
+ *
208
+ * @returns Promise that resolves when streaming completes
209
+ *
210
+ * @throws {FFmpegError} If transcoding or muxing fails
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * const stream = await WebRTCStream.create('rtsp://camera.local/stream', {
215
+ * onVideoPacket: (rtp) => sendRtp(rtp)
216
+ * });
217
+ *
218
+ * // Start streaming (blocks until complete or stopped)
219
+ * await stream.start();
220
+ * ```
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * // Non-blocking start with background promise
225
+ * const stream = await WebRTCStream.create('input.mp4');
226
+ * const streamPromise = stream.start();
227
+ *
228
+ * // Later: stop streaming
229
+ * stream.stop();
230
+ * await streamPromise;
231
+ * ```
232
+ */
233
+ start(): Promise<void>;
234
+ /**
235
+ * Stop streaming gracefully.
236
+ *
237
+ * Signals the streaming loop to exit after the current packet is processed.
238
+ * Does not immediately close resources - use {@link dispose} for cleanup.
239
+ * Safe to call multiple times.
240
+ *
241
+ * @example
242
+ * ```typescript
243
+ * const stream = await WebRTCStream.create('input.mp4');
244
+ * const streamPromise = stream.start();
245
+ *
246
+ * // Stop after 10 seconds
247
+ * setTimeout(() => stream.stop(), 10000);
248
+ *
249
+ * await streamPromise; // Resolves when stopped
250
+ * stream.dispose();
251
+ * ```
252
+ */
253
+ stop(): void;
254
+ /**
255
+ * Clean up all resources and close the stream.
256
+ *
257
+ * Stops streaming if active and releases all FFmpeg resources including
258
+ * decoders, encoders, filters, outputs, and input. Should be called when
259
+ * done with the stream to prevent memory leaks.
260
+ * Safe to call multiple times.
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * const stream = await WebRTCStream.create('input.mp4');
265
+ * await stream.start();
266
+ * stream.dispose();
267
+ * ```
268
+ *
269
+ * @example
270
+ * ```typescript
271
+ * // Using automatic cleanup
272
+ * {
273
+ * await using stream = await WebRTCStream.create('input.mp4');
274
+ * await stream.start();
275
+ * } // Automatically disposed
276
+ * ```
277
+ */
278
+ dispose(): void;
279
+ /**
280
+ * Check if the given audio codec is compatible with WebRTC.
281
+ *
282
+ * @param codecId - The AVCodecID to check
283
+ *
284
+ * @returns True if the codec is WebRTC compatible, false otherwise
285
+ *
286
+ * @internal
287
+ */
288
+ private isAudioCodecSupported;
289
+ /**
290
+ * Check if the given video codec is compatible with WebRTC.
291
+ *
292
+ * @param codecId - The AVCodecID to check
293
+ *
294
+ * @returns True if the codec is WebRTC compatible, false otherwise
295
+ *
296
+ * @internal
297
+ */
298
+ private isVideoCodecSupported;
299
+ /**
300
+ * Get the audio codec configuration for WebRTC.
301
+ *
302
+ * @param codecId - The AVCodecID of the audio codec
303
+ *
304
+ * @returns An object containing MIME type, clock rate, and channels, or null if unsupported
305
+ *
306
+ * @internal
307
+ */
308
+ private getAudioCodecConfig;
309
+ /**
310
+ * Get the video codec configuration for WebRTC.
311
+ *
312
+ * @param codecId - The AVCodecID of the video codec
313
+ *
314
+ * @returns An object containing MIME type and clock rate, or null if unsupported
315
+ *
316
+ * @internal
317
+ */
318
+ private getVideoCodecConfig;
319
+ /**
320
+ * Flush video encoder pipeline.
321
+ *
322
+ * @param videoStreamIndex - Output video stream index
323
+ *
324
+ * @internal
325
+ */
326
+ private flushVideo;
327
+ /**
328
+ * Flush audio encoder pipeline.
329
+ *
330
+ * @param audioStreamIndex - Output audio stream index
331
+ *
332
+ * @param hasAudio - Whether audio stream exists
333
+ *
334
+ * @internal
335
+ */
336
+ private flushAudio;
337
+ /**
338
+ * Symbol.dispose implementation for automatic cleanup.
339
+ *
340
+ * @internal
341
+ */
342
+ [Symbol.dispose](): void;
343
+ }
344
+ /**
345
+ * Options for configuring WebRTC session with werift integration.
346
+ *
347
+ * Extends WebRTCStreamOptions but excludes RTP packet callbacks since
348
+ * they are automatically handled by the session's media tracks.
349
+ */
350
+ export interface WebRTCSessionOptions extends Omit<WebRTCStreamOptions, 'onVideoPacket' | 'onAudioPacket'> {
351
+ /**
352
+ * ICE servers for NAT traversal and STUN/TURN configuration.
353
+ *
354
+ * @default []
355
+ *
356
+ * @example
357
+ * ```typescript
358
+ * const session = await WebRTCSession.create('input.mp4', {
359
+ * iceServers: [
360
+ * { urls: 'stun:stun.l.google.com:19302' },
361
+ * { urls: 'turn:turn.example.com:3478' }
362
+ * ]
363
+ * });
364
+ * ```
365
+ */
366
+ iceServers?: {
367
+ urls: string;
368
+ }[];
369
+ }
370
+ /**
371
+ * Complete WebRTC session management with werift integration.
372
+ *
373
+ * Provides end-to-end WebRTC streaming with automatic SDP negotiation,
374
+ * ICE candidate handling, and peer connection management.
375
+ * Built on top of {@link WebRTCStream} but handles all WebRTC protocol details.
376
+ * Integrates with werift library for RTCPeerConnection and media track handling.
377
+ * Ideal for building complete WebRTC streaming applications with minimal code.
378
+ *
379
+ * @example
380
+ * ```typescript
381
+ * import { WebRTCSession } from 'node-av/api';
382
+ *
383
+ * // Create session from media source
384
+ * const session = await WebRTCSession.create('rtsp://camera.local/stream', {
385
+ * mtu: 1200,
386
+ * hardware: 'auto',
387
+ * iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
388
+ * });
389
+ *
390
+ * // Setup ICE candidate handler
391
+ * session.onIceCandidate = (candidate) => {
392
+ * sendToClient({ type: 'candidate', value: candidate });
393
+ * };
394
+ *
395
+ * // Process SDP offer from client
396
+ * const answer = await session.setOffer(clientOffer);
397
+ * sendToClient({ type: 'answer', value: answer });
398
+ *
399
+ * // Start streaming
400
+ * await session.start();
401
+ * ```
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * // Complete WebSocket signaling server
406
+ * import { WebSocket } from 'ws';
407
+ *
408
+ * ws.on('message', async (data) => {
409
+ * const msg = JSON.parse(data);
410
+ *
411
+ * if (msg.type === 'offer') {
412
+ * const session = await WebRTCSession.create(msg.url, {
413
+ * hardware: 'auto'
414
+ * });
415
+ *
416
+ * session.onIceCandidate = (candidate) => {
417
+ * ws.send(JSON.stringify({ type: 'candidate', value: candidate }));
418
+ * };
419
+ *
420
+ * const answer = await session.setOffer(msg.value);
421
+ * ws.send(JSON.stringify({ type: 'answer', value: answer }));
422
+ *
423
+ * await session.start();
424
+ * } else if (msg.type === 'candidate') {
425
+ * session.addIceCandidate(msg.value);
426
+ * }
427
+ * });
428
+ * ```
429
+ *
430
+ * @see {@link WebRTCStream} For library-agnostic RTP streaming
431
+ * @see {@link MediaInput} For input media handling
432
+ * @see {@link HardwareContext} For GPU acceleration
433
+ */
434
+ export declare class WebRTCSession implements Disposable {
435
+ private stream;
436
+ private pc;
437
+ private videoTrack;
438
+ private audioTrack;
439
+ private options;
440
+ /**
441
+ * Callback invoked when a new ICE candidate is discovered.
442
+ * Send this candidate to the remote peer via signaling channel.
443
+ *
444
+ * @param candidate - ICE candidate string to send to remote peer
445
+ *
446
+ * @example
447
+ * ```typescript
448
+ * session.onIceCandidate = (candidate) => {
449
+ * ws.send(JSON.stringify({ type: 'candidate', value: candidate }));
450
+ * };
451
+ * ```
452
+ */
453
+ onIceCandidate: ((candidate: string) => void) | null;
454
+ /**
455
+ * @param options - Session configuration options
456
+ *
457
+ * Use {@link create} factory method
458
+ *
459
+ * @internal
460
+ */
461
+ private constructor();
462
+ /**
463
+ * Create a WebRTC session from a media source.
464
+ *
465
+ * Opens the input media, creates internal streaming components, and prepares
466
+ * for WebRTC peer connection negotiation. Does not start streaming yet.
467
+ * Call {@link setOffer} to negotiate SDP and {@link start} to begin streaming.
468
+ *
469
+ * @param inputUrl - Media source URL (RTSP, file path, HTTP, etc.)
470
+ *
471
+ * @param options - Session configuration options
472
+ *
473
+ * @returns Configured WebRTC session instance
474
+ *
475
+ * @throws {Error} If no video stream found in input
476
+ *
477
+ * @throws {FFmpegError} If input cannot be opened
478
+ *
479
+ * @example
480
+ * ```typescript
481
+ * const session = await WebRTCSession.create('rtsp://camera.local/stream', {
482
+ * mtu: 1200,
483
+ * hardware: 'auto',
484
+ * iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
485
+ * });
486
+ * ```
487
+ *
488
+ * @example
489
+ * ```typescript
490
+ * // Session from file with hardware acceleration
491
+ * const session = await WebRTCSession.create('video.mp4', {
492
+ * hardware: {
493
+ * deviceType: AV_HWDEVICE_TYPE_CUDA
494
+ * }
495
+ * });
496
+ * ```
497
+ */
498
+ static create(inputUrl: string, options?: WebRTCSessionOptions): Promise<WebRTCSession>;
499
+ /**
500
+ * Get detected codec information.
501
+ *
502
+ * Returns RTP codec parameters and FFmpeg codec IDs for video and audio.
503
+ * Useful for inspecting what codecs will be used in the WebRTC session.
504
+ *
505
+ * @returns Codec configuration for video and audio streams
506
+ *
507
+ * @throws {Error} If stream not initialized
508
+ *
509
+ * @example
510
+ * ```typescript
511
+ * const session = await WebRTCSession.create('input.mp4');
512
+ * const codecs = session.getCodecs();
513
+ *
514
+ * console.log('Video:', codecs.video.mimeType);
515
+ * console.log('Audio:', codecs.audio?.mimeType);
516
+ * ```
517
+ */
518
+ getCodecs(): WebRTCCodecInfo;
519
+ /**
520
+ * Process SDP offer from remote peer and generate SDP answer.
521
+ *
522
+ * Creates RTCPeerConnection with detected codecs, sets up media tracks,
523
+ * processes the remote SDP offer, and generates a local SDP answer.
524
+ * Also configures ICE candidate handling via {@link onIceCandidate} callback.
525
+ * Must be called before {@link start}.
526
+ *
527
+ * @param offerSdp - SDP offer string from remote WebRTC peer
528
+ *
529
+ * @returns SDP answer string to send back to remote peer
530
+ *
531
+ * @throws {Error} If stream not initialized
532
+ *
533
+ * @example
534
+ * ```typescript
535
+ * const session = await WebRTCSession.create('input.mp4');
536
+ *
537
+ * // Setup ICE candidate handler first
538
+ * session.onIceCandidate = (candidate) => {
539
+ * sendToRemote({ type: 'candidate', value: candidate });
540
+ * };
541
+ *
542
+ * // Process offer and send answer
543
+ * const answer = await session.setOffer(remoteOffer);
544
+ * sendToRemote({ type: 'answer', value: answer });
545
+ * ```
546
+ */
547
+ setOffer(offerSdp: string): Promise<string>;
548
+ /**
549
+ * Add ICE candidate from remote peer.
550
+ *
551
+ * Processes ICE candidates received from the remote peer via signaling channel.
552
+ * Should be called whenever a new candidate message arrives from remote peer.
553
+ * Can be called multiple times as candidates are discovered.
554
+ *
555
+ * @param candidate - ICE candidate string from remote peer
556
+ *
557
+ * @throws {Error} If peer connection not initialized (call {@link setOffer} first)
558
+ *
559
+ * @example
560
+ * ```typescript
561
+ * // In signaling message handler
562
+ * if (msg.type === 'candidate') {
563
+ * session.addIceCandidate(msg.value);
564
+ * }
565
+ * ```
566
+ */
567
+ addIceCandidate(candidate: string): void;
568
+ /**
569
+ * Start streaming media to WebRTC peer connection.
570
+ *
571
+ * Begins the media processing pipeline, reading packets from input,
572
+ * transcoding if necessary, and sending RTP packets to media tracks.
573
+ * Must call {@link setOffer} before starting.
574
+ * This method blocks until streaming completes or {@link stop} is called.
575
+ *
576
+ * @returns Promise that resolves when streaming completes
577
+ *
578
+ * @throws {Error} If stream not initialized
579
+ *
580
+ * @throws {FFmpegError} If transcoding or muxing fails
581
+ *
582
+ * @example
583
+ * ```typescript
584
+ * const session = await WebRTCSession.create('input.mp4');
585
+ * session.onIceCandidate = (c) => sendToRemote(c);
586
+ *
587
+ * const answer = await session.setOffer(remoteOffer);
588
+ * sendToRemote(answer);
589
+ *
590
+ * // Start streaming (blocks until complete)
591
+ * await session.start();
592
+ * ```
593
+ *
594
+ * @example
595
+ * ```typescript
596
+ * // Non-blocking start
597
+ * const session = await WebRTCSession.create('input.mp4');
598
+ * const streamPromise = session.start();
599
+ *
600
+ * // Later: stop streaming
601
+ * session.stop();
602
+ * await streamPromise;
603
+ * ```
604
+ */
605
+ start(): Promise<void>;
606
+ /**
607
+ * Stop streaming gracefully.
608
+ *
609
+ * Signals the streaming loop to exit after the current packet is processed.
610
+ * Does not immediately close resources - use {@link dispose} for cleanup.
611
+ * Safe to call multiple times.
612
+ *
613
+ * @example
614
+ * ```typescript
615
+ * const session = await WebRTCSession.create('input.mp4');
616
+ * const streamPromise = session.start();
617
+ *
618
+ * // Stop after 10 seconds
619
+ * setTimeout(() => session.stop(), 10000);
620
+ *
621
+ * await streamPromise;
622
+ * session.dispose();
623
+ * ```
624
+ */
625
+ stop(): void;
626
+ /**
627
+ * Clean up all resources and close the session.
628
+ *
629
+ * Stops streaming if active, releases all FFmpeg resources, closes peer connection,
630
+ * and cleans up media tracks. Should be called when done with the session to prevent
631
+ * memory leaks. Safe to call multiple times.
632
+ *
633
+ * @example
634
+ * ```typescript
635
+ * const session = await WebRTCSession.create('input.mp4');
636
+ * await session.start();
637
+ * session.dispose();
638
+ * ```
639
+ *
640
+ * @example
641
+ * ```typescript
642
+ * // Using automatic cleanup
643
+ * {
644
+ * await using session = await WebRTCSession.create('input.mp4');
645
+ * await session.start();
646
+ * } // Automatically disposed
647
+ * ```
648
+ */
649
+ dispose(): void;
650
+ /**
651
+ * Symbol.dispose implementation for automatic cleanup.
652
+ *
653
+ * @internal
654
+ */
655
+ [Symbol.dispose](): void;
656
+ }