no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / dom / media / AudioCompactor.cpp
blob54e723d55ef7d3aa400c04dad5c141f730abd1db
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
11 namespace mozilla {
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
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;
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);
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);
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);
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");
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);
55 NS_ASSERTION((mNextByte + bytes) <= mSourceBytes,
56 "tried to copy beyond source buffer");
57 NS_ASSERTION(bytes <= bufferBytes, "tried to copy beyond destination buffer");
59 memcpy(aBuffer, mSource + mNextByte, bytes);
61 mNextByte += bytes;
62 return frames;
65 } // namespace mozilla