From 5c037404a7d3b7a599f2057290b7739135894fdc Mon Sep 17 00:00:00 2001 From: Ramadan Date: Mon, 30 Nov 2026 13:08:27 +0000 Subject: [PATCH 1/5] Preserve decoded video frame timestamps and durations --- native/async_decoder.cpp | 52 ++------------ native/async_decoder.h | 7 +- native/decoder.cpp | 13 +--- native/decoder.h | 1 - native/frame.cpp | 13 ++++ native/frame.h | 1 + test/fixtures/reordered-video/README.md | 8 +++ test/fixtures/reordered-video/h264.bin | Bin 0 -> 2716 bytes test/fixtures/reordered-video/hevc.bin | Bin 0 -> 5034 bytes test/fixtures/reordered-video/inventory.json | 10 +++ test/reordered-video-decoder.test.ts | 72 +++++++++++++++++++ 11 files changed, 114 insertions(+), 63 deletions(-) create mode 100644 test/fixtures/reordered-video/README.md create mode 100644 test/fixtures/reordered-video/h264.bin create mode 100644 test/fixtures/reordered-video/hevc.bin create mode 100644 test/fixtures/reordered-video/inventory.json create mode 100644 test/reordered-video-decoder.test.ts diff --git a/native/async_decoder.cpp b/native/async_decoder.cpp index 7f6aeab..a3672e4 100644 --- a/native/async_decoder.cpp +++ b/native/async_decoder.cpp @@ -264,8 +264,6 @@ void VideoDecoderAsync::ProcessDecode(DecodeJob& job) { av_strerror(ret, errBuf, sizeof(errBuf)); DecodeResult result; - result.frame = nullptr; - result.isError = true; result.errorMessage = std::string("Decode error: ") + errBuf; tsfnError_.BlockingCall(&result, [](Napi::Env env, Napi::Function fn, DecodeResult* res) { @@ -287,8 +285,6 @@ void VideoDecoderAsync::ProcessDecode(DecodeJob& job) { av_strerror(ret, errBuf, sizeof(errBuf)); DecodeResult result; - result.frame = nullptr; - result.isError = true; result.errorMessage = std::string("Decode error: ") + errBuf; tsfnError_.BlockingCall(&result, [](Napi::Env env, Napi::Function fn, DecodeResult* res) { @@ -297,28 +293,10 @@ void VideoDecoderAsync::ProcessDecode(DecodeJob& job) { break; } - // Clone frame for output AVFrame* outputFrame = av_frame_clone(frame); - - DecodeResult* result = new DecodeResult(); - result->frame = outputFrame; - result->timestamp = job.timestamp; - result->duration = job.duration; - result->isError = false; - result->isFlushComplete = false; - - // Call JS callback - tsfnOutput_.BlockingCall(result, [](Napi::Env env, Napi::Function fn, DecodeResult* res) { - Napi::Object nativeFrame = VideoFrameNative::NewInstance(env, res->frame); - - fn.Call({ - nativeFrame, - Napi::Number::New(env, static_cast(res->timestamp)), - Napi::Number::New(env, static_cast(res->duration)) - }); - - delete res; - }); + if (tsfnOutput_.BlockingCall(outputFrame, VideoFrameNative::EmitDecoded) != napi_ok) { + av_frame_free(&outputFrame); + } av_frame_unref(frame); } @@ -341,26 +319,10 @@ void VideoDecoderAsync::ProcessFlush() { while ((ret = avcodec_receive_frame(codecCtx_, frame)) >= 0) { AVFrame* outputFrame = av_frame_clone(frame); - DecodeResult* result = new DecodeResult(); - result->frame = outputFrame; - result->timestamp = frame->pts; - result->duration = NWC_FRAME_DURATION(frame); - result->isError = false; - result->isFlushComplete = false; - - // Use NonBlockingCall to prevent deadlock in resource-constrained environments - // (CI, serverless, containers) where the JS event loop may be starved - tsfnOutput_.NonBlockingCall(result, [](Napi::Env env, Napi::Function fn, DecodeResult* res) { - Napi::Object nativeFrame = VideoFrameNative::NewInstance(env, res->frame); - - fn.Call({ - nativeFrame, - Napi::Number::New(env, static_cast(res->timestamp)), - Napi::Number::New(env, static_cast(res->duration)) - }); - - delete res; - }); + // Keep drain output nonblocking for resource-constrained environments. + if (tsfnOutput_.NonBlockingCall(outputFrame, VideoFrameNative::EmitDecoded) != napi_ok) { + av_frame_free(&outputFrame); + } av_frame_unref(frame); } diff --git a/native/async_decoder.h b/native/async_decoder.h index 61c352d..80a49d8 100644 --- a/native/async_decoder.h +++ b/native/async_decoder.h @@ -23,14 +23,9 @@ struct DecodeJob { bool isFlush; }; -// Result from worker thread back to JS +// Error reported from the worker thread back to JS. struct DecodeResult { - AVFrame* frame; // Ownership transferred to callback - int64_t timestamp; - int64_t duration; - bool isError; std::string errorMessage; - bool isFlushComplete; }; class VideoDecoderAsync : public Napi::ObjectWrap { diff --git a/native/decoder.cpp b/native/decoder.cpp index 53051b7..4564322 100644 --- a/native/decoder.cpp +++ b/native/decoder.cpp @@ -182,7 +182,7 @@ void VideoDecoderNative::Decode(const Napi::CallbackInfo& info) { // Clone frame and emit AVFrame* outputFrame = av_frame_clone(frame); - EmitFrame(env, outputFrame, timestamp, duration); + VideoFrameNative::EmitDecoded(env, outputCallback_.Value(), outputFrame); av_frame_unref(frame); } @@ -190,15 +190,6 @@ void VideoDecoderNative::Decode(const Napi::CallbackInfo& info) { av_packet_free(&packet); } -void VideoDecoderNative::EmitFrame(Napi::Env env, AVFrame* frame, int64_t timestamp, int64_t duration) { - Napi::Object nativeFrame = VideoFrameNative::NewInstance(env, frame); - outputCallback_.Value().Call({ - nativeFrame, - Napi::Number::New(env, timestamp), - Napi::Number::New(env, duration) - }); -} - void VideoDecoderNative::EmitError(Napi::Env env, const std::string& message) { errorCallback_.Value().Call({ Napi::String::New(env, message) }); } @@ -214,7 +205,7 @@ Napi::Value VideoDecoderNative::Flush(const Napi::CallbackInfo& info) { int ret; while ((ret = avcodec_receive_frame(codecCtx_, frame)) >= 0) { AVFrame* outputFrame = av_frame_clone(frame); - EmitFrame(env, outputFrame, frame->pts, NWC_FRAME_DURATION(frame)); + VideoFrameNative::EmitDecoded(env, outputCallback_.Value(), outputFrame); av_frame_unref(frame); } av_frame_free(&frame); diff --git a/native/decoder.h b/native/decoder.h index 7af290e..f6b1e5f 100644 --- a/native/decoder.h +++ b/native/decoder.h @@ -24,7 +24,6 @@ class VideoDecoderNative : public Napi::ObjectWrap { void Reset(const Napi::CallbackInfo& info); void Close(const Napi::CallbackInfo& info); - void EmitFrame(Napi::Env env, AVFrame* frame, int64_t timestamp, int64_t duration); void EmitError(Napi::Env env, const std::string& message); AVCodecContext* codecCtx_; diff --git a/native/frame.cpp b/native/frame.cpp index a45ac42..03a12a2 100644 --- a/native/frame.cpp +++ b/native/frame.cpp @@ -523,6 +523,19 @@ Napi::Value VideoFrameNative::Scale(const Napi::CallbackInfo& info) { return NewInstance(env, out); } +void VideoFrameNative::EmitDecoded(Napi::Env env, const Napi::Function& callback, AVFrame* frame) { + // A frame can be released by a later packet or during drain. Its PTS and + // duration belong to the decoded picture, regardless of what released it. + const int64_t timestamp = frame->pts; + const int64_t duration = NWC_FRAME_DURATION(frame); + Napi::Object nativeFrame = NewInstance(env, frame); + callback.Call({ + nativeFrame, + Napi::Number::New(env, static_cast(timestamp)), + Napi::Number::New(env, static_cast(duration)) + }); +} + Napi::Object VideoFrameNative::NewInstance(Napi::Env env, AVFrame* frame) { Napi::Object obj = constructor.New({}); VideoFrameNative* instance = Napi::ObjectWrap::Unwrap(obj); diff --git a/native/frame.h b/native/frame.h index b4e283c..a83e46a 100644 --- a/native/frame.h +++ b/native/frame.h @@ -22,6 +22,7 @@ class VideoFrameNative : public Napi::ObjectWrap { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); static Napi::Object NewInstance(Napi::Env env, AVFrame* frame); + static void EmitDecoded(Napi::Env env, const Napi::Function& callback, AVFrame* frame); static Napi::FunctionReference constructor; VideoFrameNative(const Napi::CallbackInfo& info); diff --git a/test/fixtures/reordered-video/README.md b/test/fixtures/reordered-video/README.md new file mode 100644 index 0000000..04446ba --- /dev/null +++ b/test/fixtures/reordered-video/README.md @@ -0,0 +1,8 @@ +# Reordered decoder timing fixtures + +These are synthetic 64 × 48 Annex B streams from FFmpeg 8.0.1 `testsrc2`, each with 40 access units and B-pictures. The inventory joins the packet byte position from `ffprobe -show_packets` to `pkt_pos` in `ffprobe -show_frames` to identify the source packet of every displayed picture. The test supplies timestamps and durations separately. + +```sh +ffmpeg -f lavfi -i 'testsrc2=size=64x48:rate=12' -frames:v 40 -an -c:v libx264 -preset veryfast -crf 30 -x264-params 'bframes=3:b-adapt=0:keyint=60:scenecut=0:aud=1:threads=1' -f h264 h264.bin +ffmpeg -f lavfi -i 'testsrc2=size=64x48:rate=12' -frames:v 40 -an -c:v libx265 -preset fast -crf 30 -x265-params 'bframes=3:b-adapt=0:keyint=60:scenecut=0:aud=1:pools=none:frame-threads=1:log-level=error' -f hevc hevc.bin +``` diff --git a/test/fixtures/reordered-video/h264.bin b/test/fixtures/reordered-video/h264.bin new file mode 100644 index 0000000000000000000000000000000000000000..24ac8d72b1c38bf197cd576953709b616dc53e8c GIT binary patch literal 2716 zcmZWpX;f258YO@WiUN(Yv|^qDBC;hUB1XfGAfO;>)3joINnRESNqC8pXe$9kaRFQq z6ov#B1Qhg0%Rw6uu(fd_n<$$$&EkRzvWWvKlBpMF0%zt=y{h}&y7zun@06C77EaGl z3yf^0*1W=YpMyBC($T^OoNRbS_#Ujr89ahkf$!{DD%FL*eBW2RZTBxtw{L^mEe8fA z&Msug0b&SH1R}bu0aJfR06A?A@%3{cL!Li*gBlZIfP%L`DCHq6G2~1jkQ|%|&KR2` z77Hm(PBAetj{CVxM8JdjjsleJgy}kR#8EuJ5eUUx0bfLc7%&}XP>B$Vu)xSf=sW=< zl1iiyCHUpfH7=^ifAOVOdjB!{f9EFIeB#2HE zO2M4V1P4K5TIRHs0!r$|H!w5cwH z|IBDnTt3wW5-|`y!q|sNs;#l(L=h1OtWgF{(<_yTt*H!@1x3-pnPNSG1(gIY0*b~u zp%NT{cC-+aRexa#)ny$3L}ElpB|}^xxFGN|fcqnZD~|?ukKLq}4E&x*(h)61s~=0Y zDfrPchF{yMrI%@&@cP|gG&kJDPgO93i_=NZvCUny#7$nIWNu<+wG4}E9Yi^cxsRHDy&N~7~fBd_NNf= zodF-$vkk0-?jb4Frtw+a0RIJy2LYpthP2#uM{b66#UIT5A>852$FeI2VP&K?*H;%;&+7YFzIk}foM4NJ3*L}(aILA$MH@*;IfQtaCmY=j7~RHgq$Eg% z^|FUQCb+(;?>*4^`!Sxysx+zTHj=eUJ9TtX$__#B&{fxMCdgBxvE3`~m3pKMC&WJ6 zx{O{J-#e>ogOtp2uZTO)FziMM-5D4^v16`ctVJ0~UG}cum(p=Vq8r{Zy3u6Bp7HR_ zP>}wS7`DKsf!FkYAn{&PMn&?Q*S{>#O0gHZ4nh!05E9J(uTH^R7=3WM`qgZ8+OF_kvZy zriOdRkA5#p`L*Xy%Ou@%K{YjRMtq%>fjM^fno)yf?ZTDp&bAFLiD|c6DvbYh(N)^^ z+h=TNKlI+4G4iE;sNXYv zN~w#|RfqTd;+pi%ed3#I(GL30PS>A$W&aD8cQ_O+B-`#8cP zE4cRNWYvIe%b}OMA1%TwYtE>45{xghU#v)((EjIM!Gf)~$IZ&`+YMunt{wplo|#r= z=TwamNs6_zBOE%4&momeUAt;y2~Wq&cA3GE)6|Jl4>dakW6Qm~3{{h@I?a40P71d_ zyB3J=)>LtF*k?IbeNblpsjz%{8&1vuh2%IjbIO%N4%(z@JT!7S$D+x}+PAQ$j?)t_ z_b3Q^sgd)PAN4h|2ZAlf8mcuYPM$lhg=NCY^Dsa*L%dKezDavGxojT(XVrqwI<=|v zj*PY4b8C}3eVL1^^6~sI{63uOi}nPH`+d@q{6tkKKjt29+l}YQw0^R&xq;LVD%X@r zwyxd1Vo+aW?kQLLE(VdB$_FSXWhGM$O@(+r9byXT13=U2su{6{uvj~HWqi-rmuqeI z*_&c=+RY-}y3t}J%k*$wL7BZ#<>x?y=c^RTQ`~7w#X?}oe#D(L*jsEBYD^r7UD>UB zqhX|RtGw>-T~a(g!#or-zq_Wga+1C!dp3y|zGX*qnp=zgT&Pki&dzs6O4Iz&pbXgHrR92yvW zCStO@Xf^t@zoj5`zUYj`+EbB^HBo12bY;?I^VXL|F@}n6J@cp-P6nhQ;S?q6d}r-E zXJDlOYs%TOTn$Y{F2^DVzGZlBpcr|5@V9Gri+G;D_&{u zr+gXadG_(Ve3_PZk>RqUv3ZT1d#1JJ)cNX z{5;a%*~S^>e}h}AHS7>T5?6LK9Y1yA;z32~Xin(Y)R2Da`{$eO+Wm}W z8b9!!V0mgMDh4~vR@m1R+w~ERtQ<7;sTbwEHX0CMKLh-~*Mvjj6yqD0 literal 0 HcmV?d00001 diff --git a/test/fixtures/reordered-video/hevc.bin b/test/fixtures/reordered-video/hevc.bin new file mode 100644 index 0000000000000000000000000000000000000000..57a05d2895289297104dc81cb79cffdc8b3c268c GIT binary patch literal 5034 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 aTVl6; +type Timing = [timestamp: number, duration: number | null]; + +const data = path.join(__dirname, 'fixtures', 'reordered-video'); +const inventory: Inventory = JSON.parse(readFileSync(path.join(data, 'inventory.json'), 'utf8')); + +describe.each([ + ['h264', 'avc1.64001f'], + ['hevc', 'hev1.1.6.L93.B0'], +] as const)('%s reordered video timing', (fixture, codec) => { + it.each([false, true])('preserves decoded picture timing with useWorkerThread=%s', async (useWorkerThread) => { + if (useWorkerThread) expect(typeof native.VideoDecoderAsync).toBe('function'); + const bytes = readFileSync(path.join(data, `${fixture}.bin`)); + const { sizes, displayOrder } = inventory[fixture]; + // Use signed, sometimes equal timestamps in decode order and give every packet + // a distinct duration so the fixture also detects swaps between equal timestamps. + const inputTiming = sizes.map((_, index): [number, number] => [ + (Math.floor(index / 2) - 5) * 1000, + index + 101, + ]); + const expected = displayOrder.map(index => inputTiming[index]); + const output: Timing[] = []; + const errors: Error[] = []; + let firstFrame!: () => void; + const hasOutput = new Promise(resolve => { firstFrame = resolve; }); + const decoder = new VideoDecoder({ + output(frame) { + output.push([frame.timestamp, frame.duration]); + frame.close(); + firstFrame(); + }, + error(error) { + errors.push(error); + }, + }); + + try { + decoder.configure({ codec, useWorkerThread }); + let offset = 0; + for (const [index, size] of sizes.entries()) { + const [timestamp, duration] = inputTiming[index]; + decoder.decode(new EncodedVideoChunk({ + type: index === 0 ? 'key' : 'delta', + timestamp, + duration, + data: bytes.subarray(offset, offset + size), + })); + offset += size; + } + expect(offset).toBe(bytes.length); + // Demand an output from decode() before sending any flush request. Drain was + // already using the frame metadata, so a drain-only test would miss the bug. + await hasOutput; + const beforeDrain = output.slice(); + expect(beforeDrain).toEqual(expected.slice(0, beforeDrain.length)); + + await decoder.flush(); + expect(errors).toEqual([]); + expect(beforeDrain.length).toBeLessThan(output.length); + expect(output).toEqual(expected); + } finally { + decoder.close(); + } + }, 15000); +}); From a17a056afb5d45f723cd46180127aa0dfd0cb1b4 Mon Sep 17 00:00:00 2001 From: Ramadan Date: Mon, 30 Nov 2026 13:16:03 +0000 Subject: [PATCH 2/5] Own decoder output frames and serialize worker flush completion --- native/async_decoder.cpp | 187 ++++++++++++--------------- native/async_decoder.h | 26 ++-- native/decoder.cpp | 62 ++++----- native/decoder.h | 1 + native/frame.cpp | 10 +- native/frame.h | 9 +- test/reordered-video-decoder.test.ts | 124 ++++++++++++------ 7 files changed, 226 insertions(+), 193 deletions(-) diff --git a/native/async_decoder.cpp b/native/async_decoder.cpp index a3672e4..8a20997 100644 --- a/native/async_decoder.cpp +++ b/native/async_decoder.cpp @@ -1,6 +1,6 @@ #include "async_decoder.h" #include "env_state.h" -#include "frame.h" +#include Napi::FunctionReference VideoDecoderAsync::constructor; @@ -33,7 +33,7 @@ VideoDecoderAsync::VideoDecoderAsync(const Napi::CallbackInfo& info) } // Create thread-safe functions for callbacks - tsfnOutput_ = Napi::ThreadSafeFunction::New( + tsfnOutput_ = decltype(tsfnOutput_)::New( env, info[0].As(), "VideoDecoderAsyncOutput", @@ -50,7 +50,7 @@ VideoDecoderAsync::VideoDecoderAsync(const Napi::CallbackInfo& info) ); // Don't hold the event loop open when idle; a pending flush() holds it - // via tsfnFlush_ instead, so awaited work still completes + // via its own completion callback, so awaited work still completes tsfnOutput_.Unref(env); tsfnError_.Unref(env); @@ -100,9 +100,13 @@ VideoDecoderAsync::~VideoDecoderAsync() { // Release thread-safe functions unless env teardown already finalized them if (!nwc_env_teardown.load()) { + while (!jobQueue_.empty()) { + auto flush = jobQueue_.front().flush; + if (flush) flush.Release(); + jobQueue_.pop(); + } if (tsfnOutput_) tsfnOutput_.Release(); if (tsfnError_) tsfnError_.Release(); - if (tsfnFlush_) tsfnFlush_.Release(); if (tsfnJobDone_) tsfnJobDone_.Release(); } } @@ -216,7 +220,7 @@ void VideoDecoderAsync::WorkerThread() { return !jobQueue_.empty() || !running_; }); - if (!running_ && jobQueue_.empty()) { + if (!running_) { break; } @@ -228,12 +232,13 @@ void VideoDecoderAsync::WorkerThread() { jobQueue_.pop(); } - if (job.isFlush) { - ProcessFlush(); + if (job.flush) { + ProcessFlush(std::exchange(job.flush, {})); } else { ProcessDecode(job); } + if (!running_) break; tsfnJobDone_.NonBlockingCall([this](Napi::Env env, Napi::Function) { JobFinished(env); }); @@ -245,104 +250,95 @@ void VideoDecoderAsync::ProcessDecode(DecodeJob& job) { return; } - // Create packet AVPacket* packet = av_packet_alloc(); + if (!packet) { + EmitError(AVERROR(ENOMEM)); + return; + } packet->data = job.data.data(); packet->size = static_cast(job.data.size()); packet->pts = job.timestamp; packet->dts = job.timestamp; packet->duration = job.duration; + if (job.isKeyframe) packet->flags |= AV_PKT_FLAG_KEY; - if (job.isKeyframe) { - packet->flags |= AV_PKT_FLAG_KEY; - } - - // Send packet to decoder int ret = avcodec_send_packet(codecCtx_, packet); - if (ret < 0) { - char errBuf[256]; - av_strerror(ret, errBuf, sizeof(errBuf)); - - DecodeResult result; - result.errorMessage = std::string("Decode error: ") + errBuf; - - tsfnError_.BlockingCall(&result, [](Napi::Env env, Napi::Function fn, DecodeResult* res) { - fn.Call({ Napi::String::New(env, res->errorMessage) }); - }); - - av_packet_free(&packet); - return; + av_packet_free(&packet); + if (ret >= 0) { + ret = ReceiveFrames(); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF || ret == AVERROR_EXIT) return; } + if (ret < 0) EmitError(ret); +} - // Receive decoded frames - AVFrame* frame = av_frame_alloc(); - while (ret >= 0) { - ret = avcodec_receive_frame(codecCtx_, frame); - if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { - break; - } else if (ret < 0) { - char errBuf[256]; - av_strerror(ret, errBuf, sizeof(errBuf)); - - DecodeResult result; - result.errorMessage = std::string("Decode error: ") + errBuf; - - tsfnError_.BlockingCall(&result, [](Napi::Env env, Napi::Function fn, DecodeResult* res) { - fn.Call({ Napi::String::New(env, res->errorMessage) }); - }); - break; - } +int VideoDecoderAsync::ReceiveFrames() { + for (;;) { + DecodedFramePtr frame(av_frame_alloc()); + if (!frame) return AVERROR(ENOMEM); + int ret = avcodec_receive_frame(codecCtx_, frame.get()); + if (ret < 0) return ret; + if (!QueueOutput({std::move(frame), {}})) return AVERROR_EXIT; + } +} - AVFrame* outputFrame = av_frame_clone(frame); - if (tsfnOutput_.BlockingCall(outputFrame, VideoFrameNative::EmitDecoded) != napi_ok) { - av_frame_free(&outputFrame); - } +void VideoDecoderAsync::EmitError(int error) { + char errBuf[256]; + av_strerror(error, errBuf, sizeof(errBuf)); + tsfnError_.NonBlockingCall([message = std::string("Decode error: ") + errBuf]( + Napi::Env env, Napi::Function callback) { + callback.Call({ Napi::String::New(env, message) }); + }); +} - av_frame_unref(frame); +bool VideoDecoderAsync::QueueOutput(Output output) { + auto pending = std::make_unique(std::move(output)); + if (tsfnOutput_.NonBlockingCall(pending.get()) != napi_ok) { + running_ = false; + return false; } - - av_frame_free(&frame); - av_packet_free(&packet); + pending.release(); + return true; } -void VideoDecoderAsync::ProcessFlush() { - if (!codecCtx_) { - flushPending_ = false; +void VideoDecoderAsync::DeliverOutput(Napi::Env env, Napi::Function callback, void*, Output* output) { + // The typed dispatch is invoked even when Node drops a queued event at + // teardown. Own it before testing env so the frame is always released. + std::unique_ptr pending(output); + if (env == nullptr) return; + if (pending->frame) { + VideoFrameNative::EmitDecoded(env, callback, std::move(pending->frame)); return; } - // Send NULL packet to flush - avcodec_send_packet(codecCtx_, nullptr); - - AVFrame* frame = av_frame_alloc(); - int ret; - while ((ret = avcodec_receive_frame(codecCtx_, frame)) >= 0) { - AVFrame* outputFrame = av_frame_clone(frame); - - // Keep drain output nonblocking for resource-constrained environments. - if (tsfnOutput_.NonBlockingCall(outputFrame, VideoFrameNative::EmitDecoded) != napi_ok) { - av_frame_free(&outputFrame); + auto flush = pending->flush; + int error = pending->error; + flush.NonBlockingCall([error](Napi::Env env, Napi::Function done) { + if (error < 0) { + char errBuf[256]; + av_strerror(error, errBuf, sizeof(errBuf)); + done.Call({ Napi::Error::New(env, errBuf).Value() }); + } else { + done.Call({ env.Null() }); } + }); + flush.Release(); +} - av_frame_unref(frame); +void VideoDecoderAsync::ProcessFlush(Napi::ThreadSafeFunction flush) { + int ret = AVERROR_EOF; + if (codecCtx_) { + ret = avcodec_send_packet(codecCtx_, nullptr); + if (ret >= 0) ret = ReceiveFrames(); + // Drain puts the codec in EOF state. Allow new input after flush. + avcodec_flush_buffers(codecCtx_); } - av_frame_free(&frame); - - // Draining puts the codec in EOF state; per WebCodecs spec the decoder - // must accept new chunks after flush(), so reset it - avcodec_flush_buffers(codecCtx_); - // Signal flush complete using NonBlockingCall to prevent deadlock - if (tsfnFlush_) { - tsfnFlush_.NonBlockingCall([](Napi::Env env, Napi::Function fn) { - fn.Call({ env.Null() }); - }); - // Queued call still runs; releasing lets the event loop drain after it - tsfnFlush_.Release(); - tsfnFlush_ = Napi::ThreadSafeFunction(); + // A marker in the output FIFO runs after every drained frame callback. + // Its separate flush TSFN stays referenced until that marker is delivered. + // When receive returns EXIT, the output queue is already closing. + if (ret != AVERROR_EXIT) { + QueueOutput({{}, flush, ret == AVERROR_EOF ? 0 : ret}); } - - flushPending_ = false; } void VideoDecoderAsync::Decode(const Napi::CallbackInfo& info) { @@ -364,7 +360,6 @@ void VideoDecoderAsync::Decode(const Napi::CallbackInfo& info) { job.isKeyframe = isKeyframe; job.timestamp = timestamp; job.duration = duration; - job.isFlush = false; { std::lock_guard lock(queueMutex_); @@ -383,23 +378,10 @@ Napi::Value VideoDecoderAsync::Flush(const Napi::CallbackInfo& info) { return env.Undefined(); } - // Create thread-safe function for flush callback - Napi::Function callback = info[0].As(); - if (tsfnFlush_) tsfnFlush_.Release(); // stale handle from an unresolved earlier flush - tsfnFlush_ = Napi::ThreadSafeFunction::New( - env, - callback, - "VideoDecoderAsyncFlush", - 0, - 1 - ); - - flushPending_ = true; - - // Queue flush job + // Each job owns its own completion callback until it reaches the output FIFO. DecodeJob job; - job.isFlush = true; - + job.flush = Napi::ThreadSafeFunction::New( + env, info[0].As(), "VideoDecoderAsyncFlush", 0, 1); { std::lock_guard lock(queueMutex_); jobQueue_.push(std::move(job)); @@ -415,6 +397,8 @@ void VideoDecoderAsync::Reset(const Napi::CallbackInfo& info) { { std::lock_guard lock(queueMutex_); while (!jobQueue_.empty()) { + auto flush = jobQueue_.front().flush; + if (flush) flush.Release(); jobQueue_.pop(); } } @@ -437,6 +421,8 @@ void VideoDecoderAsync::Close(const Napi::CallbackInfo& info) { { std::lock_guard lock(queueMutex_); while (!jobQueue_.empty()) { + auto flush = jobQueue_.front().flush; + if (flush) flush.Release(); jobQueue_.pop(); } } @@ -449,9 +435,8 @@ void VideoDecoderAsync::Close(const Napi::CallbackInfo& info) { // Worker is joined, so no more calls are queued; release now and null the // handles so the destructor doesn't touch already-finalized functions - if (tsfnOutput_) { tsfnOutput_.Release(); tsfnOutput_ = Napi::ThreadSafeFunction(); } + if (tsfnOutput_) { tsfnOutput_.Release(); tsfnOutput_ = decltype(tsfnOutput_)(); } if (tsfnError_) { tsfnError_.Release(); tsfnError_ = Napi::ThreadSafeFunction(); } - if (tsfnFlush_) { tsfnFlush_.Release(); tsfnFlush_ = Napi::ThreadSafeFunction(); } if (tsfnJobDone_) { tsfnJobDone_.Release(); tsfnJobDone_ = Napi::ThreadSafeFunction(); } if (activeJobs_ > 0) { activeJobs_ = 0; diff --git a/native/async_decoder.h b/native/async_decoder.h index 80a49d8..e37a4eb 100644 --- a/native/async_decoder.h +++ b/native/async_decoder.h @@ -7,6 +7,7 @@ #include #include #include +#include "frame.h" extern "C" { #include @@ -20,12 +21,7 @@ struct DecodeJob { bool isKeyframe; int64_t timestamp; int64_t duration; - bool isFlush; -}; - -// Error reported from the worker thread back to JS. -struct DecodeResult { - std::string errorMessage; + Napi::ThreadSafeFunction flush; }; class VideoDecoderAsync : public Napi::ObjectWrap { @@ -49,12 +45,21 @@ class VideoDecoderAsync : public Napi::ObjectWrap { // Process a single decode job (runs on worker thread) void ProcessDecode(DecodeJob& job); - void ProcessFlush(); + void ProcessFlush(Napi::ThreadSafeFunction flush); + int ReceiveFrames(); + void EmitError(int error); + + struct Output { + DecodedFramePtr frame; + Napi::ThreadSafeFunction flush; + int error = 0; + }; + static void DeliverOutput(Napi::Env env, Napi::Function callback, void*, Output* output); + bool QueueOutput(Output output); // Thread-safe functions for callbacks to JS - Napi::ThreadSafeFunction tsfnOutput_; + Napi::TypedThreadSafeFunction tsfnOutput_; Napi::ThreadSafeFunction tsfnError_; - Napi::ThreadSafeFunction tsfnFlush_; // Worker thread std::thread workerThread_; @@ -71,9 +76,6 @@ class VideoDecoderAsync : public Napi::ObjectWrap { std::mutex queueMutex_; std::condition_variable queueCV_; - // Flush synchronization - std::atomic flushPending_{false}; - // FFmpeg context (owned/accessed by worker thread after configure) AVCodecContext* codecCtx_; const AVCodec* codec_; diff --git a/native/decoder.cpp b/native/decoder.cpp index 4564322..5f469e6 100644 --- a/native/decoder.cpp +++ b/native/decoder.cpp @@ -147,6 +147,10 @@ void VideoDecoderNative::Decode(const Napi::CallbackInfo& info) { // Create packet from data AVPacket* packet = av_packet_alloc(); + if (!packet) { + EmitError(env, "Failed to allocate packet"); + return; + } packet->data = data.Data(); packet->size = data.Length(); packet->pts = timestamp; @@ -157,37 +161,28 @@ void VideoDecoderNative::Decode(const Napi::CallbackInfo& info) { packet->flags |= AV_PKT_FLAG_KEY; } - // Send packet to decoder int ret = avcodec_send_packet(codecCtx_, packet); + av_packet_free(&packet); + if (ret >= 0) { + ret = ReceiveFrames(env); + if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; + } if (ret < 0) { char errBuf[256]; av_strerror(ret, errBuf, sizeof(errBuf)); EmitError(env, std::string("Decode error: ") + errBuf); - av_packet_free(&packet); - return; } +} - // Receive decoded frames - AVFrame* frame = av_frame_alloc(); - while (ret >= 0) { - ret = avcodec_receive_frame(codecCtx_, frame); - if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { - break; - } else if (ret < 0) { - char errBuf[256]; - av_strerror(ret, errBuf, sizeof(errBuf)); - EmitError(env, std::string("Decode error: ") + errBuf); - break; - } - - // Clone frame and emit - AVFrame* outputFrame = av_frame_clone(frame); - VideoFrameNative::EmitDecoded(env, outputCallback_.Value(), outputFrame); - av_frame_unref(frame); +int VideoDecoderNative::ReceiveFrames(Napi::Env env) { + while (codecCtx_) { + DecodedFramePtr frame(av_frame_alloc()); + if (!frame) return AVERROR(ENOMEM); + int ret = avcodec_receive_frame(codecCtx_, frame.get()); + if (ret < 0) return ret; + VideoFrameNative::EmitDecoded(env, outputCallback_.Value(), std::move(frame)); } - - av_frame_free(&frame); - av_packet_free(&packet); + return AVERROR_EOF; } void VideoDecoderNative::EmitError(Napi::Env env, const std::string& message) { @@ -197,22 +192,17 @@ void VideoDecoderNative::EmitError(Napi::Env env, const std::string& message) { Napi::Value VideoDecoderNative::Flush(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); - // Flush decoder by sending NULL packet + Napi::Function callback = info[0].As(); if (configured_ && codecCtx_) { - avcodec_send_packet(codecCtx_, nullptr); - - AVFrame* frame = av_frame_alloc(); - int ret; - while ((ret = avcodec_receive_frame(codecCtx_, frame)) >= 0) { - AVFrame* outputFrame = av_frame_clone(frame); - VideoFrameNative::EmitDecoded(env, outputCallback_.Value(), outputFrame); - av_frame_unref(frame); + int ret = avcodec_send_packet(codecCtx_, nullptr); + if (ret >= 0) ret = ReceiveFrames(env); + if (ret < 0 && ret != AVERROR_EOF) { + char errBuf[256]; + av_strerror(ret, errBuf, sizeof(errBuf)); + callback.Call({ Napi::Error::New(env, errBuf).Value() }); + return env.Undefined(); } - av_frame_free(&frame); } - - // Return promise that resolves when queue is empty - Napi::Function callback = info[0].As(); callback.Call({ env.Null() }); return env.Undefined(); diff --git a/native/decoder.h b/native/decoder.h index f6b1e5f..e77c77d 100644 --- a/native/decoder.h +++ b/native/decoder.h @@ -24,6 +24,7 @@ class VideoDecoderNative : public Napi::ObjectWrap { void Reset(const Napi::CallbackInfo& info); void Close(const Napi::CallbackInfo& info); + int ReceiveFrames(Napi::Env env); void EmitError(Napi::Env env, const std::string& message); AVCodecContext* codecCtx_; diff --git a/native/frame.cpp b/native/frame.cpp index 03a12a2..4693620 100644 --- a/native/frame.cpp +++ b/native/frame.cpp @@ -523,12 +523,14 @@ Napi::Value VideoFrameNative::Scale(const Napi::CallbackInfo& info) { return NewInstance(env, out); } -void VideoFrameNative::EmitDecoded(Napi::Env env, const Napi::Function& callback, AVFrame* frame) { +void VideoFrameNative::EmitDecoded(Napi::Env env, const Napi::Function& callback, DecodedFramePtr frame) { // A frame can be released by a later packet or during drain. Its PTS and // duration belong to the decoded picture, regardless of what released it. const int64_t timestamp = frame->pts; - const int64_t duration = NWC_FRAME_DURATION(frame); - Napi::Object nativeFrame = NewInstance(env, frame); + const int64_t duration = NWC_FRAME_DURATION(frame.get()); + Napi::Object nativeFrame = NewInstance(env, frame.get()); + if (nativeFrame.IsEmpty()) return; + frame.release(); callback.Call({ nativeFrame, Napi::Number::New(env, static_cast(timestamp)), @@ -538,7 +540,9 @@ void VideoFrameNative::EmitDecoded(Napi::Env env, const Napi::Function& callback Napi::Object VideoFrameNative::NewInstance(Napi::Env env, AVFrame* frame) { Napi::Object obj = constructor.New({}); + if (obj.IsEmpty()) return obj; VideoFrameNative* instance = Napi::ObjectWrap::Unwrap(obj); + if (!instance) return Napi::Object(); instance->frame_ = frame; instance->ownsFrame_ = true; return obj; diff --git a/native/frame.h b/native/frame.h index a83e46a..6bd5d68 100644 --- a/native/frame.h +++ b/native/frame.h @@ -2,6 +2,7 @@ #define FRAME_H #include +#include extern "C" { #include @@ -18,11 +19,17 @@ extern "C" { #define NWC_FRAME_DURATION(f) ((f)->duration) #endif +struct AvFrameDeleter { + void operator()(AVFrame* frame) const { av_frame_free(&frame); } +}; + +using DecodedFramePtr = std::unique_ptr; + class VideoFrameNative : public Napi::ObjectWrap { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); static Napi::Object NewInstance(Napi::Env env, AVFrame* frame); - static void EmitDecoded(Napi::Env env, const Napi::Function& callback, AVFrame* frame); + static void EmitDecoded(Napi::Env env, const Napi::Function& callback, DecodedFramePtr frame); static Napi::FunctionReference constructor; VideoFrameNative(const Napi::CallbackInfo& info); diff --git a/test/reordered-video-decoder.test.ts b/test/reordered-video-decoder.test.ts index ef34f9b..ea7c46b 100644 --- a/test/reordered-video-decoder.test.ts +++ b/test/reordered-video-decoder.test.ts @@ -11,41 +11,40 @@ type Timing = [timestamp: number, duration: number | null]; const data = path.join(__dirname, 'fixtures', 'reordered-video'); const inventory: Inventory = JSON.parse(readFileSync(path.join(data, 'inventory.json'), 'utf8')); -describe.each([ - ['h264', 'avc1.64001f'], - ['hevc', 'hev1.1.6.L93.B0'], -] as const)('%s reordered video timing', (fixture, codec) => { - it.each([false, true])('preserves decoded picture timing with useWorkerThread=%s', async (useWorkerThread) => { - if (useWorkerThread) expect(typeof native.VideoDecoderAsync).toBe('function'); - const bytes = readFileSync(path.join(data, `${fixture}.bin`)); - const { sizes, displayOrder } = inventory[fixture]; - // Use signed, sometimes equal timestamps in decode order and give every packet - // a distinct duration so the fixture also detects swaps between equal timestamps. - const inputTiming = sizes.map((_, index): [number, number] => [ - (Math.floor(index / 2) - 5) * 1000, - index + 101, - ]); - const expected = displayOrder.map(index => inputTiming[index]); - const output: Timing[] = []; - const errors: Error[] = []; - let firstFrame!: () => void; - const hasOutput = new Promise(resolve => { firstFrame = resolve; }); - const decoder = new VideoDecoder({ - output(frame) { - output.push([frame.timestamp, frame.duration]); - frame.close(); - firstFrame(); - }, - error(error) { - errors.push(error); - }, - }); +function decode(fixture: keyof Inventory, codec: string, useWorkerThread: boolean, runs = 1) { + if (useWorkerThread) expect(typeof native.VideoDecoderAsync).toBe('function'); + const bytes = readFileSync(path.join(data, `${fixture}.bin`)); + const { sizes, displayOrder } = inventory[fixture]; + // Include negative and equal timestamps. Distinct durations distinguish + // pictures with the same timestamp and catch metadata from the wrong packet. + const timing = (index: number): [number, number] => [ + (Math.floor(index / 2) - 5) * 1000, + index + 101, + ]; + const expected = Array.from({ length: runs }, (_, run) => + displayOrder.map(index => timing(run * sizes.length + index)), + ).flat(); + const output: Timing[] = []; + const errors: Error[] = []; + let firstFrame!: () => void; + const hasOutput = new Promise(resolve => { firstFrame = resolve; }); + const decoder = new VideoDecoder({ + output(frame) { + output.push([frame.timestamp, frame.duration]); + frame.close(); + firstFrame(); + }, + error(error) { + errors.push(error); + }, + }); - try { - decoder.configure({ codec, useWorkerThread }); + try { + decoder.configure({ codec, useWorkerThread }); + for (let run = 0; run < runs; run++) { let offset = 0; for (const [index, size] of sizes.entries()) { - const [timestamp, duration] = inputTiming[index]; + const [timestamp, duration] = timing(run * sizes.length + index); decoder.decode(new EncodedVideoChunk({ type: index === 0 ? 'key' : 'delta', timestamp, @@ -55,16 +54,61 @@ describe.each([ offset += size; } expect(offset).toBe(bytes.length); - // Demand an output from decode() before sending any flush request. Drain was - // already using the frame metadata, so a drain-only test would miss the bug. - await hasOutput; - const beforeDrain = output.slice(); - expect(beforeDrain).toEqual(expected.slice(0, beforeDrain.length)); + } + return { decoder, output, errors, expected, hasOutput }; + } catch (error) { + decoder.close(); + throw error; + } +} + +describe.each([ + ['h264', 'avc1.64001f'], + ['hevc', 'hev1.1.6.L93.B0'], +] as const)('%s reordered video timing', (fixture, codec) => { + it('keeps picture metadata during normal output and drain in both decoders', async () => { + const sync = decode(fixture, codec, false); + const drainStart = sync.output.length; + try { + expect(drainStart).toBeGreaterThan(0); + expect(drainStart).toBeLessThan(sync.expected.length); + expect(sync.output).toEqual(sync.expected.slice(0, drainStart)); + await sync.decoder.flush(); + expect(sync.output).toEqual(sync.expected); + expect(sync.errors).toEqual([]); + } finally { + sync.decoder.close(); + } + + const worker = decode(fixture, codec, true); + try { + // Require a normal output before requesting flush. + await worker.hasOutput; + expect(worker.output).toEqual(worker.expected.slice(0, worker.output.length)); + await worker.decoder.flush(); + // Use the synchronous decode/drain boundary to identify the delayed suffix, + // independently of when the JS thread happens to observe worker callbacks. + expect(worker.output.slice(drainStart)).toEqual(sync.output.slice(drainStart)); + expect(worker.output).toEqual(worker.expected); + expect(worker.errors).toEqual([]); + } finally { + worker.decoder.close(); + } + }, 15000); - await decoder.flush(); + it('delivers all worker frames before each flush resolves with a busy queue', async () => { + // More output events than one Node TSFN dispatch turn can consume. Multiple + // pending flushes also exercise ownership of the individual completion handles. + const { decoder, output, errors, expected } = decode(fixture, codec, true, 48); + try { + const first = decoder.flush().then(() => { + expect(output).toEqual(expected); + }); + const second = decoder.flush().then(() => { + expect(output).toEqual(expected); + }); + await Promise.all([first, second]); expect(errors).toEqual([]); - expect(beforeDrain.length).toBeLessThan(output.length); - expect(output).toEqual(expected); } finally { decoder.close(); } From c4aef3b92d2e94380cbe6646ce3546435d72e61a Mon Sep 17 00:00:00 2001 From: Ramadan Date: Mon, 30 Nov 2026 13:17:38 +0000 Subject: [PATCH 3/5] Stress native flush callback ordering behind queued video frames --- test/reordered-video-decoder.test.ts | 67 +++++++++++++++++----------- 1 file changed, 40 insertions(+), 27 deletions(-) diff --git a/test/reordered-video-decoder.test.ts b/test/reordered-video-decoder.test.ts index ea7c46b..6ab5ccb 100644 --- a/test/reordered-video-decoder.test.ts +++ b/test/reordered-video-decoder.test.ts @@ -11,7 +11,7 @@ type Timing = [timestamp: number, duration: number | null]; const data = path.join(__dirname, 'fixtures', 'reordered-video'); const inventory: Inventory = JSON.parse(readFileSync(path.join(data, 'inventory.json'), 'utf8')); -function decode(fixture: keyof Inventory, codec: string, useWorkerThread: boolean, runs = 1) { +function decode(fixture: keyof Inventory, codec: string, useWorkerThread: boolean) { if (useWorkerThread) expect(typeof native.VideoDecoderAsync).toBe('function'); const bytes = readFileSync(path.join(data, `${fixture}.bin`)); const { sizes, displayOrder } = inventory[fixture]; @@ -21,9 +21,7 @@ function decode(fixture: keyof Inventory, codec: string, useWorkerThread: boolea (Math.floor(index / 2) - 5) * 1000, index + 101, ]; - const expected = Array.from({ length: runs }, (_, run) => - displayOrder.map(index => timing(run * sizes.length + index)), - ).flat(); + const expected = displayOrder.map(timing); const output: Timing[] = []; const errors: Error[] = []; let firstFrame!: () => void; @@ -41,20 +39,18 @@ function decode(fixture: keyof Inventory, codec: string, useWorkerThread: boolea try { decoder.configure({ codec, useWorkerThread }); - for (let run = 0; run < runs; run++) { - let offset = 0; - for (const [index, size] of sizes.entries()) { - const [timestamp, duration] = timing(run * sizes.length + index); - decoder.decode(new EncodedVideoChunk({ - type: index === 0 ? 'key' : 'delta', - timestamp, - duration, - data: bytes.subarray(offset, offset + size), - })); - offset += size; - } - expect(offset).toBe(bytes.length); + let offset = 0; + for (const [index, size] of sizes.entries()) { + const [timestamp, duration] = timing(index); + decoder.decode(new EncodedVideoChunk({ + type: index === 0 ? 'key' : 'delta', + timestamp, + duration, + data: bytes.subarray(offset, offset + size), + })); + offset += size; } + expect(offset).toBe(bytes.length); return { decoder, output, errors, expected, hasOutput }; } catch (error) { decoder.close(); @@ -96,18 +92,35 @@ describe.each([ } }, 15000); - it('delivers all worker frames before each flush resolves with a busy queue', async () => { - // More output events than one Node TSFN dispatch turn can consume. Multiple - // pending flushes also exercise ownership of the individual completion handles. - const { decoder, output, errors, expected } = decode(fixture, codec, true, 48); + it('delivers all worker frames before each native flush callback with a busy queue', async () => { + const bytes = readFileSync(path.join(data, `${fixture}.bin`)); + const { sizes } = inventory[fixture]; + const runs = 80; + let seen = 0; + const errors: string[] = []; + const decoder = new native.VideoDecoderAsync( + (frame: { close(): void }) => { seen++; frame.close(); }, + (error: string) => errors.push(error), + ); try { - const first = decoder.flush().then(() => { - expect(output).toEqual(expected); - }); - const second = decoder.flush().then(() => { - expect(output).toEqual(expected); + decoder.configure({ codec: fixture }); + for (let run = 0; run < runs; run++) { + let offset = 0; + for (const [index, size] of sizes.entries()) { + const timestamp = (run * sizes.length + index) * 1000; + decoder.decode(bytes.subarray(offset, offset + size), index === 0, timestamp, index + 1); + offset += size; + } + } + const flush = () => new Promise((resolve, reject) => { + decoder.flush((error: Error | null) => error ? reject(error) : resolve(seen)); }); - await Promise.all([first, second]); + const first = flush(); + const second = flush(); + // Back up the native dispatch queue while the decoder thread works. + // Assert at native completion, before the JS wrapper's extra event-loop wait. + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200); + expect(await Promise.all([first, second])).toEqual([runs * sizes.length, runs * sizes.length]); expect(errors).toEqual([]); } finally { decoder.close(); From 565111c79db91b8fe332238778053b269aa6271f Mon Sep 17 00:00:00 2001 From: Ramadan Date: Mon, 30 Nov 2026 13:19:19 +0000 Subject: [PATCH 4/5] Value-initialize async decoder flush jobs --- native/async_decoder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/async_decoder.cpp b/native/async_decoder.cpp index 8a20997..6830f03 100644 --- a/native/async_decoder.cpp +++ b/native/async_decoder.cpp @@ -379,7 +379,7 @@ Napi::Value VideoDecoderAsync::Flush(const Napi::CallbackInfo& info) { } // Each job owns its own completion callback until it reaches the output FIFO. - DecodeJob job; + DecodeJob job{}; job.flush = Napi::ThreadSafeFunction::New( env, info[0].As(), "VideoDecoderAsyncFlush", 0, 1); { From 47d63abe28a9654b60ad3621500f02220eb4a3dc Mon Sep 17 00:00:00 2001 From: Ramadan Date: Mon, 30 Nov 2026 13:19:44 +0000 Subject: [PATCH 5/5] Preserve worker flush handling of interrupted drains --- native/async_decoder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/async_decoder.cpp b/native/async_decoder.cpp index 6830f03..a99ffe3 100644 --- a/native/async_decoder.cpp +++ b/native/async_decoder.cpp @@ -337,7 +337,7 @@ void VideoDecoderAsync::ProcessFlush(Napi::ThreadSafeFunction flush) { // Its separate flush TSFN stays referenced until that marker is delivered. // When receive returns EXIT, the output queue is already closing. if (ret != AVERROR_EXIT) { - QueueOutput({{}, flush, ret == AVERROR_EOF ? 0 : ret}); + QueueOutput({{}, flush, ret == AVERROR_EOF || ret == AVERROR(EAGAIN) ? 0 : ret}); } }