Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 88 additions & 141 deletions native/async_decoder.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#include "async_decoder.h"
#include "env_state.h"
#include "frame.h"
#include <utility>

Napi::FunctionReference VideoDecoderAsync::constructor;

Expand Down Expand Up @@ -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<Napi::Function>(),
"VideoDecoderAsyncOutput",
Expand All @@ -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);

Expand Down Expand Up @@ -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();
}
}
Expand Down Expand Up @@ -216,7 +220,7 @@ void VideoDecoderAsync::WorkerThread() {
return !jobQueue_.empty() || !running_;
});

if (!running_ && jobQueue_.empty()) {
if (!running_) {
break;
}

Expand All @@ -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);
});
Expand All @@ -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<int>(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<double>(res->timestamp)),
Napi::Number::New(env, static_cast<double>(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<Output>(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<Output> 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<double>(res->timestamp)),
Napi::Number::New(env, static_cast<double>(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) {
Expand All @@ -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<std::mutex> lock(queueMutex_);
Expand All @@ -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<Napi::Function>();
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<Napi::Function>(), "VideoDecoderAsyncFlush", 0, 1);
{
std::lock_guard<std::mutex> lock(queueMutex_);
jobQueue_.push(std::move(job));
Expand All @@ -453,6 +397,8 @@ void VideoDecoderAsync::Reset(const Napi::CallbackInfo& info) {
{
std::lock_guard<std::mutex> lock(queueMutex_);
while (!jobQueue_.empty()) {
auto flush = jobQueue_.front().flush;
if (flush) flush.Release();
jobQueue_.pop();
}
}
Expand All @@ -475,6 +421,8 @@ void VideoDecoderAsync::Close(const Napi::CallbackInfo& info) {
{
std::lock_guard<std::mutex> lock(queueMutex_);
while (!jobQueue_.empty()) {
auto flush = jobQueue_.front().flush;
if (flush) flush.Release();
jobQueue_.pop();
}
}
Expand All @@ -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;
Expand Down
Loading