|
| 1 | +// Not in lib.dom yet. |
| 2 | +interface MediaStreamTrackProcessorCtor { |
| 3 | + new (init: { track: MediaStreamTrack }): { readable: ReadableStream<VideoFrame> }; |
| 4 | +} |
| 5 | +interface MediaStreamTrackGeneratorCtor { |
| 6 | + new (init: { kind: "video" }): MediaStreamTrack & { writable: WritableStream<VideoFrame> }; |
| 7 | +} |
| 8 | + |
| 9 | +type FlipImpl = "track-processor" | "canvas" | "noop"; |
| 10 | + |
| 11 | +export interface MirroredStreamOptions { |
| 12 | + fps: number; |
| 13 | +} |
| 14 | + |
| 15 | +export interface MirroredStream { |
| 16 | + stream: MediaStream; |
| 17 | + dispose: () => void; |
| 18 | + impl: FlipImpl; |
| 19 | +} |
| 20 | + |
| 21 | +export function isMediaStreamTrackProcessorSupported(): boolean { |
| 22 | + return ( |
| 23 | + typeof globalThis !== "undefined" && |
| 24 | + typeof (globalThis as { MediaStreamTrackProcessor?: unknown }).MediaStreamTrackProcessor === "function" && |
| 25 | + typeof (globalThis as { MediaStreamTrackGenerator?: unknown }).MediaStreamTrackGenerator === "function" |
| 26 | + ); |
| 27 | +} |
| 28 | + |
| 29 | +export function shouldMirrorTrack(track: MediaStreamTrack): boolean { |
| 30 | + if (track.kind !== "video") return false; |
| 31 | + let facingMode: string | undefined; |
| 32 | + try { |
| 33 | + facingMode = track.getSettings?.().facingMode; |
| 34 | + } catch { |
| 35 | + return false; |
| 36 | + } |
| 37 | + return facingMode === "user"; |
| 38 | +} |
| 39 | + |
| 40 | +export function createMirroredStream(input: MediaStream, opts: MirroredStreamOptions): MirroredStream { |
| 41 | + const [sourceVideo] = input.getVideoTracks(); |
| 42 | + const audioTracks = input.getAudioTracks(); |
| 43 | + |
| 44 | + if (!sourceVideo) { |
| 45 | + return { stream: input, dispose: () => {}, impl: "noop" }; |
| 46 | + } |
| 47 | + |
| 48 | + if (isMediaStreamTrackProcessorSupported()) { |
| 49 | + return createWithTrackProcessor(sourceVideo, audioTracks); |
| 50 | + } |
| 51 | + return createWithCanvas(sourceVideo, audioTracks, opts.fps); |
| 52 | +} |
| 53 | + |
| 54 | +function createWithTrackProcessor(sourceVideo: MediaStreamTrack, audioTracks: MediaStreamTrack[]): MirroredStream { |
| 55 | + const Processor = (globalThis as unknown as { MediaStreamTrackProcessor: MediaStreamTrackProcessorCtor }) |
| 56 | + .MediaStreamTrackProcessor; |
| 57 | + const Generator = (globalThis as unknown as { MediaStreamTrackGenerator: MediaStreamTrackGeneratorCtor }) |
| 58 | + .MediaStreamTrackGenerator; |
| 59 | + |
| 60 | + // Probe 2D context at setup so we fail loud here rather than silently |
| 61 | + // passing un-flipped frames through the pipeline. |
| 62 | + if (!new OffscreenCanvas(1, 1).getContext("2d")) { |
| 63 | + throw new Error("createMirroredStream: OffscreenCanvas 2D context unavailable"); |
| 64 | + } |
| 65 | + |
| 66 | + const processor = new Processor({ track: sourceVideo }); |
| 67 | + const generator = new Generator({ kind: "video" }); |
| 68 | + |
| 69 | + let canvas = new OffscreenCanvas(1, 1); |
| 70 | + let ctx = canvas.getContext("2d") as OffscreenCanvasRenderingContext2D; |
| 71 | + |
| 72 | + const transform = new TransformStream<VideoFrame, VideoFrame>({ |
| 73 | + transform(frame, controller) { |
| 74 | + const w = frame.displayWidth; |
| 75 | + const h = frame.displayHeight; |
| 76 | + if (canvas.width !== w || canvas.height !== h) { |
| 77 | + canvas = new OffscreenCanvas(w, h); |
| 78 | + ctx = canvas.getContext("2d") as OffscreenCanvasRenderingContext2D; |
| 79 | + } |
| 80 | + |
| 81 | + // VideoFrames hold GPU buffers; close them deterministically even if |
| 82 | + // VideoFrame construction or enqueue throws. |
| 83 | + let flipped: VideoFrame | undefined; |
| 84 | + try { |
| 85 | + ctx.save(); |
| 86 | + ctx.setTransform(-1, 0, 0, 1, w, 0); |
| 87 | + ctx.drawImage(frame, 0, 0, w, h); |
| 88 | + ctx.restore(); |
| 89 | + flipped = new VideoFrame(canvas, { timestamp: frame.timestamp, alpha: "discard" }); |
| 90 | + controller.enqueue(flipped); |
| 91 | + flipped = undefined; |
| 92 | + } finally { |
| 93 | + flipped?.close(); |
| 94 | + frame.close(); |
| 95 | + } |
| 96 | + }, |
| 97 | + }); |
| 98 | + |
| 99 | + processor.readable |
| 100 | + .pipeThrough(transform) |
| 101 | + .pipeTo(generator.writable) |
| 102 | + .catch(() => {}); |
| 103 | + |
| 104 | + const stream = new MediaStream([generator, ...audioTracks]); |
| 105 | + |
| 106 | + let disposed = false; |
| 107 | + return { |
| 108 | + stream, |
| 109 | + impl: "track-processor", |
| 110 | + dispose: () => { |
| 111 | + if (disposed) return; |
| 112 | + disposed = true; |
| 113 | + generator.stop(); |
| 114 | + }, |
| 115 | + }; |
| 116 | +} |
| 117 | + |
| 118 | +function createWithCanvas(sourceVideo: MediaStreamTrack, audioTracks: MediaStreamTrack[], fps: number): MirroredStream { |
| 119 | + if (typeof document === "undefined") { |
| 120 | + throw new Error("createMirroredStream requires a DOM environment (document is undefined)"); |
| 121 | + } |
| 122 | + |
| 123 | + const canvas = document.createElement("canvas"); |
| 124 | + const ctx = canvas.getContext("2d"); |
| 125 | + if (!ctx) { |
| 126 | + throw new Error("createMirroredStream: 2D canvas context unavailable"); |
| 127 | + } |
| 128 | + |
| 129 | + // Resolve the output track before kicking off playback / rAF, so a missing |
| 130 | + // captureStream API doesn't leave background work running. |
| 131 | + if (typeof canvas.captureStream !== "function") { |
| 132 | + throw new Error("createMirroredStream: canvas.captureStream unavailable"); |
| 133 | + } |
| 134 | + const [flippedTrack] = canvas.captureStream(fps).getVideoTracks(); |
| 135 | + if (!flippedTrack) { |
| 136 | + throw new Error("createMirroredStream: canvas.captureStream produced no video track"); |
| 137 | + } |
| 138 | + |
| 139 | + const video = document.createElement("video"); |
| 140 | + video.muted = true; |
| 141 | + video.playsInline = true; |
| 142 | + video.autoplay = true; |
| 143 | + video.srcObject = new MediaStream([sourceVideo]); |
| 144 | + |
| 145 | + let disposed = false; |
| 146 | + let rafHandle: number | null = null; |
| 147 | + |
| 148 | + const draw = () => { |
| 149 | + if (disposed) return; |
| 150 | + const w = video.videoWidth; |
| 151 | + const h = video.videoHeight; |
| 152 | + if (w > 0 && h > 0) { |
| 153 | + if (canvas.width !== w) canvas.width = w; |
| 154 | + if (canvas.height !== h) canvas.height = h; |
| 155 | + ctx.save(); |
| 156 | + ctx.setTransform(-1, 0, 0, 1, w, 0); |
| 157 | + ctx.drawImage(video, 0, 0, w, h); |
| 158 | + ctx.restore(); |
| 159 | + } |
| 160 | + rafHandle = requestAnimationFrame(draw); |
| 161 | + }; |
| 162 | + |
| 163 | + void video.play().catch(() => {}); |
| 164 | + rafHandle = requestAnimationFrame(draw); |
| 165 | + |
| 166 | + return { |
| 167 | + stream: new MediaStream([flippedTrack, ...audioTracks]), |
| 168 | + impl: "canvas", |
| 169 | + dispose: () => { |
| 170 | + if (disposed) return; |
| 171 | + disposed = true; |
| 172 | + if (rafHandle !== null) cancelAnimationFrame(rafHandle); |
| 173 | + flippedTrack.stop(); |
| 174 | + video.srcObject = null; |
| 175 | + }, |
| 176 | + }; |
| 177 | +} |
0 commit comments