Repository navigation
Expand file tree
/
Copy pathdecoder.cpp
More file actions
244 lines (203 loc) · 7.77 KB
/
Copy pathdecoder.cpp
File metadata and controls
244 lines (203 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#include "decoder.h"
#include "frame.h"
Napi::FunctionReference VideoDecoderNative::constructor;
Napi::Object VideoDecoderNative::Init(Napi::Env env, Napi::Object exports) {
Napi::Function func = DefineClass(env, "VideoDecoderNative", {
InstanceMethod("configure", &VideoDecoderNative::Configure),
InstanceMethod("decode", &VideoDecoderNative::Decode),
InstanceMethod("flush", &VideoDecoderNative::Flush),
InstanceMethod("reset", &VideoDecoderNative::Reset),
InstanceMethod("close", &VideoDecoderNative::Close),
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("VideoDecoderNative", func);
return exports;
}
VideoDecoderNative::VideoDecoderNative(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<VideoDecoderNative>(info)
, codecCtx_(nullptr)
, codec_(nullptr)
, configured_(false) {
Napi::Env env = info.Env();
if (info.Length() < 2) {
Napi::TypeError::New(env, "Expected 2 callbacks").ThrowAsJavaScriptException();
return;
}
// Store callbacks directly for synchronous operations
outputCallback_ = Napi::Persistent(info[0].As<Napi::Function>());
errorCallback_ = Napi::Persistent(info[1].As<Napi::Function>());
}
VideoDecoderNative::~VideoDecoderNative() {
if (codecCtx_) {
avcodec_free_context(&codecCtx_);
}
}
void VideoDecoderNative::Configure(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (!info[0].IsObject()) {
Napi::TypeError::New(env, "Config must be an object").ThrowAsJavaScriptException();
return;
}
Napi::Object config = info[0].As<Napi::Object>();
std::string codecName = config.Get("codec").As<Napi::String>().Utf8Value();
// For H.264 decoding, use the decoder not encoder
if (codecName == "libx264") {
codecName = "h264";
}
// For AV1, prefer libdav1d (software decoder) over hardware decoder
// since hardware AV1 decoding may not be available on all platforms
if (codecName == "av1") {
codec_ = avcodec_find_decoder_by_name("libdav1d");
if (!codec_) {
// Fallback to libaom-av1 software decoder
codec_ = avcodec_find_decoder_by_name("libaom-av1");
}
if (!codec_) {
// Last resort: try generic AV1 decoder
codec_ = avcodec_find_decoder(AV_CODEC_ID_AV1);
}
} else {
codec_ = avcodec_find_decoder_by_name(codecName.c_str());
}
if (!codec_) {
// Try by codec ID
if (codecName == "h264") {
codec_ = avcodec_find_decoder(AV_CODEC_ID_H264);
} else if (codecName == "vp8") {
codec_ = avcodec_find_decoder(AV_CODEC_ID_VP8);
} else if (codecName == "vp9") {
codec_ = avcodec_find_decoder(AV_CODEC_ID_VP9);
} else if (codecName == "hevc") {
codec_ = avcodec_find_decoder(AV_CODEC_ID_HEVC);
}
}
if (!codec_) {
Napi::Error::New(env, "Codec not found: " + codecName).ThrowAsJavaScriptException();
return;
}
codecCtx_ = avcodec_alloc_context3(codec_);
if (!codecCtx_) {
Napi::Error::New(env, "Failed to allocate codec context").ThrowAsJavaScriptException();
return;
}
// Set dimensions if provided
if (config.Has("width")) {
codecCtx_->width = config.Get("width").As<Napi::Number>().Int32Value();
}
if (config.Has("height")) {
codecCtx_->height = config.Get("height").As<Napi::Number>().Int32Value();
}
// Set extradata (AVCC format for H.264)
if (config.Has("extradata")) {
Napi::Buffer<uint8_t> extradata = config.Get("extradata").As<Napi::Buffer<uint8_t>>();
codecCtx_->extradata_size = extradata.Length();
codecCtx_->extradata = (uint8_t*)av_malloc(extradata.Length() + AV_INPUT_BUFFER_PADDING_SIZE);
memcpy(codecCtx_->extradata, extradata.Data(), extradata.Length());
memset(codecCtx_->extradata + extradata.Length(), 0, AV_INPUT_BUFFER_PADDING_SIZE);
}
// 0 = auto-detect core count; default of 1 leaves multicore decode on the table
codecCtx_->thread_count = 0;
// Open codec
int ret = avcodec_open2(codecCtx_, codec_, nullptr);
if (ret < 0) {
char errBuf[256];
av_strerror(ret, errBuf, sizeof(errBuf));
avcodec_free_context(&codecCtx_);
Napi::Error::New(env, std::string("Failed to open codec: ") + errBuf).ThrowAsJavaScriptException();
return;
}
configured_ = true;
}
void VideoDecoderNative::Decode(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (!configured_) {
Napi::Error::New(env, "Decoder not configured").ThrowAsJavaScriptException();
return;
}
Napi::Buffer<uint8_t> data = info[0].As<Napi::Buffer<uint8_t>>();
bool isKeyframe = info[1].As<Napi::Boolean>().Value();
int64_t timestamp = info[2].As<Napi::Number>().Int64Value();
int64_t duration = info[3].As<Napi::Number>().Int64Value();
// Create packet from data
AVPacket* packet = av_packet_alloc();
packet->data = data.Data();
packet->size = data.Length();
packet->pts = timestamp;
packet->dts = timestamp;
packet->duration = duration;
if (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));
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)
});
}
void VideoDecoderNative::EmitError(Napi::Env env, const std::string& message) {
errorCallback_.Value().Call({ Napi::String::New(env, message) });
}
Napi::Value VideoDecoderNative::Flush(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
// Flush decoder by sending NULL packet
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);
}
av_frame_free(&frame);
}
// Return promise that resolves when queue is empty
Napi::Function callback = info[0].As<Napi::Function>();
callback.Call({ env.Null() });
return env.Undefined();
}
void VideoDecoderNative::Reset(const Napi::CallbackInfo& info) {
// Reset codec state
if (codecCtx_) {
avcodec_flush_buffers(codecCtx_);
}
}
void VideoDecoderNative::Close(const Napi::CallbackInfo& info) {
if (codecCtx_) {
avcodec_free_context(&codecCtx_);
codecCtx_ = nullptr;
}
configured_ = false;
}