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 : mWrapper(nullptr), 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 : mWrapper(nullptr), mInternal(new InternalData()) {
53 init(buffers, buffer_size, growthLimit);
54 }
55
init(size_t buffers,size_t buffer_size,size_t growthLimit)56 void MediaBufferGroup::init(size_t buffers, size_t buffer_size, size_t growthLimit) {
57 mInternal->mGrowthLimit = growthLimit;
58
59 if (mInternal->mGrowthLimit > 0 && buffers > mInternal->mGrowthLimit) {
60 ALOGW("Preallocated buffers %zu > growthLimit %zu, increasing growthLimit",
61 buffers, mInternal->mGrowthLimit);
62 mInternal->mGrowthLimit = buffers;
63 }
64
65 #ifndef NO_IMEMORY
66 if (buffer_size >= kSharedMemoryThreshold) {
67 ALOGD("creating MemoryDealer");
68 // Using a single MemoryDealer is efficient for a group of shared memory objects.
69 // This loop guarantees that we use shared memory (no fallback to malloc).
70
71 size_t alignment = MemoryDealer::getAllocationAlignment();
72 size_t augmented_size = buffer_size + sizeof(MediaBuffer::SharedControl);
73 size_t total = (augmented_size + alignment - 1) / alignment * alignment * buffers;
74 sp<MemoryDealer> memoryDealer = new MemoryDealer(total, "MediaBufferGroup");
75
76 for (size_t i = 0; i < buffers; ++i) {
77 sp<IMemory> mem = memoryDealer->allocate(augmented_size);
78 if (mem.get() == nullptr || mem->pointer() == nullptr) {
79 ALOGW("Only allocated %zu shared buffers of size %zu", i, buffer_size);
80 break;
81 }
82 MediaBuffer *buffer = new MediaBuffer(mem);
83 buffer->getSharedControl()->clear();
84 add_buffer(buffer);
85 }
86 return;
87 }
88 #else
89 (void)kSharedMemoryThreshold;
90 #endif
91
92 // Non-shared memory allocation.
93 for (size_t i = 0; i < buffers; ++i) {
94 MediaBuffer *buffer = new MediaBuffer(buffer_size);
95 if (buffer->data() == nullptr) {
96 delete buffer; // don't call release, it's not properly formed
97 ALOGW("Only allocated %zu malloc buffers of size %zu", i, buffer_size);
98 break;
99 }
100 add_buffer(buffer);
101 }
102 }
103
~MediaBufferGroup()104 MediaBufferGroup::~MediaBufferGroup() {
105 for (MediaBufferBase *buffer : mInternal->mBuffers) {
106 if (buffer->refcount() != 0) {
107 const int localRefcount = buffer->localRefcount();
108 const int remoteRefcount = buffer->remoteRefcount();
109
110 // Fatal if we have a local refcount.
111 LOG_ALWAYS_FATAL_IF(localRefcount != 0,
112 "buffer(%p) localRefcount %d != 0, remoteRefcount %d",
113 buffer, localRefcount, remoteRefcount);
114
115 // Log an error if we have a remaining remote refcount,
116 // as the remote process may have died or may have inappropriate behavior.
117 // The shared memory associated with the MediaBuffer will
118 // automatically be reclaimed when there are no remaining fds
119 // associated with it.
120 ALOGE("buffer(%p) has residual remoteRefcount %d",
121 buffer, remoteRefcount);
122 }
123 // gracefully delete.
124 buffer->setObserver(nullptr);
125 buffer->release();
126 }
127 delete mInternal;
128 delete mWrapper;
129 }
130
add_buffer(MediaBufferBase * buffer)131 void MediaBufferGroup::add_buffer(MediaBufferBase *buffer) {
132 Mutex::Autolock autoLock(mInternal->mLock);
133
134 // if we're above our growth limit, release buffers if we can
135 for (auto it = mInternal->mBuffers.begin();
136 mInternal->mGrowthLimit > 0
137 && mInternal->mBuffers.size() >= mInternal->mGrowthLimit
138 && it != mInternal->mBuffers.end();) {
139 if ((*it)->refcount() == 0) {
140 (*it)->setObserver(nullptr);
141 (*it)->release();
142 it = mInternal->mBuffers.erase(it);
143 } else {
144 ++it;
145 }
146 }
147
148 buffer->setObserver(this);
149 mInternal->mBuffers.emplace_back(buffer);
150 }
151
has_buffers()152 bool MediaBufferGroup::has_buffers() {
153 if (mInternal->mBuffers.size() < mInternal->mGrowthLimit) {
154 return true; // We can add more buffers internally.
155 }
156 for (MediaBufferBase *buffer : mInternal->mBuffers) {
157 if (buffer->refcount() == 0) {
158 return true;
159 }
160 }
161 return false;
162 }
163
acquire_buffer(MediaBufferBase ** out,bool nonBlocking,size_t requestedSize)164 status_t MediaBufferGroup::acquire_buffer(
165 MediaBufferBase **out, bool nonBlocking, size_t requestedSize) {
166 Mutex::Autolock autoLock(mInternal->mLock);
167 for (;;) {
168 size_t smallest = requestedSize;
169 size_t biggest = requestedSize;
170 MediaBufferBase *buffer = nullptr;
171 auto free = mInternal->mBuffers.end();
172 for (auto it = mInternal->mBuffers.begin(); it != mInternal->mBuffers.end(); ++it) {
173 const size_t size = (*it)->size();
174 if (size > biggest) {
175 biggest = size;
176 }
177 if ((*it)->refcount() == 0) {
178 if (size >= requestedSize) {
179 buffer = *it;
180 break;
181 }
182 if (size < smallest) {
183 smallest = size; // always free the smallest buf
184 free = it;
185 }
186 }
187 }
188 if (buffer == nullptr
189 && (free != mInternal->mBuffers.end()
190 || mInternal->mBuffers.size() < mInternal->mGrowthLimit)) {
191 // We alloc before we free so failure leaves group unchanged.
192 const size_t allocateSize = requestedSize == 0 ? biggest :
193 requestedSize < SIZE_MAX / 3 * 2 /* NB: ordering */ ?
194 requestedSize * 3 / 2 : requestedSize;
195 buffer = new MediaBuffer(allocateSize);
196 if (buffer->data() == nullptr) {
197 ALOGE("Allocation failure for size %zu", allocateSize);
198 delete buffer; // Invalid alloc, prefer not to call release.
199 buffer = nullptr;
200 } else {
201 buffer->setObserver(this);
202 if (free != mInternal->mBuffers.end()) {
203 ALOGV("reallocate buffer, requested size %zu vs available %zu",
204 requestedSize, (*free)->size());
205 (*free)->setObserver(nullptr);
206 (*free)->release();
207 *free = buffer; // in-place replace
208 } else {
209 ALOGV("allocate buffer, requested size %zu", requestedSize);
210 mInternal->mBuffers.emplace_back(buffer);
211 }
212 }
213 }
214 if (buffer != nullptr) {
215 buffer->add_ref();
216 buffer->reset();
217 *out = buffer;
218 return OK;
219 }
220 if (nonBlocking) {
221 *out = nullptr;
222 return WOULD_BLOCK;
223 }
224 // All buffers are in use, block until one of them is returned.
225 mInternal->mCondition.wait(mInternal->mLock);
226 }
227 // Never gets here.
228 }
229
buffers() const230 size_t MediaBufferGroup::buffers() const {
231 return mInternal->mBuffers.size();
232 }
233
signalBufferReturned(MediaBufferBase *)234 void MediaBufferGroup::signalBufferReturned(MediaBufferBase *) {
235 Mutex::Autolock autoLock(mInternal->mLock);
236 mInternal->mCondition.signal();
237 }
238
239 } // namespace android
240