diff --git a/native/async_decoder.cpp b/native/async_decoder.cpp index 7f6aeab..a99ffe3 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,142 +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.frame = nullptr; - result.isError = true; - 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.frame = nullptr; - result.isError = true; - 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; - } - - // 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)) - }); +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; + } +} - delete res; - }); +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); - - 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; - }); + 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 || ret == AVERROR(EAGAIN) ? 0 : ret}); } - - flushPending_ = false; } void VideoDecoderAsync::Decode(const Napi::CallbackInfo& info) { @@ -402,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_); @@ -421,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 - DecodeJob job; - job.isFlush = true; - + // Each job owns its own completion callback until it reaches the output FIFO. + DecodeJob job{}; + job.flush = Napi::ThreadSafeFunction::New( + env, info[0].As(), "VideoDecoderAsyncFlush", 0, 1); { std::lock_guard lock(queueMutex_); jobQueue_.push(std::move(job)); @@ -453,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(); } } @@ -475,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(); } } @@ -487,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 61c352d..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,17 +21,7 @@ struct DecodeJob { bool isKeyframe; int64_t timestamp; int64_t duration; - bool isFlush; -}; - -// Result from 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; + Napi::ThreadSafeFunction flush; }; class VideoDecoderAsync : public Napi::ObjectWrap { @@ -54,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_; @@ -76,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 53051b7..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,46 +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); - EmitFrame(env, outputFrame, timestamp, duration); - av_frame_unref(frame); } - - av_frame_free(&frame); - 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) - }); +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)); + } + return AVERROR_EOF; } void VideoDecoderNative::EmitError(Napi::Env env, const std::string& message) { @@ -206,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); - EmitFrame(env, outputFrame, frame->pts, NWC_FRAME_DURATION(frame)); - 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 7af290e..e77c77d 100644 --- a/native/decoder.h +++ b/native/decoder.h @@ -24,7 +24,7 @@ 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); + 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 a45ac42..4693620 100644 --- a/native/frame.cpp +++ b/native/frame.cpp @@ -523,9 +523,26 @@ Napi::Value VideoFrameNative::Scale(const Napi::CallbackInfo& info) { return NewInstance(env, out); } +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.get()); + Napi::Object nativeFrame = NewInstance(env, frame.get()); + if (nativeFrame.IsEmpty()) return; + frame.release(); + 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({}); + 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 b4e283c..6bd5d68 100644 --- a/native/frame.h +++ b/native/frame.h @@ -2,6 +2,7 @@ #define FRAME_H #include +#include extern "C" { #include @@ -18,10 +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, DecodedFramePtr 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 0000000..24ac8d7 Binary files /dev/null and b/test/fixtures/reordered-video/h264.bin differ diff --git a/test/fixtures/reordered-video/hevc.bin b/test/fixtures/reordered-video/hevc.bin new file mode 100644 index 0000000..57a05d2 Binary files /dev/null and b/test/fixtures/reordered-video/hevc.bin differ diff --git a/test/fixtures/reordered-video/inventory.json b/test/fixtures/reordered-video/inventory.json new file mode 100644 index 0000000..39cd1f0 --- /dev/null +++ b/test/fixtures/reordered-video/inventory.json @@ -0,0 +1,10 @@ +{ + "h264": { + "sizes": [1431, 46, 30, 25, 17, 37, 22, 17, 17, 91, 25, 17, 18, 55, 42, 23, 23, 37, 47, 27, 20, 103, 37, 20, 19, 75, 38, 18, 20, 40, 32, 18, 18, 76, 32, 21, 17, 28, 20, 17], + "displayOrder": [0, 3, 2, 4, 1, 7, 6, 8, 5, 11, 10, 12, 9, 15, 14, 16, 13, 19, 18, 20, 17, 23, 22, 24, 21, 27, 26, 28, 25, 31, 30, 32, 29, 35, 34, 36, 33, 38, 39, 37] + }, + "hevc": { + "sizes": [3249, 71, 32, 30, 22, 79, 24, 25, 23, 141, 24, 23, 25, 94, 51, 24, 23, 67, 36, 25, 24, 166, 41, 23, 24, 124, 35, 27, 28, 76, 31, 25, 25, 109, 48, 24, 24, 42, 27, 23], + "displayOrder": [0, 3, 2, 4, 1, 7, 6, 8, 5, 11, 10, 12, 9, 15, 14, 16, 13, 19, 18, 20, 17, 23, 22, 24, 21, 27, 26, 28, 25, 31, 30, 32, 29, 35, 34, 36, 33, 39, 38, 37] + } +} diff --git a/test/reordered-video-decoder.test.ts b/test/reordered-video-decoder.test.ts new file mode 100644 index 0000000..6ab5ccb --- /dev/null +++ b/test/reordered-video-decoder.test.ts @@ -0,0 +1,129 @@ +/** Native decoder regression for per-picture timing through reordering and drain. */ +import { readFileSync } from 'fs'; +import path from 'path'; +import { EncodedVideoChunk } from '../src/EncodedVideoChunk'; +import { VideoDecoder } from '../src/VideoDecoder'; +import { native } from '../src/native'; + +type Inventory = Record<'h264' | 'hevc', { sizes: number[]; displayOrder: number[] }>; +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) { + 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 = displayOrder.map(timing); + 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] = 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(); + 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); + + 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 { + 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)); + }); + 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(); + } + }, 15000); +});