forked from BabylonJS/BabylonNative
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediaStream.cpp
More file actions
381 lines (316 loc) · 16.1 KB
/
MediaStream.cpp
File metadata and controls
381 lines (316 loc) · 16.1 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#if defined(_MSC_VER)
// Disable the compiler warning for unreachable code due to CameraDevice being stubbed out on the windows platform
#pragma warning(disable : 4702)
#endif
#include "MediaStream.h"
#include "CameraDevice.h"
#include "Constraint.h"
#include <assert.h>
namespace Babylon::Plugins
{
arcana::task<Napi::Object, std::exception_ptr> MediaStream::NewAsync(Napi::Env env, Napi::Object constraints)
{
// Create a an object reference to the mediaStream javascript object so that it is not destructed during the async operation
auto mediaStreamObject{Napi::Persistent(GetConstructor(env).New({}))};
auto mediaStream{MediaStream::Unwrap(mediaStreamObject.Value())};
return mediaStream->ApplyInitialConstraintsAsync(constraints).then(arcana::inline_scheduler, arcana::cancellation::none(), [mediaStreamObject{ std::move(mediaStreamObject) }]() {
return mediaStreamObject.Value();
});
}
Napi::Function MediaStream::GetConstructor(Napi::Env env)
{
Napi::Object _native{JsRuntime::NativeObject::GetFromJavaScript(env)};
Napi::Value ctorValue{_native.Get(JS_CLASS_NAME)};
Napi::Function ctor{ctorValue.IsFunction() ? ctorValue.As<Napi::Function>() : Napi::Function{}};
if (ctor.IsEmpty() || ctor.IsUndefined())
{
// Initialize the persistent constructor
ctor = DefineClass(
env,
JS_CLASS_NAME,
{
InstanceMethod("getTracks", &MediaStream::GetVideoTracks), // The only supported tracks are video tracks
InstanceMethod("getVideoTracks", &MediaStream::GetVideoTracks),
InstanceMethod("getAudioTracks", &MediaStream::GetAudioTracks),
InstanceMethod("applyConstraints", &MediaStream::ApplyConstraints),
InstanceMethod("getCapabilities", &MediaStream::GetCapabilities),
InstanceMethod("getSettings", &MediaStream::GetSettings),
InstanceMethod("getConstraints", &MediaStream::GetConstraints),
InstanceMethod("stop", &MediaStream::Stop),
});
_native.Set(JS_CLASS_NAME, ctor);
}
return ctor;
}
MediaStream::MediaStream(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<MediaStream>{info}
, m_runtimeScheduler{JsRuntime::GetFromJavaScript(info.Env())}
{
}
MediaStream::~MediaStream()
{
m_cancellationSource.cancel();
// HACK: This is a hack to make sure the camera device is destroyed on the JS thread.
// The napi-jsi adapter currently calls the destructors of JS objects possibly on the wrong thread.
// Once this is fixed, this hack will no longer be needed.
if (m_cameraDevice != nullptr)
{
// The cameraDevice should be destroyed on the JS thread as it may need to access main thread resources
// move ownership of the cameraDevice to a lambda and dispatch it with the runtimeScheduler so the destructor
// is called from that thread.
m_runtimeScheduler.Get()([cameraDevice = std::move(m_cameraDevice)]() {});
}
m_runtimeScheduler.Rundown();
}
Napi::Value MediaStream::GetVideoTracks(const Napi::CallbackInfo& info)
{
// To simply the implementation (because only a single track is supported by the native implementation) the same
// ObjectWrap fullfills the MediaStream and MediaStreamTrack interfaces
auto tracks = Napi::Array::New(info.Env(), 1);
tracks.Set(uint32_t{0}, info.This());
return std::move(tracks);
}
Napi::Value MediaStream::GetAudioTracks(const Napi::CallbackInfo& info)
{
// Only video tracks are currently supported
return Napi::Array::New(info.Env(), 0);
}
Napi::Value MediaStream::ApplyConstraints(const Napi::CallbackInfo& info)
{
auto env = info.Env();
auto constraints = info[0].As<Napi::Object>();
auto deferred{Napi::Promise::Deferred::New(env)};
auto promise{deferred.Promise()};
// Apply the constraints to the existing device
if (!UpdateConstraints(constraints))
{
// Setting the constraint to the capability failed
deferred.Reject(Napi::Error::New(env, "OverconstrainedError: Unable to match constraints to a supported camera configuration.").Value());
return static_cast<Napi::Value>(promise);
}
deferred.Resolve(env.Undefined());
return static_cast<Napi::Value>(promise);
}
arcana::task<void, std::exception_ptr> MediaStream::ApplyInitialConstraintsAsync(Napi::Object constraints)
{
// A camera device hasn't been selected yet. Find the best device and open the stream
auto bestCamera = FindBestCameraStream(constraints);
// If m_cameraDevice is still null that means a camera device could not be found that meets the constraints
if (!bestCamera.has_value())
{
// If no device could be fount to satisfy the constraints throw a "ConstraintError" to match the browser implementation
throw std::runtime_error{"ConstraintError: Unable to match constraints to a supported camera configuration."};
}
// We need to create a shared_ptr to the CameraDevice because internally it calls shared_from_this
m_cameraDevice = std::make_shared<Plugins::CameraDevice>(std::move(bestCamera->first));
// Create a persistent ref to the constraints object so it isn't destructed during our async work
auto constraintsRef{Napi::Persistent(constraints)};
return m_cameraDevice->OpenAsync(bestCamera.value().second).then(m_runtimeScheduler.Get(), arcana::cancellation::none(), [this, constraintsRef{std::move(constraintsRef)}](CameraDevice::CameraDimensions cameraDimensions) {
this->Width = cameraDimensions.width;
this->Height = cameraDimensions.height;
if (!UpdateConstraints(constraintsRef.Value()))
{
// Setting the constraint to the capability failed
throw std::runtime_error{"ConstraintError: Unable to match constraints to a supported camera configuration."};
}
});
}
Napi::Value MediaStream::GetCapabilities(const Napi::CallbackInfo& info)
{
auto env = info.Env();
if (m_cameraDevice == nullptr)
{
// We don't have a cameraDevice selected yet.
return Napi::Object::New(env);
}
auto capabilities = Napi::Object::New(env);
for (const auto& capability : m_cameraDevice->Capabilities())
{
capability->AddAsCapability(capabilities);
}
return std::move(capabilities);
}
Napi::Value MediaStream::GetSettings(const Napi::CallbackInfo& info)
{
auto env = info.Env();
if (m_cameraDevice == nullptr)
{
// We don't have a cameraDevice selected yet.
return Napi::Object::New(env);
}
auto settings = Napi::Object::New(env);
for (const auto& capability : m_cameraDevice->Capabilities())
{
capability->AddAsSetting(settings);
}
return std::move(settings);
}
Napi::Value MediaStream::GetConstraints(const Napi::CallbackInfo& info)
{
auto env = info.Env();
// return a clone of the currently applied constraints
return Napi::Object::From(env, m_currentConstraints.Value());
}
std::optional<std::pair<Plugins::CameraDevice, const CameraTrack&>> MediaStream::FindBestCameraStream(Napi::Object constraints)
{
// Get the available camera devices
std::vector<Plugins::CameraDevice> cameraDevices{CameraDevice::GetCameraDevices(Env())};
std::optional<std::pair<Plugins::CameraDevice, const CameraTrack&>> bestCameraConfiguration{};
int32_t bestFullySatisfiedCapabilityCount{0};
// The camera devices should be assumed to be sorted from best to worst. Pick the first camera device that fully
// satisfies the most constraints without failing any.
for (auto& cameraDevice : cameraDevices)
{
bool failedAConstraint{false};
int32_t fullySatisfiedCapabilityCount{0};
for (const auto& capability : cameraDevice.Capabilities())
{
Capability::MeetsConstraint constraintSatifaction{capability->MeetsConstraints(constraints)};
switch (constraintSatifaction)
{
case Capability::MeetsConstraint::FullySatisfied:
fullySatisfiedCapabilityCount++;
break;
case Capability::MeetsConstraint::PartiallySatisfied:
case Capability::MeetsConstraint::Unconstrained:
// Don't weight partialy satisfied or unconstrained capabilites any higher than another device
break;
case Capability::MeetsConstraint::Unsatisfied:
default:
failedAConstraint = true;
break;
}
// Don't bother continuing to count capabilities if we've failed on
if (failedAConstraint)
{
break;
}
}
if (failedAConstraint)
{
// The device fails at least one of the constraint requirements. Skip it.
continue;
}
// Ensure the width/height constraints can be met and find the best resolution available within
// the constraints
const CameraTrack* bestResolution{nullptr};
int32_t bestWidthDiff{INT32_MAX};
int32_t bestHeightDiff{INT32_MAX};
auto widthConstraint{Constraint::ParseConstraint<int32_t>(constraints.Get("width"))};
auto heightConstraint{Constraint::ParseConstraint<int32_t>(constraints.Get("height"))};
// Set the targetWidth and targetHeight as a fallback through the values exact, ideal, max, min
auto targetWidth = widthConstraint.exact.has_value() ? widthConstraint.exact
: widthConstraint.ideal.has_value() ? widthConstraint.ideal
: widthConstraint.max.has_value() ? widthConstraint.max
: widthConstraint.min;
auto targetHeight = heightConstraint.exact.has_value() ? heightConstraint.exact
: heightConstraint.ideal.has_value() ? heightConstraint.ideal
: heightConstraint.max.has_value() ? heightConstraint.max
: heightConstraint.min;
for (uint32_t j = 0; j < cameraDevice.SupportedResolutions().size(); j++)
{
auto& resolution = cameraDevice.SupportedResolutions()[j];
auto meetsWidthRequirements =
(!widthConstraint.exact.has_value() || widthConstraint.exact.value() == resolution.Width()) &&
(!widthConstraint.min.has_value() || widthConstraint.min.value() <= resolution.Width()) &&
(!widthConstraint.max.has_value() || widthConstraint.max.value() >= resolution.Width());
auto meetsHeightRequirements =
(!heightConstraint.exact.has_value() || heightConstraint.exact.value() == resolution.Height()) &&
(!heightConstraint.min.has_value() || heightConstraint.min.value() <= resolution.Height()) &&
(!heightConstraint.max.has_value() || heightConstraint.max.value() >= resolution.Height());
if (!meetsWidthRequirements || !meetsHeightRequirements)
{
// The resolution doesn't meet the constraint requirements
continue;
}
int32_t widthDiff = targetWidth.has_value() ? abs(static_cast<int32_t>(targetWidth.value() - resolution.Width())) : 0;
int32_t heightDiff = targetHeight.has_value() ? abs(static_cast<int32_t>(targetHeight.value() - resolution.Height())) : 0;
if (bestResolution == nullptr || widthDiff + heightDiff < bestWidthDiff + bestHeightDiff)
{
bestWidthDiff = widthDiff;
bestHeightDiff = heightDiff;
bestResolution = &resolution;
// Check if we got an exact match exit the loop as no other resolution would be better
if (widthDiff + heightDiff == 0)
{
break;
}
}
}
if (bestResolution == nullptr)
{
// This device doesn't meet the width/height constraints
continue;
}
// Count a fully satisfied width or height constraint towards the overal device satisfaction
fullySatisfiedCapabilityCount += bestWidthDiff == 0 ? 1 : 0;
fullySatisfiedCapabilityCount += bestHeightDiff == 0 ? 1 : 0;
// At this point we have a device that fully satisfies all given constraints, we'll have to search
// all devices to find the one that meets the most constraints
if (!bestCameraConfiguration.has_value() || fullySatisfiedCapabilityCount > bestFullySatisfiedCapabilityCount)
{
bestCameraConfiguration.emplace(std::move(cameraDevice), *bestResolution);
bestFullySatisfiedCapabilityCount = fullySatisfiedCapabilityCount;
}
}
return bestCameraConfiguration;
}
bool MediaStream::UpdateConstraints(Napi::Object constraints)
{
bool allConstraintsSatisfied = true;
m_currentConstraints = Napi::Persistent(Napi::Object::New(Env()));
if (m_cameraDevice == nullptr)
{
// We don't have a cameraDevice selected yet.
return false;
}
for (auto& capability : m_cameraDevice->Capabilities())
{
Capability::MeetsConstraint constraintSatisfaction{capability->MeetsConstraints(constraints)};
switch (constraintSatisfaction)
{
case Capability::MeetsConstraint::FullySatisfied:
case Capability::MeetsConstraint::PartiallySatisfied:
m_currentConstraints.Set(capability->GetName(), constraints.Get(capability->GetName()));
break;
case Capability::MeetsConstraint::Unconstrained:
// Still apply the unconstrained capability so that it resets to it's default in case it was previously set
break;
case Capability::MeetsConstraint::Unsatisfied:
default:
// The constraint couldn't be satisfied ignore it and continue applying the remaining constraints
allConstraintsSatisfied = false;
continue;
;
}
if (!capability->ApplyConstraints(constraints))
{
// Setting the constraint to the capability failed
allConstraintsSatisfied = false;
}
}
return allConstraintsSatisfied;
}
void MediaStream::Stop(const Napi::CallbackInfo& /*info*/)
{
// Clear out the cameraDevice which will disconnect the camera stream
m_cameraDevice = nullptr;
}
bool MediaStream::UpdateTexture(bgfx::TextureHandle textureHandle)
{
bool dimensionsChanged = false;
if (m_cameraDevice == nullptr)
{
// We don't have a cameraDevice selected yet.
return dimensionsChanged;
}
auto cameraDimensions{m_cameraDevice->UpdateCameraTexture(textureHandle)};
if (this->Width != cameraDimensions.width || this->Height != cameraDimensions.height)
{
dimensionsChanged = true;
this->Width = cameraDimensions.width;
this->Height = cameraDimensions.height;
}
return dimensionsChanged;
}
}