Skip to content

Open source CapCut alternative.

TypeScript
71.9 KB
Raw Blame
diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.cjs b/node_modules/mediabunny/dist/bundles/mediabunny.cjs
index f984c84..cf6c6e2 100644
--- a/node_modules/mediabunny/dist/bundles/mediabunny.cjs
+++ b/node_modules/mediabunny/dist/bundles/mediabunny.cjs
@@ -12381,6 +12381,21 @@ var Mediabunny = (() => {
                 frameCount: flags & 1 /* FrameCount */ ? view2.getUint32(4, false) : null,
                 fileSize: flags & 2 /* FileSize */ ? view2.getUint32(8, false) : null
               };
+              // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
+              // holds the encoder delay, and the decoder adds 529 samples of priming on
+              // top. The audio starts after both, as ffmpeg plays it, so the first
+              // frames carry negative timestamps.
+              const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
+              let tagSlice = this.reader.requestSlice(tagAt, 24);
+              if (isThenable(tagSlice)) tagSlice = await tagSlice;
+              if (tagSlice && this.nextTimestampInSamples === 0) {
+                const tag = readBytes(tagSlice, 24);
+                const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
+                if (id === "LAME" || id === "Lavf" || id === "Lavc") {
+                  const delay = (tag[21] << 4) | (tag[22] >> 4);
+                  this.nextTimestampInSamples = -(delay + 529);
+                }
+              }
             }
           }
           return;
