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 (56e7b9127e89)

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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* 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 "AllocationPolicy.h"

#include "PDMFactory.h"
#include "MediaInfo.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/SystemGroup.h"
#ifdef MOZ_WIDGET_ANDROID
#include "mozilla/jni/Utils.h"
#endif

namespace mozilla {

using TrackType = TrackInfo::TrackType;

StaticMutex GlobalAllocPolicy::sMutex;

class GlobalAllocPolicy::AutoDeallocToken : public Token
{
public:
  explicit AutoDeallocToken(GlobalAllocPolicy& aPolicy) : mPolicy(aPolicy) { }

private:
  ~AutoDeallocToken()
  {
    mPolicy.Dealloc();
  }

  GlobalAllocPolicy& mPolicy; // reference to a singleton object.
};

static int32_t
MediaDecoderLimitDefault()
{
#ifdef MOZ_WIDGET_ANDROID
  if (jni::GetAPIVersion() < 18) {
    // Older Android versions have broken support for multiple simultaneous
    // decoders, see bug 1278574.
    return 1;
  }
#endif
  // Otherwise, set no decoder limit.
  return -1;
}

GlobalAllocPolicy::GlobalAllocPolicy()
  : mMonitor("DecoderAllocPolicy::mMonitor")
  , mDecoderLimit(MediaDecoderLimitDefault())
{
  SystemGroup::Dispatch(
    TaskCategory::Other,
    NS_NewRunnableFunction("GlobalAllocPolicy::GlobalAllocPolicy", [this]() {
      ClearOnShutdown(this, ShutdownPhase::ShutdownThreads);
    }));
}

GlobalAllocPolicy::~GlobalAllocPolicy()
{
  while (!mPromises.empty()) {
    RefPtr<PromisePrivate> p = mPromises.front().forget();
    mPromises.pop();
    p->Reject(true, __func__);
  }
}

GlobalAllocPolicy&
GlobalAllocPolicy::Instance(TrackType aTrack)
{
  StaticMutexAutoLock lock(sMutex);
  if (aTrack == TrackType::kAudioTrack) {
    static auto sAudioPolicy = new GlobalAllocPolicy();
    return *sAudioPolicy;
  } else {
    static auto sVideoPolicy = new GlobalAllocPolicy();
    return *sVideoPolicy;
  }
}

auto
GlobalAllocPolicy::Alloc() -> RefPtr<Promise>
{
  // No decoder limit set.
  if (mDecoderLimit < 0) {
    return Promise::CreateAndResolve(new Token(), __func__);
  }

  ReentrantMonitorAutoEnter mon(mMonitor);
  RefPtr<PromisePrivate> p = new PromisePrivate(__func__);
  mPromises.push(p);
  ResolvePromise(mon);
  return p.forget();
}

void
GlobalAllocPolicy::Dealloc()
{
  ReentrantMonitorAutoEnter mon(mMonitor);
  ++mDecoderLimit;
  ResolvePromise(mon);
}

void
GlobalAllocPolicy::ResolvePromise(ReentrantMonitorAutoEnter& aProofOfLock)
{
  MOZ_ASSERT(mDecoderLimit >= 0);

  if (mDecoderLimit > 0 && !mPromises.empty()) {
    --mDecoderLimit;
    RefPtr<PromisePrivate> p = mPromises.front().forget();
    mPromises.pop();
    p->Resolve(new AutoDeallocToken(*this), __func__);
  }
}

void
GlobalAllocPolicy::operator=(std::nullptr_t)
{
  delete this;
}

AllocationWrapper::AllocationWrapper(
  already_AddRefed<MediaDataDecoder> aDecoder,
  already_AddRefed<Token> aToken)
  : mDecoder(aDecoder)
  , mToken(aToken)
{
  DecoderDoctorLogger::LogConstructionAndBase(
    "AllocationWrapper", this, static_cast<const MediaDataDecoder*>(this));
  DecoderDoctorLogger::LinkParentAndChild(
    "AllocationWrapper", this, "decoder", mDecoder.get());
}

AllocationWrapper::~AllocationWrapper()
{
  DecoderDoctorLogger::LogDestruction("AllocationWrapper", this);
}

RefPtr<ShutdownPromise>
AllocationWrapper::Shutdown()
{
  RefPtr<MediaDataDecoder> decoder = mDecoder.forget();
  RefPtr<Token> token = mToken.forget();
  return decoder->Shutdown()->Then(
    AbstractThread::GetCurrent(), __func__, [token]() {
      return ShutdownPromise::CreateAndResolve(true, __func__);
    });
}
/* static */ RefPtr<AllocationWrapper::AllocateDecoderPromise>
AllocationWrapper::CreateDecoder(const CreateDecoderParams& aParams)
{
  // aParams.mConfig is guaranteed to stay alive during the lifetime of the
  // MediaDataDecoder, so keeping a pointer to the object is safe.
  const TrackInfo* config = &aParams.mConfig;
  RefPtr<TaskQueue> taskQueue = aParams.mTaskQueue;
  DecoderDoctorDiagnostics* diagnostics = aParams.mDiagnostics;
  RefPtr<layers::ImageContainer> imageContainer = aParams.mImageContainer;
  RefPtr<layers::KnowsCompositor> knowsCompositor = aParams.mKnowsCompositor;
  RefPtr<GMPCrashHelper> crashHelper = aParams.mCrashHelper;
  CreateDecoderParams::UseNullDecoder useNullDecoder = aParams.mUseNullDecoder;
  CreateDecoderParams::NoWrapper noWrapper = aParams.mNoWrapper;
  TrackInfo::TrackType type = aParams.mType;
  MediaEventProducer<TrackInfo::TrackType>* onWaitingForKeyEvent =
    aParams.mOnWaitingForKeyEvent;
  CreateDecoderParams::OptionSet options = aParams.mOptions;
  CreateDecoderParams::VideoFrameRate rate = aParams.mRate;

  RefPtr<AllocateDecoderPromise> p =
    GlobalAllocPolicy::Instance(aParams.mType)
      .Alloc()
      ->Then(
        AbstractThread::GetCurrent(),
        __func__,
        [=](RefPtr<Token> aToken) {
          // result may not always be updated by PDMFactory::CreateDecoder
          // either when the creation succeeded or failed, as such it must be
          // initialized to a fatal error by default.
          MediaResult result = MediaResult(
            NS_ERROR_DOM_MEDIA_FATAL_ERR,
            nsPrintfCString("error creating %s decoder", TrackTypeToStr(type)));
          RefPtr<PDMFactory> pdm = new PDMFactory();
          CreateDecoderParams params{ *config,
                                      taskQueue,
                                      diagnostics,
                                      imageContainer,
                                      &result,
                                      knowsCompositor,
                                      crashHelper,
                                      useNullDecoder,
                                      noWrapper,
                                      type,
                                      onWaitingForKeyEvent,
                                      options,
                                      rate };
          RefPtr<MediaDataDecoder> decoder = pdm->CreateDecoder(params);
          if (decoder) {
            RefPtr<AllocationWrapper> wrapper =
              new AllocationWrapper(decoder.forget(), aToken.forget());
            return AllocateDecoderPromise::CreateAndResolve(wrapper, __func__);
          }
          return AllocateDecoderPromise::CreateAndReject(result, __func__);
        },
        []() {
          return AllocateDecoderPromise::CreateAndReject(
            MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
                        "Allocation policy expired"),
            __func__);
        });
  return p;
}

} // namespace mozilla