1 /*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "MediaBufferGroup"
18 #include <utils/Log.h>
19
20 #include <list>
21
22 #include <binder/MemoryDealer.h>
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/MediaBuffer.h>
25 #include <media/stagefright/MediaBufferGroup.h>
26 #include <utils/threads.h>
27
28 namespace android {
29
30 // std::min is not constexpr in C++11
31 template<typename T>
MIN(const T & a,const T & b)32 constexpr T MIN(const T &a, const T &b) { return a <= b ? a : b; }
33
34 // MediaBufferGroup may create shared memory buffers at a
35 // smaller threshold than an isolated new MediaBuffer.
36 static const size_t kSharedMemoryThreshold = MIN(
37 (size_t)MediaBuffer::kSharedMemThreshold, (size_t)(4 * 1024));
38
39 struct MediaBufferGroup::InternalData {
40 Mutex mLock;
41 Condition mCondition;
42 size_t mGrowthLimit; // Do not automatically grow group larger than this.
43 std::list<MediaBufferBase *> mBuffers;
44 };
45
MediaBufferGroup(size_t growthLimit)46 MediaBufferGroup::MediaBufferGroup(size_t growthLimit)
47 : mInternal(new InternalData()) {
48 mInternal->mGrowthLimit = growthLimit;
49 }
50
MediaBufferGroup(size_t buffers,size_t buffer_size,size_t growthLimit)51 MediaBufferGroup::MediaBufferGroup(size_t buffers, size_t buffer_size, size_t growthLimit)
52 : mInternal(new InternalData()) {
53 mInternal->mGrowthLimit = growthLimit;
54
55 if (mInternal->mGrowthLimit > 0 && buffers > mInternal->mGrowthLimit) {
56 ALOGW("Preallocated buffers %zu > growthLimit %zu, increasing growthLimit",
57 buffers, mInternal->mGrowthLimit);
58 mInternal->mGrowthLimit = buffers;
59 }
60
61 if (buffer_size >= kSharedMemoryThreshold) {
62 ALOGD("creating MemoryDealer");
63 // Using a single MemoryDealer is efficient for a group of shared memory objects.
64 // This loop guarantees that we use shared memory (no fallback to malloc).
65
66 size_t alignment = MemoryDealer::getAllocationAlignment();
67 size_t augmented_size = buffer_size + sizeof(MediaBuffer::SharedControl);
68 size_t total = (augmented_size + alignment - 1) / alignment * alignment * buffers;
69 sp<MemoryDealer> memoryDealer = new MemoryDealer(total, "MediaBufferGroup");
70
71 for (size_t i = 0; i < buffers; ++i) {
72 sp<IMemory> mem = memoryDealer->allocate(augmented_size);
73 if (mem.get() == nullptr || mem->pointer() == nullptr) {
74 ALOGW("Only allocated %zu shared buffers of size %zu", i, buffer_size);
75 break;
76 }
77 MediaBuffer *buffer = new MediaBuffer(mem);
78 buffer->getSharedControl()->clear();
79 add_buffer(buffer);
80 }
81 return;
82 }
83
84 // Non-shared memory allocation.
85 for (size_t i = 0; i < buffers; ++i) {
86 MediaBuffer *buffer = new MediaBuffer(buffer_size);
87 if (buffer->data() == nullptr) {
88 delete buffer; // don't call release, it's not properly formed
89 ALOGW("Only allocated %zu malloc buffers of size %zu", i, buffer_size);
90 break;
91 }
92 add_buffer(buffer);
93 }
94 }
95
~MediaBufferGroup()96 MediaBufferGroup::~MediaBufferGroup() {
97 for (MediaBufferBase *buffer : mInternal->mBuffers) {
98 if (buffer->refcount() != 0) {
99 const int localRefcount = buffer->localRefcount();
100 const int remoteRefcount = buffer->remoteRefcount();
101
102 // Fatal if we have a local refcount.
103 LOG_ALWAYS_FATAL_IF(localRefcount != 0,
104 "buffer(%p) localRefcount %d != 0, remoteRefcount %d",
105 buffer, localRefcount, remoteRefcount);
106
107 // Log an error if we have a remaining remote refcount,
108 // as the remote process may have died or may have inappropriate behavior.
109 // The shared memory associated with the MediaBuffer will
110 // automatically be reclaimed when there are no remaining fds
111 // associated with it.
112 ALOGE("buffer(%p) has residual remoteRefcount %d",
113 buffer, remoteRefcount);
114 }
115 // gracefully delete.
116 buffer->setObserver(nullptr);
117 buffer->release();
118 }
119 delete mInternal;
120 }
121
add_buffer(MediaBufferBase * buffer)122 void MediaBufferGroup::add_buffer(MediaBufferBase *buffer) {
123 Mutex::Autolock autoLock(mInternal->mLock);
124
125 // if we're above our growth limit, release buffers if we can
126 for (auto it = mInternal->mBuffers.begin();
127 mInternal->mGrowthLimit > 0
128 && mInternal->mBuffers.size() >= mInternal->mGrowthLimit
129 && it != mInternal->mBuffers.end();) {
130 if ((*it)->refcount() == 0) {
131 (*it)->setObserver(nullptr);
132 (*it)->release();
133 it = mInternal->mBuffers.erase(it);
134 } else {
135 ++it;
136 }
137 }
138
139 buffer->setObserver(this);
140 mInternal->mBuffers.emplace_back(buffer);
141 }
142
has_buffers()143 bool MediaBufferGroup::has_buffers() {
144 if (mInternal->mBuffers.size() < mInternal->mGrowthLimit) {
145 return true; // We can add more buffers internally.
146 }
147 for (MediaBufferBase *buffer : mInternal->mBuffers) {
148 if (buffer->refcount() == 0) {
149 return true;
150 }
151 }
152 return false;
153 }
154
acquire_buffer(MediaBufferBase ** out,bool nonBlocking,size_t requestedSize)155 status_t MediaBufferGroup::acquire_buffer(
156 MediaBufferBase **out, bool nonBlocking, size_t requestedSize) {
157 Mutex::Autolock autoLock(mInternal->mLock);
158 for (;;) {
159 size_t smallest = requestedSize;
160 MediaBufferBase *buffer = nullptr;
161 auto free = mInternal->mBuffers.end();
162 for (auto it = mInternal->mBuffers.begin(); it != mInternal->mBuffers.end(); ++it) {
163 if ((*it)->refcount() == 0) {
164 const size_t size = (*it)->size();
165 if (size >= requestedSize) {
166 buffer = *it;
167 break;
168 }
169 if (size < smallest) {
170 smallest = size; // always free the smallest buf
171 free = it;
172 }
173 }
174 }
175 if (buffer == nullptr
176 && (free != mInternal->mBuffers.end()
177 || mInternal->mBuffers.size() < mInternal->mGrowthLimit)) {
178 // We alloc before we free so failure leaves group unchanged.
179 const size_t allocateSize = requestedSize < SIZE_MAX / 3 * 2 /* NB: ordering */ ?
180 requestedSize * 3 / 2 : requestedSize;
181 buffer = new MediaBuffer(allocateSize);
182 if (buffer->data() == nullptr) {
183 ALOGE("Allocation failure for size %zu", allocateSize);
184 delete buffer; // Invalid alloc, prefer not to call release.
185 buffer = nullptr;
186 } else {
187 buffer->setObserver(this);
188 if (free != mInternal->mBuffers.end()) {
189 ALOGV("reallocate buffer, requested size %zu vs available %zu",
190 requestedSize, (*free)->size());
191 (*free)->setObserver(nullptr);
192 (*free)->release();
193 *free = buffer; // in-place replace
194 } else {
195 ALOGV("allocate buffer, requested size %zu", requestedSize);
196 mInternal->mBuffers.emplace_back(buffer);
197 }
198 }
199 }
200 if (buffer != nullptr) {
201 buffer->add_ref();
202 buffer->reset();
203 *out = buffer;
204 return OK;
205 }
206 if (nonBlocking) {
207 *out = nullptr;
208 return WOULD_BLOCK;
209 }
210 // All buffers are in use, block until one of them is returned.
211 mInternal->mCondition.wait(mInternal->mLock);
212 }
213 // Never gets here.
214 }
215
buffers() const216 size_t MediaBufferGroup::buffers() const {
217 return mInternal->mBuffers.size();
218 }
219
signalBufferReturned(MediaBufferBase *)220 void MediaBufferGroup::signalBufferReturned(MediaBufferBase *) {
221 Mutex::Autolock autoLock(mInternal->mLock);
222 mInternal->mCondition.signal();
223 }
224
225 } // namespace android
226