1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/content/media/AudioCompactor.cpp Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,73 @@ 1.4 +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.5 +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ 1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 +#include "AudioCompactor.h" 1.10 +#if defined(MOZ_MEMORY) 1.11 +# include "mozmemory.h" 1.12 +#endif 1.13 + 1.14 +namespace mozilla { 1.15 + 1.16 +static size_t 1.17 +MallocGoodSize(size_t aSize) 1.18 +{ 1.19 +# if defined(MOZ_MEMORY) 1.20 + return malloc_good_size(aSize); 1.21 +# else 1.22 + return aSize; 1.23 +# endif 1.24 +} 1.25 + 1.26 +static size_t 1.27 +TooMuchSlop(size_t aSize, size_t aAllocSize, size_t aMaxSlop) 1.28 +{ 1.29 + // If the allocated size is less then our target size, then we 1.30 + // are chunking. This means it will be completely filled with 1.31 + // zero slop. 1.32 + size_t slop = (aAllocSize > aSize) ? (aAllocSize - aSize) : 0; 1.33 + return slop > aMaxSlop; 1.34 +} 1.35 + 1.36 +uint32_t 1.37 +AudioCompactor::GetChunkSamples(uint32_t aFrames, uint32_t aChannels, 1.38 + size_t aMaxSlop) 1.39 +{ 1.40 + size_t size = AudioDataSize(aFrames, aChannels); 1.41 + size_t chunkSize = MallocGoodSize(size); 1.42 + 1.43 + // Reduce the chunk size until we meet our slop goal or the chunk 1.44 + // approaches an unreasonably small size. 1.45 + while (chunkSize > 64 && TooMuchSlop(size, chunkSize, aMaxSlop)) { 1.46 + chunkSize = MallocGoodSize(chunkSize / 2); 1.47 + } 1.48 + 1.49 + // Calculate the number of samples based on expected malloc size 1.50 + // in order to allow as many frames as possible to be packed. 1.51 + return chunkSize / sizeof(AudioDataValue); 1.52 +} 1.53 + 1.54 +uint32_t 1.55 +AudioCompactor::NativeCopy::operator()(AudioDataValue *aBuffer, 1.56 + uint32_t aSamples) 1.57 +{ 1.58 + NS_ASSERTION(aBuffer, "cannot copy to null buffer pointer"); 1.59 + NS_ASSERTION(aSamples, "cannot copy zero values"); 1.60 + 1.61 + size_t bufferBytes = aSamples * sizeof(AudioDataValue); 1.62 + size_t maxBytes = std::min(bufferBytes, mSourceBytes - mNextByte); 1.63 + uint32_t frames = maxBytes / BytesPerFrame(mChannels); 1.64 + size_t bytes = frames * BytesPerFrame(mChannels); 1.65 + 1.66 + NS_ASSERTION((mNextByte + bytes) <= mSourceBytes, 1.67 + "tried to copy beyond source buffer"); 1.68 + NS_ASSERTION(bytes <= bufferBytes, "tried to copy beyond destination buffer"); 1.69 + 1.70 + memcpy(aBuffer, mSource + mNextByte, bytes); 1.71 + 1.72 + mNextByte += bytes; 1.73 + return frames; 1.74 +} 1.75 + 1.76 +} // namespace mozilla