MemoryBlockCache.cpp 7.98 KB
Newer Older
1
2
3
4
5
6
7
8
/* -*- 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 "MemoryBlockCache.h"

9
#include "mozilla/Atomics.h"
10
#include "mozilla/ClearOnShutdown.h"
11
#include "mozilla/Logging.h"
12
#include "mozilla/Services.h"
13
#include "mozilla/StaticPrefs_media.h"
14
#include "nsWeakReference.h"
15
#include "prsystem.h"
16
17
18
19
20

namespace mozilla {

#undef LOG
LazyLogModule gMemoryBlockCacheLog("MemoryBlockCache");
21
#define LOG(x, ...) \
22
23
  MOZ_LOG(gMemoryBlockCacheLog, LogLevel::Debug, ("%p " x, this, ##__VA_ARGS__))

24
25
26
27
// Combined sizes of all MemoryBlockCache buffers.
// Initialized to 0 by non-local static initialization.
// Increases when a buffer grows (during initialization or unexpected OOB
// writes), decreases when a MemoryBlockCache (with its buffer) is destroyed.
28
static Atomic<size_t> gCombinedSizes;
29

30
static int32_t CalculateMaxBlocks(int64_t aContentLength) {
31
  int64_t maxSize = int64_t(StaticPrefs::media_memory_cache_max_size()) * 1024;
32
33
  MOZ_ASSERT(aContentLength <= maxSize);
  MOZ_ASSERT(maxSize % MediaBlockCacheBase::BLOCK_SIZE == 0);
34
35
  // Note: It doesn't matter if calculations overflow, Init() would later fail.
  // We want at least enough blocks to contain the original content length.
36
  const int32_t requiredBlocks = maxSize / MediaBlockCacheBase::BLOCK_SIZE;
37
38
  // Allow at least 1s of ultra HD (25Mbps).
  const int32_t workableBlocks =
39
      25 * 1024 * 1024 / 8 / MediaBlockCacheBase::BLOCK_SIZE;
40
41
42
  return std::max(requiredBlocks, workableBlocks);
}

43
MemoryBlockCache::MemoryBlockCache(int64_t aContentLength)
44
45
46
47
48
    // Buffer whole blocks.
    : mInitialContentLength((aContentLength >= 0) ? size_t(aContentLength) : 0),
      mMaxBlocks(CalculateMaxBlocks(aContentLength)),
      mMutex("MemoryBlockCache"),
      mHasGrown(false) {
49
  if (aContentLength <= 0) {
50
    LOG("MemoryBlockCache() MEMORYBLOCKCACHE_ERRORS='InitUnderuse'");
51
  }
52
53
}

54
MemoryBlockCache::~MemoryBlockCache() {
55
  MOZ_ASSERT(gCombinedSizes >= mBuffer.Length());
56
  size_t sizes = static_cast<size_t>(gCombinedSizes -= mBuffer.Length());
57
58
  LOG("~MemoryBlockCache() - destroying buffer of size %zu; combined sizes now "
      "%zu",
59
      mBuffer.Length(), sizes);
60
61
}

62
bool MemoryBlockCache::EnsureBufferCanContain(size_t aContentLength) {
63
64
65
66
  mMutex.AssertCurrentThreadOwns();
  if (aContentLength == 0) {
    return true;
  }
67
68
  const size_t initialLength = mBuffer.Length();
  const size_t desiredLength =
69
      ((aContentLength - 1) / BLOCK_SIZE + 1) * BLOCK_SIZE;
70
  if (initialLength >= desiredLength) {
71
72
73
    // Already large enough.
    return true;
  }
74
75
  // Need larger buffer. If we are allowed more memory, attempt to re-allocate.
  const size_t extra = desiredLength - initialLength;
76
77
78
79
80
81
82
83
84
85
86
87
88
  // Only check the very first allocation against the combined MemoryBlockCache
  // limit. Further growths will always be allowed, assuming MediaCache won't
  // go over GetMaxBlocks() by too much.
  if (initialLength == 0) {
    // Note: There is a small race between testing `atomic + extra > limit` and
    // committing to it with `atomic += extra` below; but this is acceptable, as
    // in the worst case it may allow a small number of buffers to go past the
    // limit.
    // The alternative would have been to reserve the space first with
    // `atomic += extra` and then undo it with `atomic -= extra` in case of
    // failure; but this would have meant potentially preventing other (small
    // but successful) allocations.
    static const size_t sysmem =
89
        std::max<size_t>(PR_GetPhysicalMemorySize(), 32 * 1024 * 1024);
90
    const size_t limit = std::min(
91
92
93
        size_t(StaticPrefs::media_memory_caches_combined_limit_kb()) * 1024,
        sysmem * StaticPrefs::media_memory_caches_combined_limit_pc_sysmem() /
            100);
94
95
96
97
    const size_t currentSizes = static_cast<size_t>(gCombinedSizes);
    if (currentSizes + extra > limit) {
      LOG("EnsureBufferCanContain(%zu) - buffer size %zu, wanted + %zu = %zu;"
          " combined sizes %zu + %zu > limit %zu",
98
99
          aContentLength, initialLength, extra, desiredLength, currentSizes,
          extra, limit);
100
101
      return false;
    }
102
  }
103
  if (!mBuffer.SetLength(desiredLength, mozilla::fallible)) {
104
105
    LOG("EnsureBufferCanContain(%zu) - buffer size %zu, wanted + %zu = %zu, "
        "allocation failed",
106
        aContentLength, initialLength, extra, desiredLength);
107
108
    return false;
  }
109
110
111
112
113
114
115
116
117
  MOZ_ASSERT(mBuffer.Length() == desiredLength);
  const size_t capacity = mBuffer.Capacity();
  const size_t extraCapacity = capacity - desiredLength;
  if (extraCapacity != 0) {
    // Our buffer was given a larger capacity than the requested length, we may
    // as well claim that extra capacity, both for our accounting, and to
    // possibly bypass some future growths that would fit in this new capacity.
    mBuffer.SetLength(capacity);
  }
118
119
120
121
  const size_t newSizes = gCombinedSizes += (extra + extraCapacity);
  LOG("EnsureBufferCanContain(%zu) - buffer size %zu + requested %zu + bonus "
      "%zu = %zu; combined sizes %zu",
      aContentLength, initialLength, extra, extraCapacity, capacity, newSizes);
122
  mHasGrown = true;
123
  return true;
124
125
}

126
nsresult MemoryBlockCache::Init() {
127
  LOG("Init()");
128
  MutexAutoLock lock(mMutex);
129
130
131
132
133
  MOZ_ASSERT(mBuffer.IsEmpty());
  // Attempt to pre-allocate buffer for expected content length.
  if (!EnsureBufferCanContain(mInitialContentLength)) {
    LOG("Init() MEMORYBLOCKCACHE_ERRORS='InitAllocation'");
    return NS_ERROR_FAILURE;
134
135
  }
  return NS_OK;
136
137
}

138
void MemoryBlockCache::Flush() {
139
140
141
142
143
144
145
  LOG("Flush()");
  MutexAutoLock lock(mMutex);
  MOZ_ASSERT(mBuffer.Length() >= mInitialContentLength);
  memset(mBuffer.Elements(), 0, mBuffer.Length());
  mHasGrown = false;
}

146
147
148
nsresult MemoryBlockCache::WriteBlock(uint32_t aBlockIndex,
                                      Span<const uint8_t> aData1,
                                      Span<const uint8_t> aData2) {
149
150
151
  MutexAutoLock lock(mMutex);

  size_t offset = BlockIndexToOffset(aBlockIndex);
152
153
  if (offset + aData1.Length() + aData2.Length() > mBuffer.Length() &&
      !mHasGrown) {
154
    LOG("WriteBlock() MEMORYBLOCKCACHE_ERRORS='WriteBlockOverflow'");
155
  }
156
  if (!EnsureBufferCanContain(offset + aData1.Length() + aData2.Length())) {
157
    LOG("WriteBlock() MEMORYBLOCKCACHE_ERRORS='WriteBlockCannotGrow'");
158
159
160
161
162
    return NS_ERROR_FAILURE;
  }

  memcpy(mBuffer.Elements() + offset, aData1.Elements(), aData1.Length());
  if (aData2.Length() > 0) {
163
    memcpy(mBuffer.Elements() + offset + aData1.Length(), aData2.Elements(),
164
165
166
167
168
169
           aData2.Length());
  }

  return NS_OK;
}

170
171
nsresult MemoryBlockCache::Read(int64_t aOffset, uint8_t* aData,
                                int32_t aLength, int32_t* aBytes) {
172
173
174
175
  MutexAutoLock lock(mMutex);

  MOZ_ASSERT(aOffset >= 0);
  if (aOffset + aLength > int64_t(mBuffer.Length())) {
176
    LOG("Read() MEMORYBLOCKCACHE_ERRORS='ReadOverrun'");
177
178
179
180
181
182
183
184
185
    return NS_ERROR_FAILURE;
  }

  memcpy(aData, mBuffer.Elements() + aOffset, aLength);
  *aBytes = aLength;

  return NS_OK;
}

186
187
nsresult MemoryBlockCache::MoveBlock(int32_t aSourceBlockIndex,
                                     int32_t aDestBlockIndex) {
188
189
190
191
  MutexAutoLock lock(mMutex);

  size_t sourceOffset = BlockIndexToOffset(aSourceBlockIndex);
  size_t destOffset = BlockIndexToOffset(aDestBlockIndex);
192
  if (sourceOffset + BLOCK_SIZE > mBuffer.Length()) {
193
    LOG("MoveBlock() MEMORYBLOCKCACHE_ERRORS='MoveBlockSourceOverrun'");
194
195
196
    return NS_ERROR_FAILURE;
  }
  if (destOffset + BLOCK_SIZE > mBuffer.Length() && !mHasGrown) {
197
    LOG("MoveBlock() MEMORYBLOCKCACHE_ERRORS='MoveBlockDestOverflow'");
198
199
  }
  if (!EnsureBufferCanContain(destOffset + BLOCK_SIZE)) {
200
    LOG("MoveBlock() MEMORYBLOCKCACHE_ERRORS='MoveBlockCannotGrow'");
201
202
203
    return NS_ERROR_FAILURE;
  }

204
  memcpy(mBuffer.Elements() + destOffset, mBuffer.Elements() + sourceOffset,
205
206
207
208
209
         BLOCK_SIZE);

  return NS_OK;
}

210
}  // End namespace mozilla.
211
212
213

// avoid redefined macro in unified build
#undef LOG