@appium/media-proxy 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE +201 -0
  3. package/README.md +184 -2
  4. package/THIRD_PARTY_NOTICES.md +29 -0
  5. package/binding.gyp +90 -0
  6. package/lib/src/background.d.ts +5 -0
  7. package/lib/src/background.d.ts.map +1 -0
  8. package/lib/src/background.js +16 -0
  9. package/lib/src/background.js.map +1 -0
  10. package/lib/src/capabilities.d.ts +9 -0
  11. package/lib/src/capabilities.d.ts.map +1 -0
  12. package/lib/src/capabilities.js +11 -0
  13. package/lib/src/capabilities.js.map +1 -0
  14. package/lib/src/errors.d.ts +26 -0
  15. package/lib/src/errors.d.ts.map +1 -0
  16. package/lib/src/errors.js +40 -0
  17. package/lib/src/errors.js.map +1 -0
  18. package/lib/src/framing/apst.d.ts +43 -0
  19. package/lib/src/framing/apst.d.ts.map +1 -0
  20. package/lib/src/framing/apst.js +126 -0
  21. package/lib/src/framing/apst.js.map +1 -0
  22. package/lib/src/framing/mjpeg-http.d.ts +30 -0
  23. package/lib/src/framing/mjpeg-http.d.ts.map +1 -0
  24. package/lib/src/framing/mjpeg-http.js +148 -0
  25. package/lib/src/framing/mjpeg-http.js.map +1 -0
  26. package/lib/src/framing/mjpeg-multipart.d.ts +11 -0
  27. package/lib/src/framing/mjpeg-multipart.d.ts.map +1 -0
  28. package/lib/src/framing/mjpeg-multipart.js +26 -0
  29. package/lib/src/framing/mjpeg-multipart.js.map +1 -0
  30. package/lib/src/index.d.ts +10 -0
  31. package/lib/src/index.d.ts.map +1 -0
  32. package/lib/src/index.js +7 -0
  33. package/lib/src/index.js.map +1 -0
  34. package/lib/src/native.d.ts +12 -0
  35. package/lib/src/native.d.ts.map +1 -0
  36. package/lib/src/native.js +36 -0
  37. package/lib/src/native.js.map +1 -0
  38. package/lib/src/pkg-root.d.ts +6 -0
  39. package/lib/src/pkg-root.d.ts.map +1 -0
  40. package/lib/src/pkg-root.js +12 -0
  41. package/lib/src/pkg-root.js.map +1 -0
  42. package/lib/src/queue.d.ts +34 -0
  43. package/lib/src/queue.d.ts.map +1 -0
  44. package/lib/src/queue.js +123 -0
  45. package/lib/src/queue.js.map +1 -0
  46. package/lib/src/transcoder.d.ts +81 -0
  47. package/lib/src/transcoder.d.ts.map +1 -0
  48. package/lib/src/transcoder.js +422 -0
  49. package/lib/src/transcoder.js.map +1 -0
  50. package/lib/src/types.d.ts +147 -0
  51. package/lib/src/types.d.ts.map +1 -0
  52. package/lib/src/types.js +2 -0
  53. package/lib/src/types.js.map +1 -0
  54. package/package.json +65 -4
  55. package/prebuilds/darwin-arm64/@appium+media-proxy.node +0 -0
  56. package/prebuilds/darwin-arm64/ffmpeg-LICENSE-LGPL-2.1.txt +502 -0
  57. package/prebuilds/darwin-arm64/ffmpeg-build-info.txt +3 -0
  58. package/prebuilds/darwin-arm64/libavcodec-appium.62.dylib +0 -0
  59. package/prebuilds/darwin-arm64/libavutil-appium.60.dylib +0 -0
  60. package/prebuilds/darwin-arm64/libswscale-appium.9.dylib +0 -0
  61. package/prebuilds/darwin-x64/@appium+media-proxy.node +0 -0
  62. package/prebuilds/darwin-x64/ffmpeg-LICENSE-LGPL-2.1.txt +502 -0
  63. package/prebuilds/darwin-x64/ffmpeg-build-info.txt +3 -0
  64. package/prebuilds/darwin-x64/libavcodec-appium.62.dylib +0 -0
  65. package/prebuilds/darwin-x64/libavutil-appium.60.dylib +0 -0
  66. package/prebuilds/darwin-x64/libswscale-appium.9.dylib +0 -0
  67. package/prebuilds/linux-arm64/@appium+media-proxy.node +0 -0
  68. package/prebuilds/linux-arm64/ffmpeg-LICENSE-LGPL-2.1.txt +502 -0
  69. package/prebuilds/linux-arm64/ffmpeg-build-info.txt +3 -0
  70. package/prebuilds/linux-arm64/libavcodec-appium.so.62 +0 -0
  71. package/prebuilds/linux-arm64/libavutil-appium.so.60 +0 -0
  72. package/prebuilds/linux-arm64/libswscale-appium.so.9 +0 -0
  73. package/prebuilds/linux-x64/@appium+media-proxy.node +0 -0
  74. package/prebuilds/linux-x64/ffmpeg-LICENSE-LGPL-2.1.txt +502 -0
  75. package/prebuilds/linux-x64/ffmpeg-build-info.txt +3 -0
  76. package/prebuilds/linux-x64/libavcodec-appium.so.62 +0 -0
  77. package/prebuilds/linux-x64/libavutil-appium.so.60 +0 -0
  78. package/prebuilds/linux-x64/libswscale-appium.so.9 +0 -0
  79. package/prebuilds/win32-arm64/@appium+media-proxy.node +0 -0
  80. package/prebuilds/win32-arm64/avcodec-appium-62.dll +0 -0
  81. package/prebuilds/win32-arm64/avutil-appium-60.dll +0 -0
  82. package/prebuilds/win32-arm64/ffmpeg-LICENSE-LGPL-2.1.txt +502 -0
  83. package/prebuilds/win32-arm64/ffmpeg-build-info.txt +3 -0
  84. package/prebuilds/win32-arm64/swscale-appium-9.dll +0 -0
  85. package/prebuilds/win32-x64/@appium+media-proxy.node +0 -0
  86. package/prebuilds/win32-x64/avcodec-appium-62.dll +0 -0
  87. package/prebuilds/win32-x64/avutil-appium-60.dll +0 -0
  88. package/prebuilds/win32-x64/ffmpeg-LICENSE-LGPL-2.1.txt +502 -0
  89. package/prebuilds/win32-x64/ffmpeg-build-info.txt +3 -0
  90. package/prebuilds/win32-x64/swscale-appium-9.dll +0 -0
  91. package/scripts/install.mjs +29 -0
  92. package/src/background.ts +15 -0
  93. package/src/capabilities.ts +12 -0
  94. package/src/errors.ts +45 -0
  95. package/src/framing/apst.ts +158 -0
  96. package/src/framing/mjpeg-http.ts +186 -0
  97. package/src/framing/mjpeg-multipart.ts +38 -0
  98. package/src/index.ts +43 -0
  99. package/src/native/addon.cc +402 -0
  100. package/src/native/audio_pipeline.cc +426 -0
  101. package/src/native/audio_pipeline.h +63 -0
  102. package/src/native/ffmpeg_util.h +37 -0
  103. package/src/native/h264_encoder.cc +133 -0
  104. package/src/native/h264_encoder.h +48 -0
  105. package/src/native/mediafoundation_encoder.cc +442 -0
  106. package/src/native/mediafoundation_encoder.h +14 -0
  107. package/src/native/napi_util.h +20 -0
  108. package/src/native/openh264_encoder.cc +285 -0
  109. package/src/native/openh264_encoder.h +14 -0
  110. package/src/native/pipeline.cc +555 -0
  111. package/src/native/pipeline.h +108 -0
  112. package/src/native/vendor/openh264/LICENSE +23 -0
  113. package/src/native/vendor/openh264/codec_api.h +592 -0
  114. package/src/native/vendor/openh264/codec_app_def.h +820 -0
  115. package/src/native/vendor/openh264/codec_def.h +216 -0
  116. package/src/native/vendor/openh264/codec_ver.h +15 -0
  117. package/src/native/videotoolbox_encoder.cc +314 -0
  118. package/src/native/videotoolbox_encoder.h +13 -0
  119. package/src/native.ts +51 -0
  120. package/src/pkg-root.ts +14 -0
  121. package/src/queue.ts +133 -0
  122. package/src/transcoder.ts +480 -0
  123. package/src/types.ts +158 -0
