summaryrefslogtreecommitdiffstats
path: root/dom/media/webrtc/jsapi/RTCEncodedFrameBase.cpp
blob: 79d357d4384ac641229d7f9c12fa7a06bc889b0a (plain)
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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 https://mozilla.org/MPL/2.0/. */

#include "jsapi/RTCEncodedFrameBase.h"

#include "js/GCAPI.h"
#include "nsIGlobalObject.h"
#include "mozilla/dom/ScriptSettings.h"
#include "js/ArrayBuffer.h"

namespace mozilla::dom {
NS_IMPL_CYCLE_COLLECTION_WITH_JS_MEMBERS(RTCEncodedFrameBase, (mGlobal),
                                         (mData))
NS_IMPL_CYCLE_COLLECTING_ADDREF(RTCEncodedFrameBase)
NS_IMPL_CYCLE_COLLECTING_RELEASE(RTCEncodedFrameBase)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(RTCEncodedFrameBase)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

RTCEncodedFrameBase::RTCEncodedFrameBase(
    nsIGlobalObject* aGlobal,
    std::unique_ptr<webrtc::TransformableFrameInterface> aFrame,
    uint64_t aCounter)
    : mGlobal(aGlobal),
      mFrame(std::move(aFrame)),
      mCounter(aCounter),
      mTimestamp(mFrame->GetTimestamp()) {
  AutoJSAPI jsapi;
  if (NS_WARN_IF(!jsapi.Init(mGlobal))) {
    return;
  }

  // Avoid a copy
  mData = JS::NewArrayBufferWithUserOwnedContents(
      jsapi.cx(), mFrame->GetData().size(), (void*)(mFrame->GetData().data()));
}

RTCEncodedFrameBase::~RTCEncodedFrameBase() = default;

unsigned long RTCEncodedFrameBase::Timestamp() const { return mTimestamp; }

void RTCEncodedFrameBase::SetData(const ArrayBuffer& aData) {
  mData.set(aData.Obj());
  if (mFrame) {
    aData.ProcessData([&](const Span<uint8_t>& aData, JS::AutoCheckCannotGC&&) {
      mFrame->SetData(
          rtc::ArrayView<const uint8_t>(aData.Elements(), aData.Length()));
    });
  }
}

void RTCEncodedFrameBase::GetData(JSContext* aCx, JS::Rooted<JSObject*>* aObj) {
  aObj->set(mData);
}

uint64_t RTCEncodedFrameBase::GetCounter() const { return mCounter; }

std::unique_ptr<webrtc::TransformableFrameInterface>
RTCEncodedFrameBase::TakeFrame() {
  AutoJSAPI jsapi;
  if (!jsapi.Init(mGlobal)) {
    MOZ_CRASH("Could not init JSAPI!");
  }
  JS::Rooted<JSObject*> rootedData(jsapi.cx(), mData);
  JS::DetachArrayBuffer(jsapi.cx(), rootedData);
  return std::move(mFrame);
}

}  // namespace mozilla::dom