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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "RemoteMediaDataEncoderChild.h"
#include "RemoteDecodeUtils.h"
#include "RemoteMediaManagerChild.h"
#include "mozilla/dom/WebCodecsUtils.h"
namespace mozilla {
extern LazyLogModule sPEMLog;
#define AUTO_MARKER(var, postfix) \
AutoWebCodecsMarker var("RemoteMediaDataEncoderChild", postfix);
#define LOGE(fmt, ...) \
MOZ_LOG_FMT(sPEMLog, mozilla::LogLevel::Error, \
"[RemoteMediaDataEncoderChild] {}: " fmt, __func__, __VA_ARGS__)
#define LOGW(fmt, ...) \
MOZ_LOG_FMT(sPEMLog, mozilla::LogLevel::Warning, \
"[RemoteMediaDataEncoderChild] {}: " fmt, __func__, __VA_ARGS__)
#define LOGD(fmt, ...) \
MOZ_LOG_FMT(sPEMLog, mozilla::LogLevel::Debug, \
"[RemoteMediaDataEncoderChild] {}: " fmt, __func__, __VA_ARGS__)
#define LOGV(fmt, ...) \
MOZ_LOG_FMT(sPEMLog, mozilla::LogLevel::Verbose, \
"[RemoteMediaDataEncoderChild] {}: " fmt, __func__, __VA_ARGS__)
RemoteMediaDataEncoderChild::RemoteMediaDataEncoderChild(
nsCOMPtr<nsISerialEventTarget>&& aThread, RemoteMediaIn aLocation)
: ShmemRecycleAllocator(this),
mThread(std::move(aThread)),
mLocation(aLocation) {
LOGV("[{}]", fmt::ptr(this));
}
RemoteMediaDataEncoderChild::~RemoteMediaDataEncoderChild() {
LOGV("[{}]", fmt::ptr(this));
}
void RemoteMediaDataEncoderChild::MaybeDestroyActor() {
// If this is the last reference, and we still have an actor, then we know
// that the last reference is solely due to the IPDL reference. Dispatch to
// the owning thread to delete that so that we can clean up.
MutexAutoLock lock(mMutex);
if (mNeedsShutdown) {
mNeedsShutdown = false;
mThread->Dispatch(NS_NewRunnableFunction(__func__, [self = RefPtr{this}]() {
if (self->CanSend()) {
LOGD("[{}] destroying final self reference", fmt::ptr(self.get()));
self->Send__delete__(self);
}
}));
}
}
void RemoteMediaDataEncoderChild::ActorDestroy(ActorDestroyReason aWhy) {
LOGD("[{}]", fmt::ptr(this));
{
MutexAutoLock lock(mMutex);
mNeedsShutdown = false;
}
mRemoteCrashed = aWhy == ActorDestroyReason::AbnormalShutdown;
CleanupShmemRecycleAllocator();
}
RefPtr<PlatformEncoderModule::CreateEncoderPromise>
RemoteMediaDataEncoderChild::Construct() {
{
MutexAutoLock lock(mMutex);
mNeedsShutdown = CanSend();
}
LOGD("[{}] send", fmt::ptr(this));
SendConstruct()->Then(
mThread, __func__,
[self = RefPtr{this}](MediaResult aResult) {
LOGD("[{}] Construct resolved code={}", fmt::ptr(self.get()),
aResult.Description());
self->mHasConstructed = true;
self->mConstructPromise.Resolve(self, __func__);
if (!self->mInitPromise.IsEmpty()) {
self->DoSendInit();
}
},
[self = RefPtr{this}](const mozilla::ipc::ResponseRejectReason& aReason) {
LOGE("[{}] Construct ipc failed", fmt::ptr(self.get()));
RemoteMediaManagerChild::HandleRejectionError(
self->GetManager(), self->mLocation, aReason,
[self](const MediaResult& aError) {
self->mConstructPromise.RejectIfExists(aError, __func__);
self->mInitPromise.RejectIfExists(aError, __func__);
});
});
return mConstructPromise.Ensure(__func__);
}
void RemoteMediaDataEncoderChild::DoSendInit() {
MOZ_ASSERT(mHasConstructed);
LOGD("[{}] Init send", fmt::ptr(this));
SendInit()->Then(
mThread, __func__,
[self = RefPtr{this}](EncodeInitResultIPDL&& aResponse) {
if (aResponse.type() == EncodeInitResultIPDL::TMediaResult) {
LOGE("[{}] Init resolved code={}", fmt::ptr(self.get()),
aResponse.get_MediaResult().Description());
self->mInitPromise.Reject(aResponse.get_MediaResult(), __func__);
return;
}
const auto& initResponse = aResponse.get_EncodeInitCompletionIPDL();
LOGD("[{}] Init resolved hwAccel={} desc=\"{}\"", fmt::ptr(self.get()),
initResponse.hardware(), initResponse.description().get());
MutexAutoLock lock(self->mMutex);
self->mDescription = initResponse.description();
self->mDescription.AppendFmt(
" ({})", RemoteMediaInToStr(self->GetManager()->Location()));
self->mIsHardwareAccelerated = initResponse.hardware();
self->mHardwareAcceleratedReason = initResponse.hardwareReason();
self->mInitPromise.ResolveIfExists(true, __func__);
},
[self = RefPtr{this}](const mozilla::ipc::ResponseRejectReason& aReason) {
LOGE("[{}] Init ipc failed", fmt::ptr(self.get()));
RemoteMediaManagerChild::HandleRejectionError(
self->GetManager(), self->mLocation, aReason,
[self](const MediaResult& aError) {
self->mInitPromise.RejectIfExists(aError, __func__);
});
});
}
RefPtr<MediaDataEncoder::InitPromise> RemoteMediaDataEncoderChild::Init() {
return InvokeAsync(
mThread, __func__,
[self = RefPtr{this}]() -> RefPtr<MediaDataEncoder::InitPromise> {
// If the owner called Init before the Construct response, then just
// create promise and wait for that first. This can happen if the owner
// created the encoder via RemoteEncoderModule's CreateAudioEncoder or
// CreateVideoEncoder instead of AsyncCreateEncoder.
//
// mConstructPromise might not have been created yet either because we
// may have delayed dispatching related to the process launching.
// mHasConstructed will be set when the construct IPDL call returns.
if (self->mHasConstructed) {
self->DoSendInit();
} else {
LOGD("[{}] Init deferred, still constructing", fmt::ptr(self.get()));
}
return self->mInitPromise.Ensure(__func__);
});
}
RefPtr<PRemoteEncoderChild::EncodePromise>
RemoteMediaDataEncoderChild::DoSendEncode(
const nsTArray<RefPtr<MediaData>>& aSamples, ShmemRecycleTicket* aTicket) {
if (mRemoteCrashed) {
LOGE("[{}] remote crashed", fmt::ptr(this));
nsresult err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_UTILITY_ERR;
if (mLocation == RemoteMediaIn::GpuProcess ||
mLocation == RemoteMediaIn::RddProcess) {
err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_RDD_OR_GPU_ERR;
} else if (mLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_MF_CDM_ERR;
}
return PRemoteEncoderChild::EncodePromise::CreateAndResolve(
MediaResult(err, "Remote process crashed"), __func__);
}
if (aSamples.IsEmpty()) {
LOGE("[{}] no samples to encode", fmt::ptr(this));
return PRemoteEncoderChild::EncodePromise::CreateAndResolve(
MediaResult(NS_ERROR_INVALID_ARG), __func__);
}
MediaData::Type type = aSamples[0]->mType;
if (type == MediaData::Type::AUDIO_DATA) {
nsTArray<RefPtr<AudioData>> audioSamples;
for (auto& sample : aSamples) {
audioSamples.AppendElement(sample->As<AudioData>());
}
auto samples = MakeRefPtr<ArrayOfRemoteAudioData>();
if (!samples->Fill(audioSamples, [&](size_t aSize) {
return AllocateBuffer(aSize, aTicket);
})) {
LOGE("[{}] buffer audio failed", fmt::ptr(this));
return PRemoteEncoderChild::EncodePromise::CreateAndResolve(
MediaResult(NS_ERROR_OUT_OF_MEMORY), __func__);
}
LOGD("[{}] send {} audio samples", fmt::ptr(this), audioSamples.Length());
return SendEncode(std::move(samples));
}
if (type == MediaData::Type::VIDEO_DATA) {
nsTArray<RefPtr<VideoData>> videoSamples;
for (auto& sample : aSamples) {
videoSamples.AppendElement(sample->As<VideoData>());
}
auto samples = MakeRefPtr<ArrayOfRemoteVideoData>();
for (const auto& videoSample : videoSamples) {
if (layers::Image* videoImage = videoSample->mImage) {
// We don't need to supply a working deallocator because the ticket is
// responsible for that cleanup.
layers::SurfaceDescriptor sd;
nsresult rv = videoImage->BuildSurfaceDescriptorGPUVideoOrBuffer(
sd, layers::Image::BuildSdbFlags::Default,
Some(GetVideoBridgeSourceFromRemoteMediaIn(mLocation)),
[&](uint32_t aBufferSize) {
ShmemBuffer buffer = AllocateBuffer(aBufferSize, aTicket);
if (buffer.Valid()) {
return layers::MemoryOrShmem(std::move(buffer.Get()));
}
return layers::MemoryOrShmem();
},
[&](layers::MemoryOrShmem&&) {});
if (NS_WARN_IF(NS_FAILED(rv))) {
LOGE("[{}] buffer video failed, code={}", fmt::ptr(this),
fmt::enums::format_as(rv));
return PRemoteEncoderChild::EncodePromise::CreateAndResolve(
MediaResult(rv), __func__);
}
samples->Append(RemoteVideoData(
MediaDataIPDL(videoSample->mOffset, videoSample->mTime,
videoSample->mTimecode, videoSample->mDuration,
videoSample->mKeyframe),
videoSample->mDisplay, RemoteImageHolder(std::move(sd)),
videoSample->mFrameID));
}
}
LOGD("[{}] send {} video samples", fmt::ptr(this), videoSamples.Length());
return SendEncode(std::move(samples));
}
return PRemoteEncoderChild::EncodePromise::CreateAndResolve(
MediaResult(NS_ERROR_INVALID_ARG), __func__);
}
RefPtr<MediaDataEncoder::EncodePromise> RemoteMediaDataEncoderChild::Encode(
const MediaData* aSample) {
return Encode(nsTArray<RefPtr<MediaData>>{const_cast<MediaData*>(aSample)});
}
RefPtr<MediaDataEncoder::EncodePromise> RemoteMediaDataEncoderChild::Encode(
nsTArray<RefPtr<MediaData>>&& aSamples) {
return InvokeAsync(
mThread, __func__,
[self = RefPtr{this}, samples = std::move(aSamples)]()
-> RefPtr<MediaDataEncoder::EncodePromise> {
auto promise =
MakeRefPtr<MediaDataEncoder::EncodePromise::Private>(__func__);
auto ticket = MakeRefPtr<ShmemRecycleTicket>();
self->DoSendEncode(samples, ticket)
->Then(
self->mThread, __func__,
[self, promise, ticket](EncodeResultIPDL&& aResponse) {
self->ReleaseTicket(ticket);
if (aResponse.type() == EncodeResultIPDL::TMediaResult) {
LOGD("[{}] Encode resolved, code={}", fmt::ptr(self.get()),
aResponse.get_MediaResult().Description());
promise->Reject(aResponse.get_MediaResult(), __func__);
return;
}
const auto& encodeResponse =
aResponse.get_EncodeCompletionIPDL();
nsTArray<RefPtr<MediaRawData>> samples;
if (auto remoteSamples = encodeResponse.samples()) {
size_t count = remoteSamples->Count();
samples.SetCapacity(count);
for (size_t i = 0; i < count; ++i) {
AUTO_MARKER(marker, ".Encode.ElementAt");
if (RefPtr<MediaRawData> sample =
remoteSamples->ElementAt(i)) {
marker.End();
samples.AppendElement(std::move(sample));
} else {
LOGE(
"[{}] Encode resolved, failed to buffer "
"samples",
fmt::ptr(self.get()));
promise->Reject(MediaResult(NS_ERROR_OUT_OF_MEMORY),
__func__);
return;
}
}
}
LOGV("[{}] Encode resolved, {} samples", fmt::ptr(self.get()),
samples.Length());
promise->Resolve(std::move(samples), __func__);
self->SendReleaseTicket(encodeResponse.ticketId());
},
[self, promise,
ticket](const mozilla::ipc::ResponseRejectReason& aReason) {
LOGE("[{}] Encode ipc failed", fmt::ptr(self.get()));
self->ReleaseTicket(ticket);
RemoteMediaManagerChild::HandleRejectionError(
self->GetManager(), self->mLocation, aReason,
[promise](const MediaResult& aError) {
promise->Reject(aError, __func__);
});
});
return promise;
});
}
RefPtr<MediaDataEncoder::EncodePromise> RemoteMediaDataEncoderChild::Drain() {
return InvokeAsync(
mThread, __func__,
[self = RefPtr{this}]() -> RefPtr<MediaDataEncoder::EncodePromise> {
LOGD("[{}] Drain send", fmt::ptr(self.get()));
self->SendDrain()->Then(
self->mThread, __func__,
[self](EncodeResultIPDL&& aResponse) {
if (aResponse.type() == EncodeResultIPDL::TMediaResult) {
LOGE("[{}] Drain resolved, code={}", fmt::ptr(self.get()),
aResponse.get_MediaResult().Description());
self->mDrainPromise.Reject(aResponse.get_MediaResult(),
__func__);
return;
}
const auto& encodeResponse = aResponse.get_EncodeCompletionIPDL();
nsTArray<RefPtr<MediaRawData>> samples;
if (auto remoteSamples = encodeResponse.samples()) {
size_t count = remoteSamples->Count();
samples.SetCapacity(count);
for (size_t i = 0; i < count; ++i) {
if (RefPtr<MediaRawData> sample =
remoteSamples->ElementAt(i)) {
samples.AppendElement(std::move(sample));
} else {
LOGE("[{}] Drain resolved, failed to buffer samples",
fmt::ptr(self.get()));
self->mDrainPromise.Reject(
MediaResult(NS_ERROR_OUT_OF_MEMORY), __func__);
return;
}
}
}
LOGD("[{}] Drain resolved, {} samples", fmt::ptr(self.get()),
samples.Length());
self->mDrainPromise.Resolve(std::move(samples), __func__);
self->SendReleaseTicket(encodeResponse.ticketId());
},
[self](const mozilla::ipc::ResponseRejectReason& aReason) {
LOGE("[{}] Drain ipc failed", fmt::ptr(self.get()));
RemoteMediaManagerChild::HandleRejectionError(
self->GetManager(), self->mLocation, aReason,
[self](const MediaResult& aError) {
self->mDrainPromise.RejectIfExists(aError, __func__);
});
});
return self->mDrainPromise.Ensure(__func__);
});
}
RefPtr<MediaDataEncoder::ReconfigurationPromise>
RemoteMediaDataEncoderChild::Reconfigure(
const RefPtr<const EncoderConfigurationChangeList>& aConfigurationChanges) {
return InvokeAsync(
mThread, __func__,
[self = RefPtr{this}, changes = RefPtr{aConfigurationChanges}]()
-> RefPtr<MediaDataEncoder::ReconfigurationPromise> {
LOGD("[{}] Reconfigure send", fmt::ptr(self.get()));
self->SendReconfigure(
const_cast<EncoderConfigurationChangeList*>(changes.get()))
->Then(
self->mThread, __func__,
[self](const MediaResult& aResult) {
if (NS_SUCCEEDED(aResult)) {
LOGD("[{}] Reconfigure resolved", fmt::ptr(self.get()));
self->mReconfigurePromise.ResolveIfExists(true, __func__);
} else {
LOGD("[{}] Reconfigure resolved, code={}",
fmt::ptr(self.get()), aResult.Description());
self->mReconfigurePromise.RejectIfExists(aResult, __func__);
}
},
[self](const mozilla::ipc::ResponseRejectReason& aReason) {
LOGE("[{}] Reconfigure ipc failed", fmt::ptr(self.get()));
RemoteMediaManagerChild::HandleRejectionError(
self->GetManager(), self->mLocation, aReason,
[self](const MediaResult& aError) {
self->mReconfigurePromise.RejectIfExists(aError,
__func__);
});
});
return self->mReconfigurePromise.Ensure(__func__);
});
}
RefPtr<mozilla::ShutdownPromise> RemoteMediaDataEncoderChild::Shutdown() {
{
MutexAutoLock lock(mMutex);
mNeedsShutdown = false;
}
return InvokeAsync(
mThread, __func__,
[self = RefPtr{this}]() -> RefPtr<mozilla::ShutdownPromise> {
LOGD("[{}] Shutdown send", fmt::ptr(self.get()));
self->SendShutdown()->Then(
self->mThread, __func__,
[self](PRemoteEncoderChild::ShutdownPromise::ResolveOrRejectValue&&
aValue) {
LOGD("[{}] Shutdown resolved", fmt::ptr(self.get()));
if (self->CanSend()) {
self->Send__delete__(self);
}
self->mShutdownPromise.Resolve(aValue.IsResolve(), __func__);
});
return self->mShutdownPromise.Ensure(__func__);
});
}
RefPtr<GenericPromise> RemoteMediaDataEncoderChild::SetBitrate(
uint32_t aBitsPerSec) {
return InvokeAsync(
mThread, __func__,
[self = RefPtr{this}, aBitsPerSec]() -> RefPtr<GenericPromise> {
auto promise = MakeRefPtr<GenericPromise::Private>(__func__);
self->SendSetBitrate(aBitsPerSec)
->Then(
self->mThread, __func__,
[promise](const nsresult& aRv) {
if (NS_SUCCEEDED(aRv)) {
promise->Resolve(true, __func__);
} else {
promise->Reject(aRv, __func__);
}
},
[self,
promise](const mozilla::ipc::ResponseRejectReason& aReason) {
LOGE("[{}] SetBitrate ipc failed", fmt::ptr(self.get()));
RemoteMediaManagerChild::HandleRejectionError(
self->GetManager(), self->mLocation, aReason,
[promise](const MediaResult& aError) {
promise->Reject(aError.Code(), __func__);
});
});
return promise.forget();
});
}
RemoteMediaManagerChild* RemoteMediaDataEncoderChild::GetManager() {
if (!CanSend()) {
return nullptr;
}
return static_cast<RemoteMediaManagerChild*>(Manager());
}
bool RemoteMediaDataEncoderChild::IsHardwareAccelerated(
nsACString& aFailureReason) const {
MutexAutoLock lock(mMutex);
aFailureReason = mHardwareAcceleratedReason;
return mIsHardwareAccelerated;
}
nsCString RemoteMediaDataEncoderChild::GetDescriptionName() const {
MutexAutoLock lock(mMutex);
return mDescription;
}
#undef AUTO_MARKER
} // namespace mozilla
|