DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et ft=cpp : */
/* 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,
 * 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 "CamerasChild.h"

#undef FF
#undef FF

#include "mozilla/Assertions.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/Logging.h"
#include "mozilla/Logging.h"
#include "mozilla/SyncRunnable.h"
#include "mozilla/WeakPtr.h"
#include "mozilla/Unused.h"
#include "MediaUtils.h"
#include "nsThreadUtils.h"
#include "nsThreadUtils.h"

#undef LOG
#undef LOG_ENABLED
mozilla::LazyLogModule gCamerasChildLog("CamerasChild");
#define LOG(args) MOZ_LOG(gCamerasChildLog, mozilla::LogLevel::Debug, args)
#define LOG_ENABLED() MOZ_LOG_TEST(gCamerasChildLog, mozilla::LogLevel::Debug)


namespace mozilla {
namespace camera {

CamerasSingleton::CamerasSingleton()
    : mCamerasMutex("CamerasSingleton::mCamerasMutex"),
      mCameras(nullptr),
      mCamerasChildThread(nullptr),
      mCamerasChildThread(nullptr),
      mInShutdown(false) {
  LOG(("CamerasSingleton: %p", this));
}

CamerasSingleton::~CamerasSingleton() { LOG(("~CamerasSingleton: %p", this)); }
CamerasSingleton::~CamerasSingleton() { LOG(("~CamerasSingleton: %p", this)); }

class InitializeIPCThread : public Runnable {
 public:
  InitializeIPCThread()
      : Runnable("camera::InitializeIPCThread"), mCamerasChild(nullptr) {}
      : Runnable("camera::InitializeIPCThread"), mCamerasChild(nullptr) {}

  NS_IMETHOD Run() override {
    // Try to get the PBackground handle
    ipc::PBackgroundChild* existingBackgroundChild =
        ipc::BackgroundChild::GetForCurrentThread();
        ipc::BackgroundChild::GetForCurrentThread();
    // If it's not spun up yet, block until it is, and retry
    if (!existingBackgroundChild) {
      LOG(("No existingBackgroundChild"));
      existingBackgroundChild =
      existingBackgroundChild =
          ipc::BackgroundChild::GetOrCreateForCurrentThread();
      LOG(("BackgroundChild: %p", existingBackgroundChild));
      if (!existingBackgroundChild) {
        return NS_ERROR_FAILURE;
      }
      }
    }

    // Create CamerasChild
    // We will be returning the resulting pointer (synchronously) to our caller.
    mCamerasChild = static_cast<mozilla::camera::CamerasChild*>(
    mCamerasChild = static_cast<mozilla::camera::CamerasChild*>(
        existingBackgroundChild->SendPCamerasConstructor());


    return NS_OK;
  }

  CamerasChild* GetCamerasChild() { return mCamerasChild; }


 private:
  CamerasChild* mCamerasChild;
};

CamerasChild* GetCamerasChild() {
CamerasChild* GetCamerasChild() {
  CamerasSingleton::Mutex().AssertCurrentThreadOwns();
  if (!CamerasSingleton::Child()) {
    MOZ_ASSERT(!NS_IsMainThread(), "Should not be on the main Thread");
    MOZ_ASSERT(!CamerasSingleton::Thread());
    LOG(("No sCameras, setting up IPC Thread"));
    LOG(("No sCameras, setting up IPC Thread"));
    nsresult rv = NS_NewNamedThread("Cameras IPC",
                                    getter_AddRefs(CamerasSingleton::Thread()));
    if (NS_FAILED(rv)) {
      LOG(("Error launching IPC Thread"));
      return nullptr;
    }


    // At this point we are in the MediaManager thread, and the thread we are
    // dispatching to is the specific Cameras IPC thread that was just made
    // above, so now we will fire off a runnable to run
    // BackgroundChild::GetOrCreateForCurrentThread there, while we
    // block in this thread.
    // block in this thread.
    // We block until the following happens in the Cameras IPC thread:
    // 1) Creation of PBackground finishes
    // 2) Creation of PCameras finishes by sending a message to the parent
    RefPtr<InitializeIPCThread> runnable = new InitializeIPCThread();
    RefPtr<SyncRunnable> sr = new SyncRunnable(runnable);
    RefPtr<SyncRunnable> sr = new SyncRunnable(runnable);
    sr->DispatchToThread(CamerasSingleton::Thread());
    CamerasSingleton::Child() = runnable->GetCamerasChild();
  }
  if (!CamerasSingleton::Child()) {
    LOG(("Failed to set up CamerasChild, are we in shutdown?"));
    LOG(("Failed to set up CamerasChild, are we in shutdown?"));
  }
  return CamerasSingleton::Child();
}

CamerasChild* GetCamerasChildIfExists() {
CamerasChild* GetCamerasChildIfExists() {
  OffTheBooksMutexAutoLock lock(CamerasSingleton::Mutex());
  return CamerasSingleton::Child();
}


mozilla::ipc::IPCResult CamerasChild::RecvReplyFailure(void) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReplySuccess = false;
  mReplySuccess = false;
  monitor.Notify();
  return IPC_OK();
}

mozilla::ipc::IPCResult CamerasChild::RecvReplySuccess(void) {
mozilla::ipc::IPCResult CamerasChild::RecvReplySuccess(void) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReplySuccess = true;
  monitor.Notify();
  monitor.Notify();
  return IPC_OK();
}

mozilla::ipc::IPCResult CamerasChild::RecvReplyNumberOfCapabilities(
    const int& numdev) {
    const int& numdev) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReplySuccess = true;
  mReplyInteger = numdev;
  mReplyInteger = numdev;
  monitor.Notify();
  return IPC_OK();
}

// Helper function to dispatch calls to the IPC Thread and
// CamerasChild object. Takes the needed locks and dispatches.
// Takes a "failed" value and a reference to the output variable
// as parameters, will return the right one depending on whether
// dispatching succeeded.
// dispatching succeeded.
template <class T = int>
class LockAndDispatch {
 public:
  LockAndDispatch(CamerasChild* aCamerasChild, const char* aRequestingFunc,
                  nsIRunnable* aRunnable, const T& aFailureValue,
                  nsIRunnable* aRunnable, const T& aFailureValue,
                  const T& aSuccessValue)
      : mCamerasChild(aCamerasChild),
        mRequestingFunc(aRequestingFunc),
        mRunnable(aRunnable),
        mReplyLock(aCamerasChild->mReplyMonitor),
        mReplyLock(aCamerasChild->mReplyMonitor),
        mRequestLock(aCamerasChild->mRequestMutex),
        mSuccess(true),
        mFailureValue(aFailureValue),
        mSuccessValue(aSuccessValue) {
    Dispatch();
    Dispatch();
  }

  T ReturnValue() const {
    if (mSuccess) {
      return mSuccessValue;
      return mSuccessValue;
    } else {
      return mFailureValue;
    }
  }

  const bool& Success() const { return mSuccess; }


 private:
  void Dispatch() {
    if (!mCamerasChild->DispatchToParent(mRunnable, mReplyLock)) {
      LOG(("Cameras dispatch for IPC failed in %s", mRequestingFunc));
      mSuccess = false;
      mSuccess = false;
    }
  }
  }

  CamerasChild* mCamerasChild;
  const char* mRequestingFunc;
  nsIRunnable* mRunnable;
  // Prevent concurrent use of the reply variables by holding
  // Prevent concurrent use of the reply variables by holding
  // the mReplyMonitor. Note that this is unlocked while waiting for
  // the reply to be filled in, necessitating the additional mRequestLock/Mutex;
  MonitorAutoLock mReplyLock;
  MutexAutoLock mRequestLock;
  bool mSuccess;
  bool mSuccess;
  const T mFailureValue;
  const T& mSuccessValue;
};

bool CamerasChild::DispatchToParent(nsIRunnable* aRunnable,
bool CamerasChild::DispatchToParent(nsIRunnable* aRunnable,
                                    MonitorAutoLock& aMonitor) {
  CamerasSingleton::Mutex().AssertCurrentThreadOwns();
  CamerasSingleton::Thread()->Dispatch(aRunnable, NS_DISPATCH_NORMAL);
  // We can't see if the send worked, so we need to be able to bail
  // out on shutdown (when it failed and we won't get a reply).
  // out on shutdown (when it failed and we won't get a reply).
  if (!mIPCIsAlive) {
    return false;
  }
  // Guard against spurious wakeups.
  mReceivedReply = false;
  mReceivedReply = false;
  // Wait for a reply
  do {
    aMonitor.Wait();
  } while (!mReceivedReply && mIPCIsAlive);
  if (!mReplySuccess) {
  if (!mReplySuccess) {
    return false;
  }
  return true;
}

int CamerasChild::NumberOfCapabilities(CaptureEngine aCapEngine,
                                       const char* deviceUniqueIdUTF8) {
  LOG(("%s", __PRETTY_FUNCTION__));
  LOG(("NumberOfCapabilities for %s", deviceUniqueIdUTF8));
  nsCString unique_id(deviceUniqueIdUTF8);
  nsCString unique_id(deviceUniqueIdUTF8);
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, nsCString>(
          "camera::PCamerasChild::SendNumberOfCapabilities", this,
          &CamerasChild::SendNumberOfCapabilities, aCapEngine, unique_id);
  LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
  LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
  LOG(("Capture capability count: %d", dispatcher.ReturnValue()));
  return dispatcher.ReturnValue();
}

int CamerasChild::NumberOfCaptureDevices(CaptureEngine aCapEngine) {
int CamerasChild::NumberOfCaptureDevices(CaptureEngine aCapEngine) {
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCOMPtr<nsIRunnable> runnable = mozilla::NewRunnableMethod<CaptureEngine>(
      "camera::PCamerasChild::SendNumberOfCaptureDevices", this,
      &CamerasChild::SendNumberOfCaptureDevices, aCapEngine);
  LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
  LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
  LOG(("Capture Devices: %d", dispatcher.ReturnValue()));
  return dispatcher.ReturnValue();
}


mozilla::ipc::IPCResult CamerasChild::RecvReplyNumberOfCaptureDevices(
    const int& numdev) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReceivedReply = true;
  mReplySuccess = true;
  mReplyInteger = numdev;
  monitor.Notify();
  return IPC_OK();
}
}

int CamerasChild::EnsureInitialized(CaptureEngine aCapEngine) {
  LOG(("%s", __PRETTY_FUNCTION__));
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCOMPtr<nsIRunnable> runnable = mozilla::NewRunnableMethod<CaptureEngine>(
      "camera::PCamerasChild::SendEnsureInitialized", this,
      &CamerasChild::SendEnsureInitialized, aCapEngine);
  LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
  LOG(("Capture Devices: %d", dispatcher.ReturnValue()));
  LOG(("Capture Devices: %d", dispatcher.ReturnValue()));
  return dispatcher.ReturnValue();
}

int CamerasChild::GetCaptureCapability(
    CaptureEngine aCapEngine, const char* unique_idUTF8,
    CaptureEngine aCapEngine, const char* unique_idUTF8,
    const unsigned int capability_number,
    webrtc::VideoCaptureCapability& capability) {
  LOG(("GetCaptureCapability: %s %d", unique_idUTF8, capability_number));
  nsCString unique_id(unique_idUTF8);
  nsCOMPtr<nsIRunnable> runnable =
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, nsCString, unsigned int>(
          "camera::PCamerasChild::SendGetCaptureCapability", this,
          &CamerasChild::SendGetCaptureCapability, aCapEngine, unique_id,
          capability_number);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  if (dispatcher.Success()) {
    capability = mReplyCapability;
  }
  return dispatcher.ReturnValue();
}

mozilla::ipc::IPCResult CamerasChild::RecvReplyGetCaptureCapability(
mozilla::ipc::IPCResult CamerasChild::RecvReplyGetCaptureCapability(
    const VideoCaptureCapability& ipcCapability) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReplySuccess = true;
  mReplySuccess = true;
  mReplyCapability.width = ipcCapability.width();
  mReplyCapability.height = ipcCapability.height();
  mReplyCapability.maxFPS = ipcCapability.maxFPS();
  mReplyCapability.videoType =
      static_cast<webrtc::VideoType>(ipcCapability.videoType());
      static_cast<webrtc::VideoType>(ipcCapability.videoType());
  mReplyCapability.interlaced = ipcCapability.interlaced();
  monitor.Notify();
  return IPC_OK();
}


int CamerasChild::GetCaptureDevice(
    CaptureEngine aCapEngine, unsigned int list_number, char* device_nameUTF8,
    const unsigned int device_nameUTF8Length, char* unique_idUTF8,
    const unsigned int unique_idUTF8Length, bool* scary) {
  LOG(("%s", __PRETTY_FUNCTION__));
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, unsigned int>(
          "camera::PCamerasChild::SendGetCaptureDevice", this,
          &CamerasChild::SendGetCaptureDevice, aCapEngine, list_number);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  if (dispatcher.Success()) {
    base::strlcpy(device_nameUTF8, mReplyDeviceName.get(),
                  device_nameUTF8Length);
    base::strlcpy(unique_idUTF8, mReplyDeviceID.get(), unique_idUTF8Length);
    if (scary) {
    if (scary) {
      *scary = mReplyScary;
    }
    LOG(("Got %s name %s id", device_nameUTF8, unique_idUTF8));
  }
  return dispatcher.ReturnValue();
}


mozilla::ipc::IPCResult CamerasChild::RecvReplyGetCaptureDevice(
    const nsCString& device_name, const nsCString& device_id,
    const bool& scary) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReplySuccess = true;
  mReplyDeviceName = device_name;
  mReplyDeviceName = device_name;
  mReplyDeviceID = device_id;
  mReplyScary = scary;
  monitor.Notify();
  return IPC_OK();
}
}

int CamerasChild::AllocateCaptureDevice(CaptureEngine aCapEngine,
                                        const char* unique_idUTF8,
                                        const unsigned int unique_idUTF8Length,
                                        int& aStreamId, uint64_t aWindowID) {
                                        int& aStreamId, uint64_t aWindowID) {
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCString unique_id(unique_idUTF8);
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, nsCString, const uint64_t&>(
          "camera::PCamerasChild::SendAllocateCaptureDevice", this,
          "camera::PCamerasChild::SendAllocateCaptureDevice", this,
          &CamerasChild::SendAllocateCaptureDevice, aCapEngine, unique_id,
          aWindowID);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  if (dispatcher.Success()) {
    LOG(("Capture Device allocated: %d", mReplyInteger));
    LOG(("Capture Device allocated: %d", mReplyInteger));
    aStreamId = mReplyInteger;
  }
  return dispatcher.ReturnValue();
}
}

mozilla::ipc::IPCResult CamerasChild::RecvReplyAllocateCaptureDevice(
    const int& numdev) {
  LOG(("%s", __PRETTY_FUNCTION__));
  MonitorAutoLock monitor(mReplyMonitor);
  MonitorAutoLock monitor(mReplyMonitor);
  mReceivedReply = true;
  mReplySuccess = true;
  mReplySuccess = true;
  mReplyInteger = numdev;
  monitor.Notify();
  return IPC_OK();
}


int CamerasChild::ReleaseCaptureDevice(CaptureEngine aCapEngine,
                                       const int capture_id) {
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, int>(
      mozilla::NewRunnableMethod<CaptureEngine, int>(
          "camera::PCamerasChild::SendReleaseCaptureDevice", this,
          &CamerasChild::SendReleaseCaptureDevice, aCapEngine, capture_id);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  return dispatcher.ReturnValue();
}
}

void CamerasChild::AddCallback(const CaptureEngine aCapEngine,
                               const int capture_id, FrameRelay* render) {
  MutexAutoLock lock(mCallbackMutex);
  CapturerElement ce;
  CapturerElement ce;
  ce.engine = aCapEngine;
  ce.id = capture_id;
  ce.callback = render;
  mCallbacks.AppendElement(ce);
}

void CamerasChild::RemoveCallback(const CaptureEngine aCapEngine,
void CamerasChild::RemoveCallback(const CaptureEngine aCapEngine,
                                  const int capture_id) {
  MutexAutoLock lock(mCallbackMutex);
  for (unsigned int i = 0; i < mCallbacks.Length(); i++) {
    CapturerElement ce = mCallbacks[i];
    if (ce.engine == aCapEngine && ce.id == capture_id) {
    if (ce.engine == aCapEngine && ce.id == capture_id) {
      mCallbacks.RemoveElementAt(i);
      break;
    }
  }
}

int CamerasChild::StartCapture(CaptureEngine aCapEngine, const int capture_id,
int CamerasChild::StartCapture(CaptureEngine aCapEngine, const int capture_id,
                               webrtc::VideoCaptureCapability& webrtcCaps,
                               FrameRelay* cb) {
  LOG(("%s", __PRETTY_FUNCTION__));
  AddCallback(aCapEngine, capture_id, cb);
  VideoCaptureCapability capCap(
  VideoCaptureCapability capCap(
      webrtcCaps.width, webrtcCaps.height, webrtcCaps.maxFPS,
      static_cast<int>(webrtcCaps.videoType), webrtcCaps.interlaced);
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, int, VideoCaptureCapability>(
          "camera::PCamerasChild::SendStartCapture", this,
          "camera::PCamerasChild::SendStartCapture", this,
          &CamerasChild::SendStartCapture, aCapEngine, capture_id, capCap);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  return dispatcher.ReturnValue();
}
}

int CamerasChild::FocusOnSelectedSource(CaptureEngine aCapEngine,
                                        const int aCaptureId) {
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCOMPtr<nsIRunnable> runnable =
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, int>(
          "camera::PCamerasChild::SendFocusOnSelectedSource", this,
          &CamerasChild::SendFocusOnSelectedSource, aCapEngine, aCaptureId);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  return dispatcher.ReturnValue();
  return dispatcher.ReturnValue();
}

int CamerasChild::StopCapture(CaptureEngine aCapEngine, const int capture_id) {
  LOG(("%s", __PRETTY_FUNCTION__));
  nsCOMPtr<nsIRunnable> runnable =
  nsCOMPtr<nsIRunnable> runnable =
      mozilla::NewRunnableMethod<CaptureEngine, int>(
      mozilla::NewRunnableMethod<CaptureEngine, int>(
          "camera::PCamerasChild::SendStopCapture", this,
          &CamerasChild::SendStopCapture, aCapEngine, capture_id);
  LockAndDispatch<> dispatcher(this, __func__, runnable, -1, mZero);
  if (dispatcher.Success()) {
    RemoveCallback(aCapEngine, capture_id);
    RemoveCallback(aCapEngine, capture_id);
  }
  return dispatcher.ReturnValue();
}

void Shutdown(void) {
void Shutdown(void) {
  OffTheBooksMutexAutoLock lock(CamerasSingleton::Mutex());

  CamerasSingleton::StartShutdown();

  CamerasChild* child = CamerasSingleton::Child();
  CamerasChild* child = CamerasSingleton::Child();
  if (!child) {
    // We don't want to cause everything to get fired up if we're
    // really already shut down.
    LOG(("Shutdown when already shut down"));
    return;
  }
  child->ShutdownAll();
}


class ShutdownRunnable : public Runnable {
 public:
  explicit ShutdownRunnable(already_AddRefed<Runnable>&& aReplyEvent)
      : Runnable("camera::ShutdownRunnable"), mReplyEvent(aReplyEvent){};


  NS_IMETHOD Run() override {
    LOG(("Closing BackgroundChild"));
    ipc::BackgroundChild::CloseForCurrentThread();

    NS_DispatchToMainThread(mReplyEvent.forget());
    NS_DispatchToMainThread(mReplyEvent.forget());

    return NS_OK;
  }

 private:
 private:
  RefPtr<Runnable> mReplyEvent;
};

void CamerasChild::ShutdownAll() {
  // Called with CamerasSingleton::Mutex() held
  // Called with CamerasSingleton::Mutex() held
  ShutdownParent();
  ShutdownChild();
}

void CamerasChild::ShutdownParent() {
void CamerasChild::ShutdownParent() {
  // Called with CamerasSingleton::Mutex() held
  {
    MonitorAutoLock monitor(mReplyMonitor);
    mIPCIsAlive = false;
    monitor.NotifyAll();
  }
  if (CamerasSingleton::Thread()) {
  if (CamerasSingleton::Thread()) {
    LOG(("Dispatching actor deletion"));
    // Delete the parent actor.
    // CamerasChild (this) will remain alive and is only deleted by the
    // IPC layer when SendAllDone returns.
    nsCOMPtr<nsIRunnable> deleteRunnable = mozilla::NewRunnableMethod(
    nsCOMPtr<nsIRunnable> deleteRunnable = mozilla::NewRunnableMethod(
        "camera::PCamerasChild::SendAllDone", this, &CamerasChild::SendAllDone);
    CamerasSingleton::Thread()->Dispatch(deleteRunnable, NS_DISPATCH_NORMAL);
  } else {
    LOG(("ShutdownParent called without PBackground thread"));
  }
  }
}

void CamerasChild::ShutdownChild() {
  // Called with CamerasSingleton::Mutex() held
  if (CamerasSingleton::Thread()) {
  if (CamerasSingleton::Thread()) {
    LOG(("PBackground thread exists, dispatching close"));
    // Dispatch closing the IPC thread back to us when the
    // BackgroundChild is closed.
    RefPtr<ShutdownRunnable> runnable = new ShutdownRunnable(
        NewRunnableMethod("nsIThread::Shutdown", CamerasSingleton::Thread(),
                          &nsIThread::Shutdown));
                          &nsIThread::Shutdown));
    CamerasSingleton::Thread()->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
  } else {
    LOG(("Shutdown called without PBackground thread"));
  }
  LOG(("Erasing sCameras & thread refs (original thread)"));
  LOG(("Erasing sCameras & thread refs (original thread)"));
  CamerasSingleton::Child() = nullptr;
  CamerasSingleton::Thread() = nullptr;
}

mozilla::ipc::IPCResult CamerasChild::RecvDeliverFrame(
    const CaptureEngine& capEngine, const int& capId,
    mozilla::ipc::Shmem&& shmem, const VideoFrameProperties& prop) {
    mozilla::ipc::Shmem&& shmem, const VideoFrameProperties& prop) {
  MutexAutoLock lock(mCallbackMutex);
  if (Callback(capEngine, capId)) {
    unsigned char* image = shmem.get<unsigned char>();
    Callback(capEngine, capId)->DeliverFrame(image, prop);
  } else {
  } else {
    LOG(("DeliverFrame called with dead callback"));
  }
  SendReleaseFrame(std::move(shmem));
  return IPC_OK();
}
}

mozilla::ipc::IPCResult CamerasChild::RecvDeviceChange() {
  mDeviceListChangeEvent.Notify();
  return IPC_OK();
}
}

void CamerasChild::ActorDestroy(ActorDestroyReason aWhy) {
  MonitorAutoLock monitor(mReplyMonitor);
  mIPCIsAlive = false;
  // Hopefully prevent us from getting stuck
  // Hopefully prevent us from getting stuck
  // on replies that'll never come.
  monitor.NotifyAll();
}

CamerasChild::CamerasChild()
CamerasChild::CamerasChild()
    : mCallbackMutex("mozilla::cameras::CamerasChild::mCallbackMutex"),
      mIPCIsAlive(true),
      mRequestMutex("mozilla::cameras::CamerasChild::mRequestMutex"),
      mReplyMonitor("mozilla::cameras::CamerasChild::mReplyMonitor"),
      mReceivedReply(false),
      mReceivedReply(false),
      mReplySuccess(false),
      mZero(0),
      mReplyInteger(0),
      mReplyScary(false) {
  LOG(("CamerasChild: %p", this));
  LOG(("CamerasChild: %p", this));

  MOZ_COUNT_CTOR(CamerasChild);
}

CamerasChild::~CamerasChild() {
CamerasChild::~CamerasChild() {
  LOG(("~CamerasChild: %p", this));

  if (!CamerasSingleton::InShutdown()) {
    OffTheBooksMutexAutoLock lock(CamerasSingleton::Mutex());
    OffTheBooksMutexAutoLock lock(CamerasSingleton::Mutex());
    // In normal circumstances we've already shut down and the
    // following does nothing. But on fatal IPC errors we will
    // get destructed immediately, and should not try to reach
    // the parent.
    ShutdownChild();
    ShutdownChild();
  }

  MOZ_COUNT_DTOR(CamerasChild);
}


FrameRelay* CamerasChild::Callback(CaptureEngine aCapEngine, int capture_id) {
  for (unsigned int i = 0; i < mCallbacks.Length(); i++) {
    CapturerElement ce = mCallbacks[i];
    if (ce.engine == aCapEngine && ce.id == capture_id) {
      return ce.callback;
    }
    }
  }

  return nullptr;
}


}  // namespace camera
}  // namespace mozilla