@@ -24351,13 +24366,17 @@ var Mediabunny = (() => {
         verifyKeyPackets: true,
         metadataOnly: false
       };
+      // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+      const wakeOnDispose = () => onQueueDequeue();
+      (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
       (async () => {
         decoder = await this._createDecoder((sample) => {
           onQueueDequeue();
           if (sample.timestamp >= endTimestamp) {
             ended = true;
           }
-          if (ended) {
+          // A sample decoded after the input was disposed has no reader left (Donkey patch).
+          if (ended || this._track.input._disposed) {
             sample.close();
             return;
           }
@@ -24422,6 +24441,12 @@ var Mediabunny = (() => {
         }
       }).finally(() => {
         decoder?.close();
+        this._track.input._disposeWakers?.delete(wakeOnDispose);
+        // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+        // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+        if (this._track.input._disposed) {
+          closeSamples();
+        }
       });
       const track = this._track;
       const closeSamples = () => {
@@ -24437,6 +24462,9 @@ var Mediabunny = (() => {
               terminated = true;
               ended = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw new InputDisposedError();
             } else if (terminated) {
               return { value: void 0, done: true };
@@ -24444,6 +24472,9 @@ var Mediabunny = (() => {
               terminated = true;
               ended = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw outOfBandError;
             } else if (sampleQueue.length > 0) {
               const value = sampleQueue.shift();
@@ -24495,10 +24526,14 @@ var Mediabunny = (() => {
         verifyKeyPackets: true,
         metadataOnly: false
       };
+      // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+      const wakeOnDispose = () => onQueueDequeue();
+      (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
       (async () => {
         decoder = await this._createDecoder((sample) => {
           onQueueDequeue();
-          if (terminated) {
+          // A sample decoded after the input was disposed has no reader left (Donkey patch).
+          if (terminated || this._track.input._disposed) {
             sample.close();
             return;
           }
@@ -24532,11 +24567,11 @@ var Mediabunny = (() => {
           decoder.decode(currentPacket);
           while (currentPacket.sequenceNumber < maxSequenceNumber) {
             const maxQueueSize = computeMaxQueueSize(sampleQueue.length);
-            while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated) {
+            while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated && !this._track.input._disposed) {
               ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());
               await queueDequeue;
             }
-            if (terminated) {
+            if (terminated || this._track.input._disposed) {
               break;
             }
             const nextPacket = await packetSink.getNextPacket(currentPacket, retrievalOptions);
@@ -24595,6 +24630,12 @@ var Mediabunny = (() => {
         }
       }).finally(() => {
         decoder?.close();
+        this._track.input._disposeWakers?.delete(wakeOnDispose);
+        // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+        // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+        if (this._track.input._disposed) {
+          closeSamples();
+        }
       });
       const track = this._track;
       const closeSamples = () => {
@@ -24608,12 +24649,18 @@ var Mediabunny = (() => {
             if (track.input._disposed) {
               terminated = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw new InputDisposedError();
             } else if (terminated) {
               return { value: void 0, done: true };
             } else if (hasOutOfBandError) {
               terminated = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw outOfBandError;
             } else if (sampleQueue.length > 0) {
               const value = sampleQueue.shift();
@@ -24644,11 +24691,13 @@ var Mediabunny = (() => {
     }
   };
   var computeMaxQueueSize = (decodedSampleQueueSize) => {
-    return decodedSampleQueueSize === 0 ? 40 : 8;
+    return decodedSampleQueueSize === 0 ? 16 : 8;
   };
   var VideoDecoderWrapper = class extends DecoderWrapper {
-    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution) {
+    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride = null, transformPacket = null) {
       super(onSample, onError);
+      // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.
+      this.transformPacket = transformPacket;
       this.codec = codec;
       this.decoderConfig = decoderConfig;
       this.rotation = rotation;
@@ -24658,6 +24707,13 @@ var Mediabunny = (() => {
       this.customDecoder = null;
       this.customDecoderCallSerializer = new CallSerializer();
       this.customDecoderQueueSize = 0;
+      // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the
+      // samples a custom decoder produces (see restampSample).
+      this.colorSpaceOverride = colorSpaceOverride;
+      this.restampBuffer = null; // Reused across restamps, sized on the first frame.
+      this.restampChain = Promise.resolve(); // Restamps in emission order.
+      this.restampsInFlight = 0;
+      this.inFlight = 0; // Packets sent to the decoder whose frames have not come back yet.
       this.inputTimestamps = [];
       // Timestamps input into the decoder, sorted.
       this.sampleQueue = [];
@@ -24689,6 +24745,17 @@ var Mediabunny = (() => {
           if (!(sample instanceof VideoSample)) {
             throw new TypeError("The argument passed to onSample must be a VideoSample.");
           }
+          if (this.colorSpaceOverride) {
+            // A custom decoder tags its samples from the bitstream. The override replaces that tag so the
+            // sample draws the way a WebCodecs frame configured with the same color space does. The restamp
+            // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the
+            // ones still copying, and a flush waits for the chain to drain.
+            this.restampsInFlight++;
+            this.restampChain = this.restampChain.then(() => this.restampSample(sample)).then((restamped) => this.finalizeAndEmitSample(restamped), (error) => onError(error)).finally(() => {
+              this.restampsInFlight--;
+            });
+            return;
+          }
           this.finalizeAndEmitSample(sample);
         };
         this.customDecoder.onError = (error) => {
@@ -24744,6 +24811,7 @@ var Mediabunny = (() => {
         const stack = new Error("Decoding error").stack;
         this.decoder = new VideoDecoder({
           output: (frame) => {
+            this.inFlight = Math.max(0, this.inFlight - 1);
             try {
               colorHandler(frame);
             } catch (error) {
@@ -24760,13 +24828,10 @@ var Mediabunny = (() => {
     }
     getDecodeQueueSize() {
       if (this.customDecoder) {
-        return this.customDecoderQueueSize;
+        return this.customDecoderQueueSize + this.restampsInFlight;
       } else {
         assert(this.decoder);
-        return Math.max(
-          this.decoder.decodeQueueSize,
-          this.alphaDecoder?.decodeQueueSize ?? 0
-        );
+        return Math.max(this.inFlight, this.alphaDecoder?.decodeQueueSize ?? 0);
       }
     }
     decode(packet) {
@@ -24824,6 +24889,13 @@ var Mediabunny = (() => {
             }
           }
         }
+        if (this.transformPacket) {
+            const transformed = this.transformPacket(packet.data, this.decoderConfig);
+            if (transformed) {
+                packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);
+            }
+        }
+        this.inFlight++;
         this.decoder.decode(packet.toEncodedVideoChunk());
         this.decodeAlphaData(packet);
       }
@@ -24940,6 +25012,49 @@ var Mediabunny = (() => {
       sample.setFlip(this.flip);
       this.onSample(sample);
     }
+    /**
+     * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:
+     * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,
+     * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.
+     */
+    async restampSample(sample) {
+      const override = this.colorSpaceOverride;
+      assert(override);
+      const data = sample._data;
+      if (!(typeof VideoFrame !== "undefined" && data instanceof VideoFrame)) {
+        sample.colorSpace = new VideoSampleColorSpace(override);
+        return sample;
+      }
+      if (data.format === null) {
+        return sample;
+      }
+      const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };
+      const size = data.allocationSize({ rect });
+      if (!this.restampBuffer || this.restampBuffer.byteLength < size) {
+        this.restampBuffer = new ArrayBuffer(size);
+      }
+      // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.
+      const { timestamp, duration, rotation } = sample;
+      let restamped;
+      try {
+        const layout = await data.copyTo(this.restampBuffer, { rect });
+        restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {
+          format: data.format,
+          codedWidth: data.codedWidth,
+          codedHeight: data.codedHeight,
+          layout,
+          visibleRect: data.visibleRect ?? void 0,
+          displayWidth: data.displayWidth,
+          displayHeight: data.displayHeight,
+          timestamp: data.timestamp,
+          duration: data.duration ?? void 0,
+          colorSpace: override
+        });
+      } finally {
+        sample.close();
+      }
+      return new VideoSample(restamped, { timestamp, duration, rotation });
+    }
     async mergeAlpha(color, alpha) {
       const resolver = promiseWithResolvers();
       this.mergeAlphaPromises.push(resolver.promise);
@@ -24968,6 +25083,11 @@ var Mediabunny = (() => {
     async flush() {
       if (this.customDecoder) {
         await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
+        // A custom decoder may hand out its last samples a microtask after its flush resolves (the same
+        // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.
+        do {
+          await this.restampChain;
+        } while (this.restampsInFlight > 0);
       } else {
         assert(this.decoder);
         await Promise.all([
@@ -24992,6 +25112,7 @@ var Mediabunny = (() => {
         }
         this.sampleQueue.length = 0;
       }
+      this.inFlight = 0;
       this.currentPacketIndex = 0;
       this.raslSkipped = false;
     }
@@ -25248,6 +25369,18 @@ var Mediabunny = (() => {
     if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {
       throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");
     }
+    if (decoderOptions.colorSpace !== void 0) {
+      if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== "object") {
+        throw new TypeError("decoderOptions.colorSpace, when provided, must be an object.");
+      }
+      new VideoSampleColorSpace(decoderOptions.colorSpace);
+    }
+    if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== "function") {
+        throw new TypeError("decoderOptions.transformConfig, when provided, must be a function.");
+    }
+    if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== "function") {
+        throw new TypeError("decoderOptions.transformPacket, when provided, must be a function.");
+    }
   };
   var VideoSampleSink = class extends BaseMediaSampleSink {
     /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */
@@ -25276,12 +25409,19 @@ var Mediabunny = (() => {
       let decoderConfig = await this._track.getDecoderConfig();
       const timeResolution = await this._track.getTimeResolution();
       assert(codec && decoderConfig);
+      const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;
       decoderConfig = {
         ...decoderConfig,
         hardwareAcceleration: this._decoderOptions.hardwareAcceleration,
-        optimizeForLatency: this._decoderOptions.optimizeForLatency
+        optimizeForLatency: this._decoderOptions.optimizeForLatency,
+        // The override replaces whatever the track carries, so the decoder emits frames tagged the way the
+        // caller asked, in-band tags included.
+        ...colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}
       };
-      return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution);
+      if (this._decoderOptions.transformConfig) {
+          decoderConfig = this._decoderOptions.transformConfig(decoderConfig);
+      }
+      return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);
     }
     /** @internal */
     _createPacketSink() {
@@ -27342,6 +27482,10 @@ var Mediabunny = (() => {
         return;
       }
       this._disposed = true;
+      // Wake the decode pumps parked on this input (Donkey patch): each unwinds and closes what it queued.
+      for (const wake of this._disposeWakers ?? []) {
+        wake();
+      }
       for (const ref of this._sourceRefs) {
         ref.free();
       }
diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.mjs b/node_modules/mediabunny/dist/bundles/mediabunny.mjs
index e675b1f..b12529a 100644
--- a/node_modules/mediabunny/dist/bundles/mediabunny.mjs
+++ b/node_modules/mediabunny/dist/bundles/mediabunny.mjs
@@ -12224,6 +12224,21 @@ var Mp3Demuxer = class extends Demuxer {
               frameCount: flags & 1 /* FrameCount */ ? view2.getUint32(4, false) : null,
               fileSize: flags & 2 /* FileSize */ ? view2.getUint32(8, false) : null
             };
+            // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
+            // holds the encoder delay, and the decoder adds 529 samples of priming on
+            // top. The audio starts after both, as ffmpeg plays it, so the first
+            // frames carry negative timestamps.
+            const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
+            let tagSlice = this.reader.requestSlice(tagAt, 24);
+            if (isThenable(tagSlice)) tagSlice = await tagSlice;
+            if (tagSlice && this.nextTimestampInSamples === 0) {
+              const tag = readBytes(tagSlice, 24);
+              const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
+              if (id === "LAME" || id === "Lavf" || id === "Lavc") {
+                const delay = (tag[21] << 4) | (tag[22] >> 4);
+                this.nextTimestampInSamples = -(delay + 529);
+              }
+            }
           }
         }
         return;
@@ -24194,13 +24209,17 @@ var BaseMediaSampleSink = class {
       verifyKeyPackets: true,
       metadataOnly: false
     };
+    // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+    const wakeOnDispose = () => onQueueDequeue();
+    (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
     (async () => {
       decoder = await this._createDecoder((sample) => {
         onQueueDequeue();
         if (sample.timestamp >= endTimestamp) {
           ended = true;
         }
-        if (ended) {
+        // A sample decoded after the input was disposed has no reader left (Donkey patch).
+        if (ended || this._track.input._disposed) {
           sample.close();
           return;
         }
@@ -24265,6 +24284,12 @@ var BaseMediaSampleSink = class {
       }
     }).finally(() => {
       decoder?.close();
+      this._track.input._disposeWakers?.delete(wakeOnDispose);
+      // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+      // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+      if (this._track.input._disposed) {
+        closeSamples();
+      }
     });
     const track = this._track;
     const closeSamples = () => {
@@ -24280,6 +24305,9 @@ var BaseMediaSampleSink = class {
             terminated = true;
             ended = true;
             closeSamples();
+            // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+            // decoder, which closes the frames it still holds (WebKit's reorder queue).
+            onQueueDequeue();
             throw new InputDisposedError();
           } else if (terminated) {
             return { value: void 0, done: true };
@@ -24287,6 +24315,9 @@ var BaseMediaSampleSink = class {
             terminated = true;
             ended = true;
             closeSamples();
+            // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+            // decoder, which closes the frames it still holds (WebKit's reorder queue).
+            onQueueDequeue();
             throw outOfBandError;
           } else if (sampleQueue.length > 0) {
             const value = sampleQueue.shift();
@@ -24338,10 +24369,14 @@ var BaseMediaSampleSink = class {
       verifyKeyPackets: true,
       metadataOnly: false
     };
+    // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+    const wakeOnDispose = () => onQueueDequeue();
+    (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
     (async () => {
       decoder = await this._createDecoder((sample) => {
         onQueueDequeue();
-        if (terminated) {
+        // A sample decoded after the input was disposed has no reader left (Donkey patch).
+        if (terminated || this._track.input._disposed) {
           sample.close();
           return;
         }
@@ -24375,11 +24410,11 @@ var BaseMediaSampleSink = class {
         decoder.decode(currentPacket);
         while (currentPacket.sequenceNumber < maxSequenceNumber) {
           const maxQueueSize = computeMaxQueueSize(sampleQueue.length);
-          while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated) {
+          while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated && !this._track.input._disposed) {
             ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());
             await queueDequeue;
           }
-          if (terminated) {
+          if (terminated || this._track.input._disposed) {
             break;
           }
           const nextPacket = await packetSink.getNextPacket(currentPacket, retrievalOptions);
@@ -24438,6 +24473,12 @@ var BaseMediaSampleSink = class {
       }
     }).finally(() => {
       decoder?.close();
+      this._track.input._disposeWakers?.delete(wakeOnDispose);
+      // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+      // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+      if (this._track.input._disposed) {
+        closeSamples();
+      }
     });
     const track = this._track;
     const closeSamples = () => {
@@ -24451,12 +24492,18 @@ var BaseMediaSampleSink = class {
           if (track.input._disposed) {
             terminated = true;
             closeSamples();
+            // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+            // decoder, which closes the frames it still holds (WebKit's reorder queue).
+            onQueueDequeue();
             throw new InputDisposedError();
           } else if (terminated) {
             return { value: void 0, done: true };
           } else if (hasOutOfBandError) {
             terminated = true;
             closeSamples();
+            // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+            // decoder, which closes the frames it still holds (WebKit's reorder queue).
+            onQueueDequeue();
             throw outOfBandError;
           } else if (sampleQueue.length > 0) {
             const value = sampleQueue.shift();
@@ -24487,11 +24534,13 @@ var BaseMediaSampleSink = class {
   }
 };
 var computeMaxQueueSize = (decodedSampleQueueSize) => {
-  return decodedSampleQueueSize === 0 ? 40 : 8;
+  return decodedSampleQueueSize === 0 ? 16 : 8;
 };
 var VideoDecoderWrapper = class extends DecoderWrapper {
-  constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution) {
+  constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride = null, transformPacket = null) {
     super(onSample, onError);
+    // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.
+    this.transformPacket = transformPacket;
     this.codec = codec;
     this.decoderConfig = decoderConfig;
     this.rotation = rotation;
@@ -24501,6 +24550,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
     this.customDecoder = null;
     this.customDecoderCallSerializer = new CallSerializer();
     this.customDecoderQueueSize = 0;
+    // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the
+    // samples a custom decoder produces (see restampSample).
+    this.colorSpaceOverride = colorSpaceOverride;
+    this.restampBuffer = null; // Reused across restamps, sized on the first frame.
+    this.restampChain = Promise.resolve(); // Restamps in emission order.
+    this.restampsInFlight = 0;
+    this.inFlight = 0; // Packets sent to the decoder whose frames have not come back yet.
     this.inputTimestamps = [];
     // Timestamps input into the decoder, sorted.
     this.sampleQueue = [];
@@ -24532,6 +24588,17 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
         if (!(sample instanceof VideoSample)) {
           throw new TypeError("The argument passed to onSample must be a VideoSample.");
         }
+        if (this.colorSpaceOverride) {
+          // A custom decoder tags its samples from the bitstream. The override replaces that tag so the
+          // sample draws the way a WebCodecs frame configured with the same color space does. The restamp
+          // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the
+          // ones still copying, and a flush waits for the chain to drain.
+          this.restampsInFlight++;
+          this.restampChain = this.restampChain.then(() => this.restampSample(sample)).then((restamped) => this.finalizeAndEmitSample(restamped), (error) => onError(error)).finally(() => {
+            this.restampsInFlight--;
+          });
+          return;
+        }
         this.finalizeAndEmitSample(sample);
       };
       this.customDecoder.onError = (error) => {
@@ -24587,6 +24654,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
       const stack = new Error("Decoding error").stack;
       this.decoder = new VideoDecoder({
         output: (frame) => {
+          this.inFlight = Math.max(0, this.inFlight - 1);
           try {
             colorHandler(frame);
           } catch (error) {
@@ -24603,13 +24671,10 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
   }
   getDecodeQueueSize() {
     if (this.customDecoder) {
-      return this.customDecoderQueueSize;
+      return this.customDecoderQueueSize + this.restampsInFlight;
     } else {
       assert(this.decoder);
-      return Math.max(
-        this.decoder.decodeQueueSize,
-        this.alphaDecoder?.decodeQueueSize ?? 0
-      );
+      return Math.max(this.inFlight, this.alphaDecoder?.decodeQueueSize ?? 0);
     }
   }
   decode(packet) {
@@ -24667,6 +24732,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
           }
         }
       }
+      if (this.transformPacket) {
+          const transformed = this.transformPacket(packet.data, this.decoderConfig);
+          if (transformed) {
+              packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);
+          }
+      }
+      this.inFlight++;
       this.decoder.decode(packet.toEncodedVideoChunk());
       this.decodeAlphaData(packet);
     }
@@ -24783,6 +24855,49 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
     sample.setFlip(this.flip);
     this.onSample(sample);
   }
+  /**
+   * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:
+   * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,
+   * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.
+   */
+  async restampSample(sample) {
+    const override = this.colorSpaceOverride;
+    assert(override);
+    const data = sample._data;
+    if (!(typeof VideoFrame !== "undefined" && data instanceof VideoFrame)) {
+      sample.colorSpace = new VideoSampleColorSpace(override);
+      return sample;
+    }
+    if (data.format === null) {
+      return sample;
+    }
+    const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };
+    const size = data.allocationSize({ rect });
+    if (!this.restampBuffer || this.restampBuffer.byteLength < size) {
+      this.restampBuffer = new ArrayBuffer(size);
+    }
+    // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.
+    const { timestamp, duration, rotation } = sample;
+    let restamped;
+    try {
+      const layout = await data.copyTo(this.restampBuffer, { rect });
+      restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {
+        format: data.format,
+        codedWidth: data.codedWidth,
+        codedHeight: data.codedHeight,
+        layout,
+        visibleRect: data.visibleRect ?? void 0,
+        displayWidth: data.displayWidth,
+        displayHeight: data.displayHeight,
+        timestamp: data.timestamp,
+        duration: data.duration ?? void 0,
+        colorSpace: override
+      });
+    } finally {
+      sample.close();
+    }
+    return new VideoSample(restamped, { timestamp, duration, rotation });
+  }
   async mergeAlpha(color, alpha) {
     const resolver = promiseWithResolvers();
     this.mergeAlphaPromises.push(resolver.promise);
@@ -24811,6 +24926,11 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
   async flush() {
     if (this.customDecoder) {
       await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
+      // A custom decoder may hand out its last samples a microtask after its flush resolves (the same
+      // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.
+      do {
+        await this.restampChain;
+      } while (this.restampsInFlight > 0);
     } else {
       assert(this.decoder);
       await Promise.all([
@@ -24835,6 +24955,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
       }
       this.sampleQueue.length = 0;
     }
+    this.inFlight = 0;
     this.currentPacketIndex = 0;
     this.raslSkipped = false;
   }
@@ -25091,6 +25212,18 @@ var validateVideoSinkDecoderOptions = (decoderOptions) => {
   if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {
     throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");
   }
+  if (decoderOptions.colorSpace !== void 0) {
+    if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== "object") {
+      throw new TypeError("decoderOptions.colorSpace, when provided, must be an object.");
+    }
+    new VideoSampleColorSpace(decoderOptions.colorSpace);
+  }
+  if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== "function") {
+      throw new TypeError("decoderOptions.transformConfig, when provided, must be a function.");
+  }
+  if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== "function") {
+      throw new TypeError("decoderOptions.transformPacket, when provided, must be a function.");
+  }
 };
 var VideoSampleSink = class extends BaseMediaSampleSink {
   /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */
@@ -25119,12 +25252,19 @@ var VideoSampleSink = class extends BaseMediaSampleSink {
     let decoderConfig = await this._track.getDecoderConfig();
     const timeResolution = await this._track.getTimeResolution();
     assert(codec && decoderConfig);
+    const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;
     decoderConfig = {
       ...decoderConfig,
       hardwareAcceleration: this._decoderOptions.hardwareAcceleration,
-      optimizeForLatency: this._decoderOptions.optimizeForLatency
+      optimizeForLatency: this._decoderOptions.optimizeForLatency,
+      // The override replaces whatever the track carries, so the decoder emits frames tagged the way the
+      // caller asked, in-band tags included.
+      ...colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}
     };
-    return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution);
+    if (this._decoderOptions.transformConfig) {
+        decoderConfig = this._decoderOptions.transformConfig(decoderConfig);
+    }
+    return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);
   }
   /** @internal */
   _createPacketSink() {
@@ -27185,6 +27325,10 @@ var Input = class _Input extends EventEmitter {
       return;
     }
     this._disposed = true;
+    // Wake the decode pumps parked on this input (Donkey patch): each unwinds and closes what it queued.
+    for (const wake of this._disposeWakers ?? []) {
+      wake();
+    }
     for (const ref of this._sourceRefs) {
       ref.free();
     }
diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs b/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs
index c828e19..26b13d6 100644
--- a/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs
+++ b/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs
@@ -12378,6 +12378,21 @@ var Mediabunny = (() => {
                 frameCount: flags & 1 /* FrameCount */ ? view2.getUint32(4, false) : null,
                 fileSize: flags & 2 /* FileSize */ ? view2.getUint32(8, false) : null
               };
+              // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
+              // holds the encoder delay, and the decoder adds 529 samples of priming on
+              // top. The audio starts after both, as ffmpeg plays it, so the first
+              // frames carry negative timestamps.
+              const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
+              let tagSlice = this.reader.requestSlice(tagAt, 24);
+              if (isThenable(tagSlice)) tagSlice = await tagSlice;
+              if (tagSlice && this.nextTimestampInSamples === 0) {
+                const tag = readBytes(tagSlice, 24);
+                const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
+                if (id === "LAME" || id === "Lavf" || id === "Lavc") {
+                  const delay = (tag[21] << 4) | (tag[22] >> 4);
+                  this.nextTimestampInSamples = -(delay + 529);
+                }
+              }
             }
           }
           return;
@@ -24354,13 +24369,17 @@ var Mediabunny = (() => {
         verifyKeyPackets: true,
         metadataOnly: false
       };
+      // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+      const wakeOnDispose = () => onQueueDequeue();
+      (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
       (async () => {
         decoder = await this._createDecoder((sample) => {
           onQueueDequeue();
           if (sample.timestamp >= endTimestamp) {
             ended = true;
           }
-          if (ended) {
+          // A sample decoded after the input was disposed has no reader left (Donkey patch).
+          if (ended || this._track.input._disposed) {
             sample.close();
             return;
           }
@@ -24425,6 +24444,12 @@ var Mediabunny = (() => {
         }
       }).finally(() => {
         decoder?.close();
+        this._track.input._disposeWakers?.delete(wakeOnDispose);
+        // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+        // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+        if (this._track.input._disposed) {
+          closeSamples();
+        }
       });
       const track = this._track;
       const closeSamples = () => {
@@ -24440,6 +24465,9 @@ var Mediabunny = (() => {
               terminated = true;
               ended = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw new InputDisposedError();
             } else if (terminated) {
               return { value: void 0, done: true };
@@ -24447,6 +24475,9 @@ var Mediabunny = (() => {
               terminated = true;
               ended = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw outOfBandError;
             } else if (sampleQueue.length > 0) {
               const value = sampleQueue.shift();
@@ -24498,10 +24529,14 @@ var Mediabunny = (() => {
         verifyKeyPackets: true,
         metadataOnly: false
       };
+      // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+      const wakeOnDispose = () => onQueueDequeue();
+      (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
       (async () => {
         decoder = await this._createDecoder((sample) => {
           onQueueDequeue();
-          if (terminated) {
+          // A sample decoded after the input was disposed has no reader left (Donkey patch).
+          if (terminated || this._track.input._disposed) {
             sample.close();
             return;
           }
@@ -24535,11 +24570,11 @@ var Mediabunny = (() => {
           decoder.decode(currentPacket);
           while (currentPacket.sequenceNumber < maxSequenceNumber) {
             const maxQueueSize = computeMaxQueueSize(sampleQueue.length);
-            while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated) {
+            while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated && !this._track.input._disposed) {
               ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());
               await queueDequeue;
             }
-            if (terminated) {
+            if (terminated || this._track.input._disposed) {
               break;
             }
             const nextPacket = await packetSink.getNextPacket(currentPacket, retrievalOptions);
@@ -24598,6 +24633,12 @@ var Mediabunny = (() => {
         }
       }).finally(() => {
         decoder?.close();
+        this._track.input._disposeWakers?.delete(wakeOnDispose);
+        // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+        // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+        if (this._track.input._disposed) {
+          closeSamples();
+        }
       });
       const track = this._track;
       const closeSamples = () => {
@@ -24611,12 +24652,18 @@ var Mediabunny = (() => {
             if (track.input._disposed) {
               terminated = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw new InputDisposedError();
             } else if (terminated) {
               return { value: void 0, done: true };
             } else if (hasOutOfBandError) {
               terminated = true;
               closeSamples();
+              // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+              // decoder, which closes the frames it still holds (WebKit's reorder queue).
+              onQueueDequeue();
               throw outOfBandError;
             } else if (sampleQueue.length > 0) {
               const value = sampleQueue.shift();
@@ -24650,8 +24697,10 @@ var Mediabunny = (() => {
     return decodedSampleQueueSize === 0 ? 40 : 8;
   };
   var VideoDecoderWrapper = class extends DecoderWrapper {
-    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution) {
+    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride = null, transformPacket = null) {
       super(onSample, onError);
+      // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.
+      this.transformPacket = transformPacket;
       this.codec = codec;
       this.decoderConfig = decoderConfig;
       this.rotation = rotation;
@@ -24661,6 +24710,12 @@ var Mediabunny = (() => {
       this.customDecoder = null;
       this.customDecoderCallSerializer = new CallSerializer();
       this.customDecoderQueueSize = 0;
+      // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the
+      // samples a custom decoder produces (see restampSample).
+      this.colorSpaceOverride = colorSpaceOverride;
+      this.restampBuffer = null; // Reused across restamps, sized on the first frame.
+      this.restampChain = Promise.resolve(); // Restamps in emission order.
+      this.restampsInFlight = 0;
       this.inputTimestamps = [];
       // Timestamps input into the decoder, sorted.
       this.sampleQueue = [];
@@ -24692,6 +24747,17 @@ var Mediabunny = (() => {
           if (!(sample instanceof VideoSample)) {
             throw new TypeError("The argument passed to onSample must be a VideoSample.");
           }
+          if (this.colorSpaceOverride) {
+            // A custom decoder tags its samples from the bitstream. The override replaces that tag so the
+            // sample draws the way a WebCodecs frame configured with the same color space does. The restamp
+            // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the
+            // ones still copying, and a flush waits for the chain to drain.
+            this.restampsInFlight++;
+            this.restampChain = this.restampChain.then(() => this.restampSample(sample)).then((restamped) => this.finalizeAndEmitSample(restamped), (error) => onError(error)).finally(() => {
+              this.restampsInFlight--;
+            });
+            return;
+          }
           this.finalizeAndEmitSample(sample);
         };
         this.customDecoder.onError = (error) => {
@@ -24763,7 +24829,7 @@ var Mediabunny = (() => {
     }
     getDecodeQueueSize() {
       if (this.customDecoder) {
-        return this.customDecoderQueueSize;
+        return this.customDecoderQueueSize + this.restampsInFlight;
       } else {
         assert(this.decoder);
         return Math.max(
@@ -24827,6 +24893,12 @@ var Mediabunny = (() => {
             }
           }
         }
+        if (this.transformPacket) {
+            const transformed = this.transformPacket(packet.data, this.decoderConfig);
+            if (transformed) {
+                packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);
+            }
+        }
         this.decoder.decode(packet.toEncodedVideoChunk());
         this.decodeAlphaData(packet);
       }
@@ -24943,6 +25015,49 @@ var Mediabunny = (() => {
       sample.setFlip(this.flip);
       this.onSample(sample);
     }
+    /**
+     * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:
+     * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,
+     * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.
+     */
+    async restampSample(sample) {
+      const override = this.colorSpaceOverride;
+      assert(override);
+      const data = sample._data;
+      if (!(typeof VideoFrame !== "undefined" && data instanceof VideoFrame)) {
+        sample.colorSpace = new VideoSampleColorSpace(override);
+        return sample;
+      }
+      if (data.format === null) {
+        return sample;
+      }
+      const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };
+      const size = data.allocationSize({ rect });
+      if (!this.restampBuffer || this.restampBuffer.byteLength < size) {
+        this.restampBuffer = new ArrayBuffer(size);
+      }
+      // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.
+      const { timestamp, duration, rotation } = sample;
+      let restamped;
+      try {
+        const layout = await data.copyTo(this.restampBuffer, { rect });
+        restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {
+          format: data.format,
+          codedWidth: data.codedWidth,
+          codedHeight: data.codedHeight,
+          layout,
+          visibleRect: data.visibleRect ?? void 0,
+          displayWidth: data.displayWidth,
+          displayHeight: data.displayHeight,
+          timestamp: data.timestamp,
+          duration: data.duration ?? void 0,
+          colorSpace: override
+        });
+      } finally {
+        sample.close();
+      }
+      return new VideoSample(restamped, { timestamp, duration, rotation });
+    }
     async mergeAlpha(color, alpha) {
       const resolver = promiseWithResolvers();
       this.mergeAlphaPromises.push(resolver.promise);
@@ -24971,6 +25086,11 @@ var Mediabunny = (() => {
     async flush() {
       if (this.customDecoder) {
         await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
+        // A custom decoder may hand out its last samples a microtask after its flush resolves (the same
+        // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.
+        do {
+          await this.restampChain;
+        } while (this.restampsInFlight > 0);
       } else {
         assert(this.decoder);
         await Promise.all([
@@ -25251,6 +25371,18 @@ var Mediabunny = (() => {
     if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {
       throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");
     }
+    if (decoderOptions.colorSpace !== void 0) {
+      if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== "object") {
+        throw new TypeError("decoderOptions.colorSpace, when provided, must be an object.");
+      }
+      new VideoSampleColorSpace(decoderOptions.colorSpace);
+    }
+    if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== "function") {
+        throw new TypeError("decoderOptions.transformConfig, when provided, must be a function.");
+    }
+    if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== "function") {
+        throw new TypeError("decoderOptions.transformPacket, when provided, must be a function.");
+    }
   };
   var VideoSampleSink = class extends BaseMediaSampleSink {
     /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */
@@ -25279,12 +25411,19 @@ var Mediabunny = (() => {
       let decoderConfig = await this._track.getDecoderConfig();
       const timeResolution = await this._track.getTimeResolution();
       assert(codec && decoderConfig);
+      const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;
       decoderConfig = {
         ...decoderConfig,
         hardwareAcceleration: this._decoderOptions.hardwareAcceleration,
-        optimizeForLatency: this._decoderOptions.optimizeForLatency
+        optimizeForLatency: this._decoderOptions.optimizeForLatency,
+        // The override replaces whatever the track carries, so the decoder emits frames tagged the way the
+        // caller asked, in-band tags included.
+        ...colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}
       };
-      return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution);
+      if (this._decoderOptions.transformConfig) {
+          decoderConfig = this._decoderOptions.transformConfig(decoderConfig);
+      }
+      return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);
     }
     /** @internal */
     _createPacketSink() {
@@ -27345,6 +27484,10 @@ var Mediabunny = (() => {
         return;
       }
       this._disposed = true;
+      // Wake the decode pumps parked on this input (Donkey patch): each unwinds and closes what it queued.
+      for (const wake of this._disposeWakers ?? []) {
+        wake();
+      }
       for (const ref of this._sourceRefs) {
         ref.free();
       }
diff --git a/node_modules/mediabunny/dist/mediabunny.d.ts b/node_modules/mediabunny/dist/mediabunny.d.ts
index 1307312..1a2027e 100644
--- a/node_modules/mediabunny/dist/mediabunny.d.ts
+++ b/node_modules/mediabunny/dist/mediabunny.d.ts
@@ -5328,6 +5328,21 @@ export declare type VideoSinkDecoderOptions = {
      * before video frames are output.
      */
     optimizeForLatency?: boolean;
+    /**
+     * The color space the decoded frames are tagged with, replacing whatever the track carries. Merged into the
+     * WebCodecs decoder config, and stamped onto the samples a custom decoder produces. Use it to read a file whose
+     * tags the browser would otherwise convert or tone-map, so the drawn pixels are the untouched code values.
+     */
+    colorSpace?: VideoColorSpaceInit;
+    /**
+     * Rewrites the WebCodecs decoder config before the decoder is configured, after the sink's own fields are
+     * merged in. Use it to edit codec-specific data such as the bitstream's in-band color tags.
+     */
+    transformConfig?: (config: VideoDecoderConfig) => VideoDecoderConfig;
+    /**
+     * Rewrites a packet's bytes before they reach the WebCodecs decoder. Return null to send the packet as is.
+     */
+    transformPacket?: (data: Uint8Array, config: VideoDecoderConfig) => Uint8Array | null;
 };
 
 /**
diff --git a/node_modules/mediabunny/dist/modules/src/input.js b/node_modules/mediabunny/dist/modules/src/input.js
index d4bec8f..8043f02 100644
--- a/node_modules/mediabunny/dist/modules/src/input.js
+++ b/node_modules/mediabunny/dist/modules/src/input.js
@@ -354,6 +354,10 @@ export class Input extends EventEmitter {
             return;
         }
         this._disposed = true;
+        // Wake the decode pumps parked on this input (Donkey patch): each unwinds and closes what it queued.
+        for (const wake of this._disposeWakers ?? []) {
+          wake();
+        }
         for (const ref of this._sourceRefs) {
             ref.free();
         }
diff --git a/node_modules/mediabunny/dist/modules/src/media-sink.d.ts b/node_modules/mediabunny/dist/modules/src/media-sink.d.ts
index 056c51c..2463224 100644
--- a/node_modules/mediabunny/dist/modules/src/media-sink.d.ts
+++ b/node_modules/mediabunny/dist/modules/src/media-sink.d.ts
@@ -129,6 +129,21 @@ export type VideoSinkDecoderOptions = {
      * before video frames are output.
      */
     optimizeForLatency?: boolean;
+    /**
+     * The color space the decoded frames are tagged with, replacing whatever the track carries. Merged into the
+     * WebCodecs decoder config, and stamped onto the samples a custom decoder produces. Use it to read a file whose
+     * tags the browser would otherwise convert or tone-map, so the drawn pixels are the untouched code values.
+     */
+    colorSpace?: VideoColorSpaceInit;
+    /**
+     * Rewrites the WebCodecs decoder config before the decoder is configured, after the sink's own fields are
+     * merged in. Use it to edit codec-specific data such as the bitstream's in-band color tags.
+     */
+    transformConfig?: (config: VideoDecoderConfig) => VideoDecoderConfig;
+    /**
+     * Rewrites a packet's bytes before they reach the WebCodecs decoder. Return null to send the packet as is.
+     */
+    transformPacket?: (data: Uint8Array, config: VideoDecoderConfig) => Uint8Array | null;
 };
 /**
  * A sink that retrieves decoded video samples (video frames) from a video track.
diff --git a/node_modules/mediabunny/dist/modules/src/media-sink.js b/node_modules/mediabunny/dist/modules/src/media-sink.js
index 9465e3b..4b77ae1 100644
--- a/node_modules/mediabunny/dist/modules/src/media-sink.js
+++ b/node_modules/mediabunny/dist/modules/src/media-sink.js
@@ -13,7 +13,7 @@ import { InputAudioTrack, InputTrack, InputVideoTrack } from './input-track.js';
 import { assert, assertNever, CallSerializer, clamp, colorSpaceIsComplete, getInt24, getUint24, insertSorted, isChromium, isFirefox, isNumber, isWebKit, last, mapAsyncGenerator, missingWebCodecsClassMessage, promiseWithResolvers, removeItem, toAsyncIterator, toDataView, toUint8Array, validateAnyIterable, } from './misc.js';
 import { EncodedPacket } from './packet.js';
 import { fromAlaw, fromUlaw } from './pcm.js';
-import { AudioSample, clampCropRectangle, validateCropRectangle, VideoSample, } from './sample.js';
+import { AudioSample, clampCropRectangle, validateCropRectangle, VideoSample, VideoSampleColorSpace, } from './sample.js';
 const validatePacketRetrievalOptions = (options) => {
     if (!options || typeof options !== 'object') {
         throw new TypeError('options must be an object.');
@@ -324,13 +324,17 @@ export class BaseMediaSampleSink {
             metadataOnly: false,
         };
         // The following is the "pump" process that keeps pumping packets into the decoder
+        // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+        const wakeOnDispose = () => onQueueDequeue();
+        (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
         (async () => {
             decoder = await this._createDecoder((sample) => {
                 onQueueDequeue();
                 if (sample.timestamp >= endTimestamp) {
                     ended = true;
                 }
-                if (ended) {
+                // A sample decoded after the input was disposed has no reader left (Donkey patch).
+                if (ended || this._track.input._disposed) {
                     sample.close();
                     return;
                 }
@@ -407,6 +411,12 @@ export class BaseMediaSampleSink {
             }
         }).finally(() => {
             decoder?.close();
+            this._track.input._disposeWakers?.delete(wakeOnDispose);
+            // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+            // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+            if (this._track.input._disposed) {
+              closeSamples();
+            }
         });
         const track = this._track;
         const closeSamples = () => {
@@ -425,6 +435,9 @@ export class BaseMediaSampleSink {
                         terminated = true;
                         ended = true;
                         closeSamples();
+                        // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+                        // decoder, which closes the frames it still holds (WebKit's reorder queue).
+                        onQueueDequeue();
                         throw new InputDisposedError();
                     }
                     else if (terminated) {
@@ -434,6 +447,9 @@ export class BaseMediaSampleSink {
                         terminated = true;
                         ended = true;
                         closeSamples();
+                        // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+                        // decoder, which closes the frames it still holds (WebKit's reorder queue).
+                        onQueueDequeue();
                         throw outOfBandError;
                     }
                     else if (sampleQueue.length > 0) {
@@ -492,10 +508,14 @@ export class BaseMediaSampleSink {
             metadataOnly: false,
         };
         // The following is the "pump" process that keeps pumping packets into the decoder
+        // Wake this pump if its input is disposed while it is parked on a full queue (Donkey patch).
+        const wakeOnDispose = () => onQueueDequeue();
+        (this._track.input._disposeWakers ??= new Set()).add(wakeOnDispose);
         (async () => {
             decoder = await this._createDecoder((sample) => {
                 onQueueDequeue();
-                if (terminated) {
+                // A sample decoded after the input was disposed has no reader left (Donkey patch).
+                if (terminated || this._track.input._disposed) {
                     sample.close();
                     return;
                 }
@@ -536,11 +556,11 @@ export class BaseMediaSampleSink {
                 decoder.decode(currentPacket);
                 while (currentPacket.sequenceNumber < maxSequenceNumber) {
                     const maxQueueSize = computeMaxQueueSize(sampleQueue.length);
-                    while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated) {
+                    while (sampleQueue.length + decoder.getDecodeQueueSize() > maxQueueSize && !terminated && !this._track.input._disposed) {
                         ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());
                         await queueDequeue;
                     }
-                    if (terminated) {
+                    if (terminated || this._track.input._disposed) {
                         break;
                     }
                     const nextPacket = await packetSink.getNextPacket(currentPacket, retrievalOptions);
@@ -605,6 +625,12 @@ export class BaseMediaSampleSink {
             }
         }).finally(() => {
             decoder?.close();
+            this._track.input._disposeWakers?.delete(wakeOnDispose);
+            // A pump that ends on a disposed input closes what it queued (Donkey patch): a reader that was idle
+            // when its input went away never calls next() again, so the samples would wait for the garbage collector.
+            if (this._track.input._disposed) {
+              closeSamples();
+            }
         });
         const track = this._track;
         const closeSamples = () => {
@@ -621,6 +647,9 @@ export class BaseMediaSampleSink {
                         // nothing can ever close.
                         terminated = true;
                         closeSamples();
+                        // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+                        // decoder, which closes the frames it still holds (WebKit's reorder queue).
+                        onQueueDequeue();
                         throw new InputDisposedError();
                     }
                     else if (terminated) {
@@ -629,6 +658,9 @@ export class BaseMediaSampleSink {
                     else if (hasOutOfBandError) {
                         terminated = true;
                         closeSamples();
+                        // Wake a pump parked on a full queue (Donkey patch): it sees the end, unwinds, and closes the
+                        // decoder, which closes the frames it still holds (WebKit's reorder queue).
+                        onQueueDequeue();
                         throw outOfBandError;
                     }
                     else if (sampleQueue.length > 0) {
@@ -662,14 +694,17 @@ export class BaseMediaSampleSink {
     }
 }
 const computeMaxQueueSize = (decodedSampleQueueSize) => {
-    // If we have decoded samples lying around, limit the total queue size to a small value (decoded samples can use up
-    // a lot of memory). If not, we're fine with a much bigger queue of encoded packets waiting to be decoded. In fact,
-    // some decoders only start flushing out decoded chunks when the packet queue is large enough.
-    return decodedSampleQueueSize === 0 ? 40 : 8;
+    // Decoded frames are large, and a video decoder holds every packet it has been handed until the frame comes out. So
+    // the pump counts frames in flight together with the decoded ones waiting, and keeps the total small: enough of a
+    // head start for a decoder that reorders frames, and no more, so a consumer that stops reading pins a bounded
+    // number of decoded frames.
+    return decodedSampleQueueSize === 0 ? 16 : 8;
 };
 class VideoDecoderWrapper extends DecoderWrapper {
-    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution) {
+    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride = null, transformPacket = null) {
         super(onSample, onError);
+        // The sink's packet hook: rewrites packet bytes before they reach the WebCodecs decoder.
+        this.transformPacket = transformPacket;
         this.codec = codec;
         this.decoderConfig = decoderConfig;
         this.rotation = rotation;
@@ -679,6 +714,13 @@ class VideoDecoderWrapper extends DecoderWrapper {
         this.customDecoder = null;
         this.customDecoderCallSerializer = new CallSerializer();
         this.customDecoderQueueSize = 0;
+        // The sink's color space override: already merged into `decoderConfig` for WebCodecs, and stamped onto the
+        // samples a custom decoder produces (see restampSample).
+        this.colorSpaceOverride = colorSpaceOverride;
+        this.restampBuffer = null; // Reused across restamps, sized on the first frame.
+        this.restampChain = Promise.resolve(); // Restamps in emission order.
+        this.restampsInFlight = 0;
+        this.inFlight = 0; // Packets sent to the decoder whose frames have not come back yet.
         this.inputTimestamps = []; // Timestamps input into the decoder, sorted.
         this.sampleQueue = []; // Safari-specific thing, check usage.
         this.currentPacketIndex = 0;
@@ -710,6 +752,20 @@ class VideoDecoderWrapper extends DecoderWrapper {
                 if (!(sample instanceof VideoSample)) {
                     throw new TypeError('The argument passed to onSample must be a VideoSample.');
                 }
+                if (this.colorSpaceOverride) {
+                    // A custom decoder tags its samples from the bitstream. The override replaces that tag so the
+                    // sample draws the way a WebCodecs frame configured with the same color space does. The restamp
+                    // copies frame data, so it runs on its own chain: samples stay in order, the pump counts the
+                    // ones still copying, and a flush waits for the chain to drain.
+                    this.restampsInFlight++;
+                    this.restampChain = this.restampChain
+                        .then(() => this.restampSample(sample))
+                        .then(restamped => this.finalizeAndEmitSample(restamped), error => onError(error))
+                        .finally(() => {
+                            this.restampsInFlight--;
+                        });
+                    return;
+                }
                 this.finalizeAndEmitSample(sample);
             };
             // @ts-expect-error It's technically readonly
@@ -780,6 +836,7 @@ class VideoDecoderWrapper extends DecoderWrapper {
             const stack = new Error('Decoding error').stack;
             this.decoder = new VideoDecoder({
                 output: (frame) => {
+                    this.inFlight = Math.max(0, this.inFlight - 1);
                     try {
                         colorHandler(frame);
                     }
@@ -797,11 +854,11 @@ class VideoDecoderWrapper extends DecoderWrapper {
     }
     getDecodeQueueSize() {
         if (this.customDecoder) {
-            return this.customDecoderQueueSize;
+            return this.customDecoderQueueSize + this.restampsInFlight;
         }
         else {
             assert(this.decoder);
-            return Math.max(this.decoder.decodeQueueSize, this.alphaDecoder?.decodeQueueSize ?? 0);
+            return Math.max(this.inFlight, this.alphaDecoder?.decodeQueueSize ?? 0);
         }
     }
     decode(packet) {
@@ -873,6 +930,13 @@ class VideoDecoderWrapper extends DecoderWrapper {
                     }
                 }
             }
+            if (this.transformPacket) {
+                const transformed = this.transformPacket(packet.data, this.decoderConfig);
+                if (transformed) {
+                    packet = new EncodedPacket(transformed, packet.type, packet.timestamp, packet.duration);
+                }
+            }
+            this.inFlight++;
             this.decoder.decode(packet.toEncodedVideoChunk());
             this.decodeAlphaData(packet);
         }
@@ -1020,6 +1084,49 @@ class VideoDecoderWrapper extends DecoderWrapper {
         sample.setFlip(this.flip);
         this.onSample(sample);
     }
+    /**
+     * Returns `sample` carrying the sink's color space override. A sample over raw planes takes the tag directly:
+     * the VideoFrame it later builds reads `sample.colorSpace`. A sample already wrapping a VideoFrame is rebuilt,
+     * since a VideoFrame's color space is fixed at construction and is what the browser draws it by.
+     */
+    async restampSample(sample) {
+        const override = this.colorSpaceOverride;
+        assert(override);
+        const data = sample._data;
+        if (!(typeof VideoFrame !== 'undefined' && data instanceof VideoFrame)) {
+            sample.colorSpace = new VideoSampleColorSpace(override);
+            return sample;
+        }
+        if (data.format === null) {
+            return sample; // Opaque frame; nothing to copy.
+        }
+        const rect = { x: 0, y: 0, width: data.codedWidth, height: data.codedHeight };
+        const size = data.allocationSize({ rect });
+        if (!this.restampBuffer || this.restampBuffer.byteLength < size) {
+            this.restampBuffer = new ArrayBuffer(size);
+        }
+        // The sample is closed on every path: a failed copy or frame build must not leak the decoder's frame.
+        const { timestamp, duration, rotation } = sample;
+        let restamped;
+        try {
+            const layout = await data.copyTo(this.restampBuffer, { rect });
+            restamped = new VideoFrame(new Uint8Array(this.restampBuffer, 0, size), {
+                format: data.format,
+                codedWidth: data.codedWidth,
+                codedHeight: data.codedHeight,
+                layout,
+                visibleRect: data.visibleRect ?? undefined,
+                displayWidth: data.displayWidth,
+                displayHeight: data.displayHeight,
+                timestamp: data.timestamp,
+                duration: data.duration ?? undefined,
+                colorSpace: override,
+            });
+        } finally {
+            sample.close();
+        }
+        return new VideoSample(restamped, { timestamp, duration, rotation });
+    }
     async mergeAlpha(color, alpha) {
         const resolver = promiseWithResolvers();
         this.mergeAlphaPromises.push(resolver.promise);
@@ -1056,6 +1163,11 @@ class VideoDecoderWrapper extends DecoderWrapper {
     async flush() {
         if (this.customDecoder) {
             await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
+            // A custom decoder may hand out its last samples a microtask after its flush resolves (the same
+            // ordering the sink's own flush relies on), so drain the chain until nothing is still copying.
+            do {
+                await this.restampChain;
+            } while (this.restampsInFlight > 0);
         }
         else {
             assert(this.decoder);
@@ -1081,6 +1193,7 @@ class VideoDecoderWrapper extends DecoderWrapper {
             }
             this.sampleQueue.length = 0;
         }
+        this.inFlight = 0;
         this.currentPacketIndex = 0;
         this.raslSkipped = false;
     }
@@ -1358,6 +1471,18 @@ const validateVideoSinkDecoderOptions = (decoderOptions) => {
     if (decoderOptions.optimizeForLatency !== undefined && typeof decoderOptions.optimizeForLatency !== 'boolean') {
         throw new TypeError('decoderOptions.optimizeForLatency, when provided, must be a boolean.');
     }
+    if (decoderOptions.colorSpace !== undefined) {
+        if (!decoderOptions.colorSpace || typeof decoderOptions.colorSpace !== 'object') {
+            throw new TypeError('decoderOptions.colorSpace, when provided, must be an object.');
+        }
+        new VideoSampleColorSpace(decoderOptions.colorSpace); // Validates the fields
+    }
+    if (decoderOptions.transformConfig !== undefined && typeof decoderOptions.transformConfig !== 'function') {
+        throw new TypeError('decoderOptions.transformConfig, when provided, must be a function.');
+    }
+    if (decoderOptions.transformPacket !== undefined && typeof decoderOptions.transformPacket !== 'function') {
+        throw new TypeError('decoderOptions.transformPacket, when provided, must be a function.');
+    }
 };
 /**
  * A sink that retrieves decoded video samples (video frames) from a video track.
@@ -1390,12 +1515,19 @@ export class VideoSampleSink extends BaseMediaSampleSink {
         let decoderConfig = await this._track.getDecoderConfig();
         const timeResolution = await this._track.getTimeResolution();
         assert(codec && decoderConfig);
+        const colorSpaceOverride = this._decoderOptions.colorSpace ?? null;
         decoderConfig = {
             ...decoderConfig,
             hardwareAcceleration: this._decoderOptions.hardwareAcceleration,
             optimizeForLatency: this._decoderOptions.optimizeForLatency,
+            // The override replaces whatever the track carries, so the decoder emits frames tagged the way the
+            // caller asked, in-band tags included.
+            ...(colorSpaceOverride ? { colorSpace: colorSpaceOverride } : {}),
         };
-        return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution);
+        if (this._decoderOptions.transformConfig) {
+            decoderConfig = this._decoderOptions.transformConfig(decoderConfig);
+        }
+        return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution, colorSpaceOverride, this._decoderOptions.transformPacket ?? null);
     }
     /** @internal */
     _createPacketSink() {
diff --git a/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js b/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js
index a7b3aa6..7cd67f4 100644
--- a/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js
+++ b/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js
@@ -103,6 +103,21 @@ export class Mp3Demuxer extends Demuxer {
                                 ? view.getUint32(8, false)
                                 : null,
                         };
+                        // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
+                        // holds the encoder delay, and the decoder adds 529 samples of priming on
+                        // top. The audio starts after both, as ffmpeg plays it, so the first
+                        // frames carry negative timestamps.
+                        const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
+                        let tagSlice = this.reader.requestSlice(tagAt, 24);
+                        if (isThenable(tagSlice)) tagSlice = await tagSlice;
+                        if (tagSlice && this.nextTimestampInSamples === 0) {
+                          const tag = readBytes(tagSlice, 24);
+                          const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
+                          if (id === "LAME" || id === "Lavf" || id === "Lavc") {
+                            const delay = (tag[21] << 4) | (tag[22] >> 4);
+                            this.nextTimestampInSamples = -(delay + 529);
+                          }
+                        }
                     }
                 }
                 return;