@@ -0,0 +1,402 @@
1
+ // N-API entry point: wraps the FFmpeg pipeline (pipeline.cc) for the TS layer in src/native.ts.
2
+ #include <napi.h>
3
+
4
+ #include <array>
5
+ #include <atomic>
6
+ #include <memory>
7
+ #include <optional>
8
+ #include <utility>
9
+ #include <vector>
10
+
11
+ #include "audio_pipeline.h"
12
+ #include "napi_util.h"
13
+ #include "pipeline.h"
14
+
15
+ namespace {
16
+
17
+ using media_proxy::AudioConfig;
18
+ using media_proxy::AudioPipeline;
19
+ using media_proxy::EncodedUnit;
20
+ using media_proxy::Pipeline;
21
+ using media_proxy::PipelineConfig;
22
+ using media_proxy::PipelineError;
23
+
24
+ // Encoded units waiting for the JS thread; beyond this new ones are dropped so a stalled loop can't grow memory.
25
+ // Fine for MJPEG (every frame stands alone); H.264 must resync to the next key frame instead.
26
+ constexpr size_t kMaxPendingUnits = 60;
27
+ // Audio units are tiny and never need a resync; this only bounds a stalled loop (~5 s of 10 ms units).
28
+ constexpr size_t kMaxPendingAudioUnits = 500;
29
+
30
+ // Shared with in-flight events, so late events never touch a dead session. JS-thread-only, except the counter.
31
+ // The callbacks are weak: the handle's `callbacks` array owns them, so an abandoned transcoder stays collectable.
32
+ struct JsState {
33
+ Napi::FunctionReference onUnit;
34
+ Napi::FunctionReference onError;
35
+ napi_deferred deferred = nullptr; // resolved on the JS thread when close() finishes
36
+ std::shared_ptr<void> keepAlive; // the Session itself, held while close() drains so GC can't abort it
37
+ std::atomic<size_t> pendingUnits{0};
38
+ std::atomic<size_t> pendingAudioUnits{0};
39
+ };
40
+
41
+ struct Event {
42
+ enum class Kind : uint8_t { kUnit, kError, kDone };
43
+ Kind kind = Kind::kUnit;
44
+ EncodedUnit unit;
45
+ PipelineError error;
46
+ std::shared_ptr<JsState> state;
47
+ bool audio = false;
48
+ };
49
+
50
+ // Owns one transcoder: the pipeline (worker thread) plus the thread-safe bridge back to JS.
51
+ class Session : public std::enable_shared_from_this<Session> {
52
+ public:
53
+ Session(Napi::Env env, const PipelineConfig& config, const std::optional<AudioConfig>& audio,
54
+ const Napi::Function& onUnit, const Napi::Function& onError)
55
+ : env_(env), isH264_(config.outputCodec == "h264"), state_(std::make_shared<JsState>()) {
56
+ state_->onUnit = Napi::Weak(onUnit);
57
+ state_->onError = Napi::Weak(onError);
58
+ // The bridge's own function is a no-op: it must not keep JS objects alive.
59
+ tsfn_ = Napi::ThreadSafeFunction::New(env, Napi::Function::New(env, [](const Napi::CallbackInfo&) {}),
60
+ "media-proxy", 0, 1);
61
+ // An abandoned transcoder must not keep the process alive; close() re-refs while it flushes.
62
+ tsfn_.Unref(env);
63
+ // Registered after the tsfn, so at environment teardown this runs first (see Shutdown()).
64
+ napi_add_env_cleanup_hook(env_, &Session::OnEnvCleanup, this);
65
+ try {
66
+ pipeline_ = std::make_unique<Pipeline>(
67
+ config, [this](EncodedUnit&& unit) { PostUnit(std::move(unit)); },
68
+ [this](PipelineError&& err) { Post(Event::Kind::kError, {}, std::move(err)); }, keyFrameRequested_);
69
+ if (audio) {
70
+ audioPipeline_ = std::make_unique<AudioPipeline>(
71
+ *audio, [this](EncodedUnit&& unit) { PostAudioUnit(std::move(unit)); },
72
+ [this](PipelineError&& err) { Post(Event::Kind::kError, {}, std::move(err)); });
73
+ }
74
+ } catch (...) {
75
+ napi_remove_env_cleanup_hook(env_, &Session::OnEnvCleanup, this);
76
+ ReleaseBridge(); // the destructor won't run for a half-built Session
77
+ throw;
78
+ }
79
+ }
80
+
81
+ ~Session() {
82
+ if (!shutdown_) {
83
+ napi_remove_env_cleanup_hook(env_, &Session::OnEnvCleanup, this);
84
+ }
85
+ audioPipeline_.reset(); // joins the workers before the bridge goes away
86
+ pipeline_.reset();
87
+ ReleaseBridge();
88
+ }
89
+ Session(const Session&) = delete;
90
+ Session& operator=(const Session&) = delete;
91
+
92
+ void Push(const Napi::CallbackInfo& info) {
93
+ const Napi::Env env = info.Env();
94
+ if (info.Length() < 3 || !info[0].IsArray() || !info[1].IsNumber() || !info[2].IsBoolean()) {
95
+ throw Napi::TypeError::New(env, "push(chunks: Buffer[], timestampMicros: number, isKeyFrame: boolean)");
96
+ }
97
+ if (closing_) {
98
+ return;
99
+ }
100
+ const auto chunks = info[0].As<Napi::Array>();
101
+ std::vector<uint8_t> unit;
102
+ for (uint32_t i = 0; i < chunks.Length(); ++i) {
103
+ const Napi::Value chunk = chunks.Get(i);
104
+ if (!chunk.IsBuffer()) {
105
+ throw Napi::TypeError::New(env, "chunks must be Buffers");
106
+ }
107
+ const auto buffer = chunk.As<Napi::Buffer<uint8_t>>();
108
+ unit.insert(unit.end(), media_proxy::kAnnexBStartCode.begin(), media_proxy::kAnnexBStartCode.end());
109
+ unit.insert(unit.end(), buffer.Data(), buffer.Data() + buffer.Length());
110
+ }
111
+ if (unit.empty()) {
112
+ return;
113
+ }
114
+ pipeline_->Push(std::move(unit), info[1].As<Napi::Number>().Int64Value(), info[2].As<Napi::Boolean>().Value());
115
+ }
116
+
117
+ void PushAudio(const Napi::CallbackInfo& info) {
118
+ const Napi::Env env = info.Env();
119
+ if (info.Length() < 2 || !info[0].IsBuffer() || !info[1].IsNumber()) {
120
+ throw Napi::TypeError::New(env, "pushAudio(data: Buffer, timestampMicros: number)");
121
+ }
122
+ if (closing_ || !audioPipeline_) {
123
+ return;
124
+ }
125
+ const auto buffer = info[0].As<Napi::Buffer<uint8_t>>();
126
+ audioPipeline_->Push(std::vector<uint8_t>(buffer.Data(), buffer.Data() + buffer.Length()),
127
+ info[1].As<Napi::Number>().Int64Value());
128
+ }
129
+
130
+ void RequestKeyFrame() { keyFrameRequested_.store(true); }
131
+
132
+ void SetRotation(const Napi::CallbackInfo& info) {
133
+ if (info.Length() < 1 || !info[0].IsNumber()) {
134
+ throw Napi::TypeError::New(info.Env(), "setRotation(degrees: number)");
135
+ }
136
+ pipeline_->SetRotation(info[0].As<Napi::Number>().Int32Value());
137
+ }
138
+
139
+ Napi::Value Close(const Napi::Env& env) {
140
+ if (!closing_) {
141
+ closing_ = true;
142
+ napi_value promise = nullptr;
143
+ if (napi_create_promise(env, &state_->deferred, &promise) != napi_ok) {
144
+ throw Napi::Error::New(env, "Could not create the close() promise");
145
+ }
146
+ closePromise_ = Napi::Persistent(Napi::Promise(env, promise));
147
+ state_->keepAlive = shared_from_this();
148
+ tsfn_.Ref(env);
149
+ // Safe even if Deliver destroys *this meanwhile: ~Session joins the workers before members die.
150
+ remainingWorkers_ = audioPipeline_ ? 2 : 1;
151
+ const auto workerDone = [this] {
152
+ if (--remainingWorkers_ == 0) {
153
+ Post(Event::Kind::kDone, {}, {});
154
+ ReleaseBridge();
155
+ }
156
+ };
157
+ pipeline_->Finish(workerDone);
158
+ if (audioPipeline_) {
159
+ audioPipeline_->Finish(workerDone);
160
+ }
161
+ }
162
+ return closePromise_.Value();
163
+ }
164
+
165
+ private:
166
+ static void OnEnvCleanup(void* self) { static_cast<Session*>(self)->Shutdown(); }
167
+
168
+ // Environment teardown: stop the worker now and leave the tsfn to Node. Releasing it later from a
169
+ // finalizer (which runs while Node holds the tsfn's lock) would deadlock.
170
+ void Shutdown() {
171
+ shutdown_ = true;
172
+ audioPipeline_.reset();
173
+ pipeline_.reset();
174
+ released_.store(true);
175
+ // A close() interrupted here would otherwise keep the session alive forever (done is never posted).
176
+ const auto self = std::move(state_->keepAlive);
177
+ // `self` may be the last owner: nothing below this line may touch *this.
178
+ }
179
+
180
+ void ReleaseBridge() {
181
+ if (!released_.exchange(true)) {
182
+ tsfn_.Release();
183
+ }
184
+ }
185
+
186
+ // Dropping an H.264 unit breaks the prediction chain: skip everything up to a fresh key frame and ask for one.
187
+ void PostUnit(EncodedUnit&& unit) {
188
+ if (state_->pendingUnits.load() >= kMaxPendingUnits) {
189
+ if (isH264_) {
190
+ awaitingKeyFrame_ = true;
191
+ keyFrameRequested_.store(true);
192
+ }
193
+ return;
194
+ }
195
+ if (awaitingKeyFrame_ && !unit.isKeyFrame) {
196
+ return;
197
+ }
198
+ awaitingKeyFrame_ = false;
199
+ ++state_->pendingUnits;
200
+ Post(Event::Kind::kUnit, std::move(unit), {});
201
+ }
202
+
203
+ void PostAudioUnit(EncodedUnit&& unit) {
204
+ if (state_->pendingAudioUnits.load() >= kMaxPendingAudioUnits) {
205
+ return;
206
+ }
207
+ ++state_->pendingAudioUnits;
208
+ Post(Event::Kind::kUnit, std::move(unit), {}, true);
209
+ }
210
+
211
+ void Post(Event::Kind kind, EncodedUnit&& unit, PipelineError&& error, bool audio = false) {
212
+ auto* event = new Event{kind, std::move(unit), std::move(error), state_, audio};
213
+ if (tsfn_.NonBlockingCall(event, Deliver) != napi_ok) {
214
+ if (kind == Event::Kind::kUnit) {
215
+ --(audio ? state_->pendingAudioUnits : state_->pendingUnits);
216
+ }
217
+ delete event;
218
+ }
219
+ }
220
+
221
+ // Runs on the JS thread, called from C. Raw N-API on purpose: while a worker is being terminated these calls
222
+ // fail, and node-addon-api would abort the process building its C++ Error for the failure. A failure just
223
+ // drops the event (a pending JS exception is left for Node to report).
224
+ static void Deliver(Napi::Env env, Napi::Function /*bridge*/, Event* raw) {
225
+ const std::unique_ptr<Event> event(raw);
226
+ JsState& state = *event->state;
227
+ switch (event->kind) {
228
+ case Event::Kind::kUnit:
229
+ --(event->audio ? state.pendingAudioUnits : state.pendingUnits);
230
+ DeliverUnit(env, state, *event);
231
+ break;
232
+ case Event::Kind::kError:
233
+ DeliverError(env, state, *event);
234
+ break;
235
+ case Event::Kind::kDone:
236
+ if (state.deferred != nullptr) {
237
+ napi_value undefined = nullptr;
238
+ if (napi_get_undefined(env, &undefined) == napi_ok) {
239
+ napi_resolve_deferred(env, state.deferred, undefined);
240
+ }
241
+ state.deferred = nullptr;
242
+ }
243
+ state.keepAlive.reset(); // may destroy the Session (and join its finished worker) right here
244
+ break;
245
+ }
246
+ }
247
+
248
+ static void CallWithArgument(napi_env env, napi_ref callbackRef, napi_value argument) {
249
+ napi_value callback = nullptr;
250
+ napi_value global = nullptr;
251
+ napi_value ignored = nullptr;
252
+ if (napi_get_reference_value(env, callbackRef, &callback) != napi_ok || callback == nullptr) {
253
+ return; // the transcoder was garbage collected
254
+ }
255
+ if (napi_get_global(env, &global) == napi_ok) {
256
+ napi_call_function(env, global, callback, 1, &argument, &ignored);
257
+ }
258
+ }
259
+
260
+ static void DeliverUnit(napi_env env, JsState& state, Event& event) {
261
+ napi_value unit = nullptr;
262
+ napi_value data = nullptr;
263
+ napi_value isKeyFrame = nullptr;
264
+ napi_value timestamp = nullptr;
265
+ napi_value audio = nullptr;
266
+ const std::vector<uint8_t>& bytes = event.unit.data;
267
+ if (napi_create_object(env, &unit) != napi_ok ||
268
+ napi_create_buffer_copy(env, bytes.size(), bytes.data(), nullptr, &data) != napi_ok ||
269
+ napi_get_boolean(env, event.unit.isKeyFrame, &isKeyFrame) != napi_ok ||
270
+ napi_create_double(env, static_cast<double>(event.unit.timestampMicros), &timestamp) != napi_ok ||
271
+ napi_set_named_property(env, unit, "data", data) != napi_ok ||
272
+ napi_set_named_property(env, unit, "isKeyFrame", isKeyFrame) != napi_ok ||
273
+ napi_set_named_property(env, unit, "timestampMicros", timestamp) != napi_ok) {
274
+ return;
275
+ }
276
+ if (event.audio && (napi_get_boolean(env, true, &audio) != napi_ok ||
277
+ napi_set_named_property(env, unit, "audio", audio) != napi_ok)) {
278
+ return;
279
+ }
280
+ CallWithArgument(env, state.onUnit, unit);
281
+ }
282
+
283
+ static void DeliverError(napi_env env, JsState& state, Event& event) {
284
+ napi_value message = nullptr;
285
+ napi_value name = nullptr;
286
+ napi_value error = nullptr;
287
+ if (napi_create_string_utf8(env, event.error.message.c_str(), NAPI_AUTO_LENGTH, &message) != napi_ok ||
288
+ napi_create_string_utf8(env, event.error.name.c_str(), NAPI_AUTO_LENGTH, &name) != napi_ok ||
289
+ napi_create_error(env, nullptr, message, &error) != napi_ok ||
290
+ napi_set_named_property(env, error, "name", name) != napi_ok) {
291
+ return;
292
+ }
293
+ CallWithArgument(env, state.onError, error);
294
+ }
295
+
296
+ napi_env env_;
297
+ bool isH264_;
298
+ std::shared_ptr<JsState> state_;
299
+ Napi::ThreadSafeFunction tsfn_;
300
+ Napi::Reference<Napi::Promise> closePromise_;
301
+ std::atomic<bool> released_{false};
302
+ bool shutdown_ = false;
303
+ bool closing_ = false;
304
+ bool awaitingKeyFrame_ = false; // worker thread only
305
+ std::atomic<bool> keyFrameRequested_{false};
306
+ std::atomic<int> remainingWorkers_{0};
307
+ std::unique_ptr<Pipeline> pipeline_;
308
+ std::unique_ptr<AudioPipeline> audioPipeline_; // last: destroyed (and joined) first
309
+ };
310
+
311
+ double ReadNumber(const Napi::Object& config, const char* key) {
312
+ return config.Get(key).As<Napi::Number>().DoubleValue();
313
+ }
314
+
315
+ // For options the TS layer always sends but a raw caller of the addon may leave out.
316
+ double ReadOptionalNumber(const Napi::Object& config, const char* key, double fallback) {
317
+ const Napi::Value value = config.Get(key);
318
+ return value.IsNumber() ? value.As<Napi::Number>().DoubleValue() : fallback;
319
+ }
320
+
321
+ Napi::Array ToArray(const Napi::Env& env, const std::vector<std::string>& names) {
322
+ Napi::Array out = Napi::Array::New(env, names.size());
323
+ for (size_t i = 0; i < names.size(); ++i) {
324
+ out.Set(static_cast<uint32_t>(i), names[i]);
325
+ }
326
+ return out;
327
+ }
328
+
329
+ Napi::Value Capabilities(const Napi::CallbackInfo& info) {
330
+ const Napi::Env env = info.Env();
331
+ const media_proxy::Capabilities probed = Pipeline::Probe();
332
+ Napi::Object caps = Napi::Object::New(env);
333
+ caps.Set("decoders", ToArray(env, probed.decoders));
334
+ caps.Set("encoders", ToArray(env, probed.encoders));
335
+ return caps;
336
+ }
337
+
338
+ Napi::Value CreateTranscoder(const Napi::CallbackInfo& info) {
339
+ const Napi::Env env = info.Env();
340
+ if (info.Length() < 3 || !info[0].IsObject() || !info[1].IsFunction() || !info[2].IsFunction()) {
341
+ throw Napi::TypeError::New(env, "createTranscoder(config, onUnit, onError)");
342
+ }
343
+ const auto config = info[0].As<Napi::Object>();
344
+ PipelineConfig pipelineConfig;
345
+ pipelineConfig.outputCodec = config.Get("outputCodec").As<Napi::String>().Utf8Value();
346
+ pipelineConfig.fps = ReadNumber(config, "fps");
347
+ pipelineConfig.bitrate = ReadNumber(config, "bitrate");
348
+ pipelineConfig.quality = ReadNumber(config, "quality");
349
+ pipelineConfig.scale = ReadNumber(config, "scale");
350
+ pipelineConfig.cropWidth = static_cast<int>(ReadOptionalNumber(config, "cropWidth", 0));
351
+ pipelineConfig.cropHeight = static_cast<int>(ReadOptionalNumber(config, "cropHeight", 0));
352
+ pipelineConfig.rotation = static_cast<int>(ReadOptionalNumber(config, "rotation", 0));
353
+
354
+ std::optional<AudioConfig> audioConfig;
355
+ if (config.Get("audio").ToBoolean().Value()) {
356
+ const Napi::Value asc = config.Get("audioSpecificConfig");
357
+ if (!asc.IsBuffer()) {
358
+ throw Napi::TypeError::New(env, "audioSpecificConfig must be a Buffer");
359
+ }
360
+ const auto bytes = asc.As<Napi::Buffer<uint8_t>>();
361
+ audioConfig.emplace();
362
+ audioConfig->audioSpecificConfig.assign(bytes.Data(), bytes.Data() + bytes.Length());
363
+ audioConfig->bitratePerChannel = ReadNumber(config, "audioBitratePerChannel");
364
+ }
365
+
366
+ std::shared_ptr<Session> session;
367
+ try {
368
+ session = std::make_shared<Session>(env, pipelineConfig, audioConfig, info[1].As<Napi::Function>(),
369
+ info[2].As<Napi::Function>());
370
+ } catch (const PipelineError& err) {
371
+ media_proxy::ThrowTyped(env, err.name.c_str(), err.message);
372
+ }
373
+
374
+ Napi::Object handle = Napi::Object::New(env);
375
+ // The session only holds the callbacks weakly; keeping them on the handle ties their lifetime to it.
376
+ Napi::Array callbacks = Napi::Array::New(env, 2);
377
+ callbacks.Set(0U, info[1]);
378
+ callbacks.Set(1U, info[2]);
379
+ handle.Set("callbacks", callbacks);
380
+ handle.Set("push", Napi::Function::New(env, [session](const Napi::CallbackInfo& call) { session->Push(call); }));
381
+ handle.Set("pushAudio",
382
+ Napi::Function::New(env, [session](const Napi::CallbackInfo& call) { session->PushAudio(call); }));
383
+ handle.Set("requestKeyFrame",
384
+ Napi::Function::New(env, [session](const Napi::CallbackInfo&) { session->RequestKeyFrame(); }));
385
+ handle.Set("setRotation",
386
+ Napi::Function::New(env, [session](const Napi::CallbackInfo& call) { session->SetRotation(call); }));
387
+ handle.Set("close", Napi::Function::New(
388
+ env, [session](const Napi::CallbackInfo& call) { return session->Close(call.Env()); }));
389
+ return handle;
390
+ }
391
+
392
+ Napi::Object Init(Napi::Env env, Napi::Object exports) {
393
+ exports.Set("capabilities", Napi::Function::New(env, Capabilities));
394
+ exports.Set("createTranscoder", Napi::Function::New(env, CreateTranscoder));
395
+ return exports;
396
+ }
397
+
398
+ } // namespace
399
+
400
+ // NODE_API_MODULE expands to a static registration function that clang-tidy flags; same as tuntap.
401
+ // NOLINTNEXTLINE(misc-use-anonymous-namespace)
402
+ NODE_API_MODULE(media_proxy, Init)