tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

AudioCompactor.cpp (2329B)


      1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
      2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
      3 /* This Source Code Form is subject to the terms of the Mozilla Public
      4 * License, v. 2.0. If a copy of the MPL was not distributed with this
      5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      6 #include "AudioCompactor.h"
      7 #if defined(MOZ_MEMORY)
      8 #  include "mozmemory.h"
      9 #endif
     10 
     11 namespace mozilla {
     12 
     13 static size_t MallocGoodSize(size_t aSize) {
     14 #if defined(MOZ_MEMORY)
     15  return malloc_good_size(aSize);
     16 #else
     17  return aSize;
     18 #endif
     19 }
     20 
     21 static size_t TooMuchSlop(size_t aSize, size_t aAllocSize, size_t aMaxSlop) {
     22  // If the allocated size is less then our target size, then we
     23  // are chunking.  This means it will be completely filled with
     24  // zero slop.
     25  size_t slop = (aAllocSize > aSize) ? (aAllocSize - aSize) : 0;
     26  return slop > aMaxSlop;
     27 }
     28 
     29 uint32_t AudioCompactor::GetChunkSamples(uint32_t aFrames, uint32_t aChannels,
     30                                         size_t aMaxSlop) {
     31  size_t size = AudioDataSize(aFrames, aChannels);
     32  size_t chunkSize = MallocGoodSize(size);
     33 
     34  // Reduce the chunk size until we meet our slop goal or the chunk
     35  // approaches an unreasonably small size.
     36  while (chunkSize > 64 && TooMuchSlop(size, chunkSize, aMaxSlop)) {
     37    chunkSize = MallocGoodSize(chunkSize / 2);
     38  }
     39 
     40  // Calculate the number of samples based on expected malloc size
     41  // in order to allow as many frames as possible to be packed.
     42  return chunkSize / sizeof(AudioDataValue);
     43 }
     44 
     45 uint32_t AudioCompactor::NativeCopy::operator()(AudioDataValue* aBuffer,
     46                                                uint32_t aSamples) {
     47  NS_ASSERTION(aBuffer, "cannot copy to null buffer pointer");
     48  NS_ASSERTION(aSamples, "cannot copy zero values");
     49 
     50  size_t bufferBytes = aSamples * sizeof(AudioDataValue);
     51  size_t maxBytes = std::min(bufferBytes, mSourceBytes - mNextByte);
     52  uint32_t frames = maxBytes / BytesPerFrame(mChannels);
     53  size_t bytes = frames * BytesPerFrame(mChannels);
     54 
     55  NS_ASSERTION((mNextByte + bytes) <= mSourceBytes,
     56               "tried to copy beyond source buffer");
     57  NS_ASSERTION(bytes <= bufferBytes, "tried to copy beyond destination buffer");
     58 
     59  memcpy(aBuffer, mSource + mNextByte, bytes);
     60 
     61  mNextByte += bytes;
     62  return frames;
     63 }
     64 
     65 }  // namespace mozilla