michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=8 sts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: #include "AudioCompactor.h" michael@0: #if defined(MOZ_MEMORY) michael@0: # include "mozmemory.h" michael@0: #endif michael@0: michael@0: namespace mozilla { michael@0: michael@0: static size_t michael@0: MallocGoodSize(size_t aSize) michael@0: { michael@0: # if defined(MOZ_MEMORY) michael@0: return malloc_good_size(aSize); michael@0: # else michael@0: return aSize; michael@0: # endif michael@0: } michael@0: michael@0: static size_t michael@0: TooMuchSlop(size_t aSize, size_t aAllocSize, size_t aMaxSlop) michael@0: { michael@0: // If the allocated size is less then our target size, then we michael@0: // are chunking. This means it will be completely filled with michael@0: // zero slop. michael@0: size_t slop = (aAllocSize > aSize) ? (aAllocSize - aSize) : 0; michael@0: return slop > aMaxSlop; michael@0: } michael@0: michael@0: uint32_t michael@0: AudioCompactor::GetChunkSamples(uint32_t aFrames, uint32_t aChannels, michael@0: size_t aMaxSlop) michael@0: { michael@0: size_t size = AudioDataSize(aFrames, aChannels); michael@0: size_t chunkSize = MallocGoodSize(size); michael@0: michael@0: // Reduce the chunk size until we meet our slop goal or the chunk michael@0: // approaches an unreasonably small size. michael@0: while (chunkSize > 64 && TooMuchSlop(size, chunkSize, aMaxSlop)) { michael@0: chunkSize = MallocGoodSize(chunkSize / 2); michael@0: } michael@0: michael@0: // Calculate the number of samples based on expected malloc size michael@0: // in order to allow as many frames as possible to be packed. michael@0: return chunkSize / sizeof(AudioDataValue); michael@0: } michael@0: michael@0: uint32_t michael@0: AudioCompactor::NativeCopy::operator()(AudioDataValue *aBuffer, michael@0: uint32_t aSamples) michael@0: { michael@0: NS_ASSERTION(aBuffer, "cannot copy to null buffer pointer"); michael@0: NS_ASSERTION(aSamples, "cannot copy zero values"); michael@0: michael@0: size_t bufferBytes = aSamples * sizeof(AudioDataValue); michael@0: size_t maxBytes = std::min(bufferBytes, mSourceBytes - mNextByte); michael@0: uint32_t frames = maxBytes / BytesPerFrame(mChannels); michael@0: size_t bytes = frames * BytesPerFrame(mChannels); michael@0: michael@0: NS_ASSERTION((mNextByte + bytes) <= mSourceBytes, michael@0: "tried to copy beyond source buffer"); michael@0: NS_ASSERTION(bytes <= bufferBytes, "tried to copy beyond destination buffer"); michael@0: michael@0: memcpy(aBuffer, mSource + mNextByte, bytes); michael@0: michael@0: mNextByte += bytes; michael@0: return frames; michael@0: } michael@0: michael@0: } // namespace mozilla