AudioCompactor.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "AudioCompactor.h"
  6. #if defined(MOZ_MEMORY)
  7. # include "mozmemory.h"
  8. #endif
  9. namespace mozilla {
  10. static size_t
  11. MallocGoodSize(size_t aSize)
  12. {
  13. # if defined(MOZ_MEMORY)
  14. return malloc_good_size(aSize);
  15. # else
  16. return aSize;
  17. # endif
  18. }
  19. static size_t
  20. TooMuchSlop(size_t aSize, size_t aAllocSize, size_t aMaxSlop)
  21. {
  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. uint32_t
  29. AudioCompactor::GetChunkSamples(uint32_t aFrames, uint32_t aChannels,
  30. size_t aMaxSlop)
  31. {
  32. size_t size = AudioDataSize(aFrames, aChannels);
  33. size_t chunkSize = MallocGoodSize(size);
  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. // Calculate the number of samples based on expected malloc size
  40. // in order to allow as many frames as possible to be packed.
  41. return chunkSize / sizeof(AudioDataValue);
  42. }
  43. uint32_t
  44. AudioCompactor::NativeCopy::operator()(AudioDataValue *aBuffer,
  45. uint32_t aSamples)
  46. {
  47. NS_ASSERTION(aBuffer, "cannot copy to null buffer pointer");
  48. NS_ASSERTION(aSamples, "cannot copy zero values");
  49. size_t bufferBytes = aSamples * sizeof(AudioDataValue);
  50. size_t maxBytes = std::min(bufferBytes, mSourceBytes - mNextByte);
  51. uint32_t frames = maxBytes / BytesPerFrame(mChannels);
  52. size_t bytes = frames * BytesPerFrame(mChannels);
  53. NS_ASSERTION((mNextByte + bytes) <= mSourceBytes,
  54. "tried to copy beyond source buffer");
  55. NS_ASSERTION(bytes <= bufferBytes, "tried to copy beyond destination buffer");
  56. memcpy(aBuffer, mSource + mNextByte, bytes);
  57. mNextByte += bytes;
  58. return frames;
  59. }
  60. } // namespace mozilla