1 /*
2  * Copyright 2016 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_NDEBUG 0
18 #define LOG_TAG "Camera3-BufferManager"
19 #define ATRACE_TAG ATRACE_TAG_CAMERA
20 
21 #include <gui/ISurfaceComposer.h>
22 #include <private/gui/ComposerService.h>
23 #include <utils/Log.h>
24 #include <utils/Trace.h>
25 #include "utils/CameraTraces.h"
26 #include "Camera3BufferManager.h"
27 
28 namespace android {
29 
30 namespace camera3 {
31 
Camera3BufferManager()32 Camera3BufferManager::Camera3BufferManager() {
33 }
34 
~Camera3BufferManager()35 Camera3BufferManager::~Camera3BufferManager() {
36 }
37 
registerStream(wp<Camera3OutputStream> & stream,const StreamInfo & streamInfo)38 status_t Camera3BufferManager::registerStream(wp<Camera3OutputStream>& stream,
39         const StreamInfo& streamInfo) {
40     ATRACE_CALL();
41 
42     int streamId = streamInfo.streamId;
43     int streamSetId = streamInfo.streamSetId;
44 
45     if (streamId == CAMERA3_STREAM_ID_INVALID || streamSetId == CAMERA3_STREAM_SET_ID_INVALID) {
46         ALOGE("%s: Stream id (%d) or stream set id (%d) is invalid",
47                 __FUNCTION__, streamId, streamSetId);
48         return BAD_VALUE;
49     }
50     if (streamInfo.totalBufferCount > kMaxBufferCount || streamInfo.totalBufferCount == 0) {
51         ALOGE("%s: Stream id (%d) with stream set id (%d) total buffer count %zu is invalid",
52                 __FUNCTION__, streamId, streamSetId, streamInfo.totalBufferCount);
53         return BAD_VALUE;
54     }
55     if (!streamInfo.isConfigured) {
56         ALOGE("%s: Stream (%d) is not configured", __FUNCTION__, streamId);
57         return BAD_VALUE;
58     }
59 
60     // For Gralloc v1, try to allocate a buffer and see if it is successful, otherwise, stream
61     // buffer sharing for this newly added stream is not supported. For Gralloc v0, we don't
62     // need check this, as the buffers are not really shared between streams, the buffers are
63     // allocated for each stream individually, the allocation failure will be checked in
64     // getBufferForStream() call.
65     if (mGrallocVersion > HARDWARE_DEVICE_API_VERSION(0,1)) {
66         // TODO: To be implemented.
67 
68         // In case allocation fails, return invalid operation
69         return INVALID_OPERATION;
70     }
71 
72     Mutex::Autolock l(mLock);
73 
74     // Check if this stream was registered with different stream set ID, if so, error out.
75     for (size_t i = 0; i < mStreamSetMap.size(); i++) {
76         ssize_t streamIdx = mStreamSetMap[i].streamInfoMap.indexOfKey(streamId);
77         if (streamIdx != NAME_NOT_FOUND &&
78             mStreamSetMap[i].streamInfoMap[streamIdx].streamSetId != streamInfo.streamSetId) {
79             ALOGE("%s: It is illegal to register the same stream id with different stream set",
80                     __FUNCTION__);
81             return BAD_VALUE;
82         }
83     }
84     // Check if there is an existing stream set registered; if not, create one; otherwise, add this
85     // stream info to the existing stream set entry.
86     ssize_t setIdx = mStreamSetMap.indexOfKey(streamSetId);
87     if (setIdx == NAME_NOT_FOUND) {
88         ALOGV("%s: stream set %d is not registered to stream set map yet, create it.",
89                 __FUNCTION__, streamSetId);
90         // Create stream info map, then add to mStreamsetMap.
91         StreamSet newStreamSet;
92         setIdx = mStreamSetMap.add(streamSetId, newStreamSet);
93     }
94     // Update stream set map and water mark.
95     StreamSet& currentStreamSet = mStreamSetMap.editValueAt(setIdx);
96     ssize_t streamIdx = currentStreamSet.streamInfoMap.indexOfKey(streamId);
97     if (streamIdx != NAME_NOT_FOUND) {
98         ALOGW("%s: stream %d was already registered with stream set %d",
99                 __FUNCTION__, streamId, streamSetId);
100         return OK;
101     }
102     currentStreamSet.streamInfoMap.add(streamId, streamInfo);
103     currentStreamSet.handoutBufferCountMap.add(streamId, 0);
104     currentStreamSet.attachedBufferCountMap.add(streamId, 0);
105     mStreamMap.add(streamId, stream);
106 
107     // The max allowed buffer count should be the max of buffer count of each stream inside a stream
108     // set.
109     if (streamInfo.totalBufferCount > currentStreamSet.maxAllowedBufferCount) {
110        currentStreamSet.maxAllowedBufferCount = streamInfo.totalBufferCount;
111     }
112 
113     return OK;
114 }
115 
unregisterStream(int streamId,int streamSetId)116 status_t Camera3BufferManager::unregisterStream(int streamId, int streamSetId) {
117     ATRACE_CALL();
118 
119     Mutex::Autolock l(mLock);
120     ALOGV("%s: unregister stream %d with stream set %d", __FUNCTION__,
121             streamId, streamSetId);
122 
123     if (!checkIfStreamRegisteredLocked(streamId, streamSetId)){
124         ALOGE("%s: stream %d with set id %d wasn't properly registered to this buffer manager!",
125                 __FUNCTION__, streamId, streamSetId);
126         return BAD_VALUE;
127     }
128 
129     // De-list all the buffers associated with this stream first.
130     StreamSet& currentSet = mStreamSetMap.editValueFor(streamSetId);
131     BufferCountMap& handOutBufferCounts = currentSet.handoutBufferCountMap;
132     BufferCountMap& attachedBufferCounts = currentSet.attachedBufferCountMap;
133     InfoMap& infoMap = currentSet.streamInfoMap;
134     handOutBufferCounts.removeItem(streamId);
135     attachedBufferCounts.removeItem(streamId);
136 
137     // Remove the stream info from info map and recalculate the buffer count water mark.
138     infoMap.removeItem(streamId);
139     currentSet.maxAllowedBufferCount = 0;
140     for (size_t i = 0; i < infoMap.size(); i++) {
141         if (infoMap[i].totalBufferCount > currentSet.maxAllowedBufferCount) {
142             currentSet.maxAllowedBufferCount = infoMap[i].totalBufferCount;
143         }
144     }
145     mStreamMap.removeItem(streamId);
146 
147     // Lazy solution: when a stream is unregistered, the streams will be reconfigured, reset
148     // the water mark and let it grow again.
149     currentSet.allocatedBufferWaterMark = 0;
150 
151     // Remove this stream set if all its streams have been removed.
152     if (handOutBufferCounts.size() == 0 && infoMap.size() == 0) {
153         mStreamSetMap.removeItem(streamSetId);
154     }
155 
156     return OK;
157 }
158 
notifyBufferRemoved(int streamId,int streamSetId)159 void Camera3BufferManager::notifyBufferRemoved(int streamId, int streamSetId) {
160     Mutex::Autolock l(mLock);
161     StreamSet &streamSet = mStreamSetMap.editValueFor(streamSetId);
162     size_t& attachedBufferCount =
163             streamSet.attachedBufferCountMap.editValueFor(streamId);
164     attachedBufferCount--;
165 }
166 
checkAndFreeBufferOnOtherStreamsLocked(int streamId,int streamSetId)167 status_t Camera3BufferManager::checkAndFreeBufferOnOtherStreamsLocked(
168         int streamId, int streamSetId) {
169     StreamId firstOtherStreamId = CAMERA3_STREAM_ID_INVALID;
170     StreamSet &streamSet = mStreamSetMap.editValueFor(streamSetId);
171     if (streamSet.streamInfoMap.size() == 1) {
172         ALOGV("StreamSet %d has no other stream available to free", streamSetId);
173         return OK;
174     }
175 
176     bool freeBufferIsAttached = false;
177     for (size_t i = 0; i < streamSet.streamInfoMap.size(); i++) {
178         firstOtherStreamId = streamSet.streamInfoMap[i].streamId;
179         if (firstOtherStreamId != streamId) {
180 
181             size_t otherBufferCount  =
182                     streamSet.handoutBufferCountMap.valueFor(firstOtherStreamId);
183             size_t otherAttachedBufferCount =
184                     streamSet.attachedBufferCountMap.valueFor(firstOtherStreamId);
185             if (otherAttachedBufferCount > otherBufferCount) {
186                 freeBufferIsAttached = true;
187                 break;
188             }
189         }
190         firstOtherStreamId = CAMERA3_STREAM_ID_INVALID;
191     }
192     if (firstOtherStreamId == CAMERA3_STREAM_ID_INVALID || !freeBufferIsAttached) {
193         ALOGV("StreamSet %d has no buffer available to free", streamSetId);
194         return OK;
195     }
196 
197 
198     // This will drop the reference to one free buffer, which will effectively free one
199     // buffer (from the free buffer list) for the inactive streams.
200     size_t totalAllocatedBufferCount = 0;
201     for (size_t i = 0; i < streamSet.attachedBufferCountMap.size(); i++) {
202         totalAllocatedBufferCount += streamSet.attachedBufferCountMap[i];
203     }
204     if (totalAllocatedBufferCount > streamSet.allocatedBufferWaterMark) {
205         ALOGV("Stream %d: Freeing buffer: detach", firstOtherStreamId);
206         sp<Camera3OutputStream> stream =
207                 mStreamMap.valueFor(firstOtherStreamId).promote();
208         if (stream == nullptr) {
209             ALOGE("%s: unable to promote stream %d to detach buffer", __FUNCTION__,
210                     firstOtherStreamId);
211             return INVALID_OPERATION;
212         }
213 
214         // Detach and then drop the buffer.
215         //
216         // Need to unlock because the stream may also be calling
217         // into the buffer manager in parallel to signal buffer
218         // release, or acquire a new buffer.
219         bool bufferFreed = false;
220         {
221             mLock.unlock();
222             sp<GraphicBuffer> buffer;
223             stream->detachBuffer(&buffer, /*fenceFd*/ nullptr);
224             mLock.lock();
225             if (buffer.get() != nullptr) {
226                 bufferFreed = true;
227             }
228         }
229         if (bufferFreed) {
230             size_t& otherAttachedBufferCount =
231                     streamSet.attachedBufferCountMap.editValueFor(firstOtherStreamId);
232             otherAttachedBufferCount--;
233         }
234     }
235 
236     return OK;
237 }
238 
getBufferForStream(int streamId,int streamSetId,sp<GraphicBuffer> * gb,int * fenceFd)239 status_t Camera3BufferManager::getBufferForStream(int streamId, int streamSetId,
240         sp<GraphicBuffer>* gb, int* fenceFd) {
241     ATRACE_CALL();
242 
243     Mutex::Autolock l(mLock);
244     ALOGV("%s: get buffer for stream %d with stream set %d", __FUNCTION__,
245             streamId, streamSetId);
246 
247     if (!checkIfStreamRegisteredLocked(streamId, streamSetId)) {
248         ALOGE("%s: stream %d is not registered with stream set %d yet!!!",
249                 __FUNCTION__, streamId, streamSetId);
250         return BAD_VALUE;
251     }
252 
253     StreamSet &streamSet = mStreamSetMap.editValueFor(streamSetId);
254     BufferCountMap& handOutBufferCounts = streamSet.handoutBufferCountMap;
255     size_t& bufferCount = handOutBufferCounts.editValueFor(streamId);
256     if (bufferCount >= streamSet.maxAllowedBufferCount) {
257         ALOGE("%s: bufferCount (%zu) exceeds the max allowed buffer count (%zu) of this stream set",
258                 __FUNCTION__, bufferCount, streamSet.maxAllowedBufferCount);
259         return INVALID_OPERATION;
260     }
261 
262     BufferCountMap& attachedBufferCounts = streamSet.attachedBufferCountMap;
263     size_t& attachedBufferCount = attachedBufferCounts.editValueFor(streamId);
264     if (attachedBufferCount > bufferCount) {
265         // We've already attached more buffers to this stream than we currently have
266         // outstanding, so have the stream just use an already-attached buffer
267         bufferCount++;
268         return ALREADY_EXISTS;
269     }
270     ALOGV("Stream %d set %d: Get buffer for stream: Allocate new", streamId, streamSetId);
271 
272     if (mGrallocVersion < HARDWARE_DEVICE_API_VERSION(1,0)) {
273         const StreamInfo& info = streamSet.streamInfoMap.valueFor(streamId);
274         GraphicBufferEntry buffer;
275         buffer.fenceFd = -1;
276         buffer.graphicBuffer = new GraphicBuffer(
277                 info.width, info.height, PixelFormat(info.format), info.combinedUsage,
278                 std::string("Camera3BufferManager pid [") +
279                         std::to_string(getpid()) + "]");
280         status_t res = buffer.graphicBuffer->initCheck();
281 
282         ALOGV("%s: allocating a new graphic buffer (%dx%d, format 0x%x) %p with handle %p",
283                 __FUNCTION__, info.width, info.height, info.format,
284                 buffer.graphicBuffer.get(), buffer.graphicBuffer->handle);
285         if (res < 0) {
286             ALOGE("%s: graphic buffer allocation failed: (error %d %s) ",
287                     __FUNCTION__, res, strerror(-res));
288             return res;
289         }
290         ALOGV("%s: allocation done", __FUNCTION__);
291 
292         // Increase the hand-out and attached buffer counts for tracking purposes.
293         bufferCount++;
294         attachedBufferCount++;
295         // Update the water mark to be the max hand-out buffer count + 1. An additional buffer is
296         // added to reduce the chance of buffer allocation during stream steady state, especially
297         // for cases where one stream is active, the other stream may request some buffers randomly.
298         if (bufferCount + 1 > streamSet.allocatedBufferWaterMark) {
299             streamSet.allocatedBufferWaterMark = bufferCount + 1;
300         }
301         *gb = buffer.graphicBuffer;
302         *fenceFd = buffer.fenceFd;
303         ALOGV("%s: get buffer (%p) with handle (%p).",
304                 __FUNCTION__, buffer.graphicBuffer.get(), buffer.graphicBuffer->handle);
305 
306         // Proactively free buffers for other streams if the current number of allocated buffers
307         // exceeds the water mark. This only for Gralloc V1, for V2, this logic can also be handled
308         // in returnBufferForStream() if we want to free buffer more quickly.
309         // TODO: probably should find out all the inactive stream IDs, and free the firstly found
310         // buffers for them.
311         res = checkAndFreeBufferOnOtherStreamsLocked(streamId, streamSetId);
312         if (res != OK) {
313             return res;
314         }
315         // Since we just allocated one new buffer above, try free one more buffer from other streams
316         // to prevent total buffer count from growing
317         res = checkAndFreeBufferOnOtherStreamsLocked(streamId, streamSetId);
318         if (res != OK) {
319             return res;
320         }
321     } else {
322         // TODO: implement this.
323         return BAD_VALUE;
324     }
325 
326     return OK;
327 }
328 
onBufferReleased(int streamId,int streamSetId,bool * shouldFreeBuffer)329 status_t Camera3BufferManager::onBufferReleased(
330         int streamId, int streamSetId, bool* shouldFreeBuffer) {
331     ATRACE_CALL();
332 
333     if (shouldFreeBuffer == nullptr) {
334         ALOGE("%s: shouldFreeBuffer is null", __FUNCTION__);
335         return BAD_VALUE;
336     }
337 
338     Mutex::Autolock l(mLock);
339     ALOGV("Stream %d set %d: Buffer released", streamId, streamSetId);
340     *shouldFreeBuffer = false;
341 
342     if (!checkIfStreamRegisteredLocked(streamId, streamSetId)){
343         ALOGV("%s: signaling buffer release for an already unregistered stream "
344                 "(stream %d with set id %d)", __FUNCTION__, streamId, streamSetId);
345         return OK;
346     }
347 
348     if (mGrallocVersion < HARDWARE_DEVICE_API_VERSION(1,0)) {
349         StreamSet& streamSet = mStreamSetMap.editValueFor(streamSetId);
350         BufferCountMap& handOutBufferCounts = streamSet.handoutBufferCountMap;
351         size_t& bufferCount = handOutBufferCounts.editValueFor(streamId);
352         bufferCount--;
353         ALOGV("%s: Stream %d set %d: Buffer count now %zu", __FUNCTION__, streamId, streamSetId,
354                 bufferCount);
355 
356         size_t totalAllocatedBufferCount = 0;
357         size_t totalHandOutBufferCount = 0;
358         for (size_t i = 0; i < streamSet.attachedBufferCountMap.size(); i++) {
359             totalAllocatedBufferCount += streamSet.attachedBufferCountMap[i];
360             totalHandOutBufferCount += streamSet.handoutBufferCountMap[i];
361         }
362 
363         size_t newWaterMark = totalHandOutBufferCount + BUFFER_WATERMARK_DEC_THRESHOLD;
364         if (totalAllocatedBufferCount > newWaterMark &&
365                     streamSet.allocatedBufferWaterMark > newWaterMark) {
366             // BufferManager got more than enough buffers, so decrease watermark
367             // to trigger more buffers free operation.
368             streamSet.allocatedBufferWaterMark = newWaterMark;
369             ALOGV("%s: Stream %d set %d: watermark--; now %zu",
370                     __FUNCTION__, streamId, streamSetId, streamSet.allocatedBufferWaterMark);
371         }
372 
373         size_t attachedBufferCount = streamSet.attachedBufferCountMap.valueFor(streamId);
374         if (attachedBufferCount <= bufferCount) {
375             ALOGV("%s: stream %d has no buffer available to free.", __FUNCTION__, streamId);
376         }
377 
378         bool freeBufferIsAttached = (attachedBufferCount > bufferCount);
379         if (freeBufferIsAttached &&
380                 totalAllocatedBufferCount > streamSet.allocatedBufferWaterMark &&
381                 attachedBufferCount > bufferCount + BUFFER_FREE_THRESHOLD) {
382             ALOGV("%s: free a buffer from stream %d", __FUNCTION__, streamId);
383             *shouldFreeBuffer = true;
384         }
385     } else {
386         // TODO: implement gralloc V1 support
387         return BAD_VALUE;
388     }
389 
390     return OK;
391 }
392 
onBuffersRemoved(int streamId,int streamSetId,size_t count)393 status_t Camera3BufferManager::onBuffersRemoved(int streamId, int streamSetId, size_t count) {
394     ATRACE_CALL();
395     Mutex::Autolock l(mLock);
396 
397     ALOGV("Stream %d set %d: Buffer removed", streamId, streamSetId);
398 
399     if (!checkIfStreamRegisteredLocked(streamId, streamSetId)){
400         ALOGV("%s: signaling buffer removal for an already unregistered stream "
401                 "(stream %d with set id %d)", __FUNCTION__, streamId, streamSetId);
402         return OK;
403     }
404 
405     if (mGrallocVersion < HARDWARE_DEVICE_API_VERSION(1,0)) {
406         StreamSet& streamSet = mStreamSetMap.editValueFor(streamSetId);
407         BufferCountMap& handOutBufferCounts = streamSet.handoutBufferCountMap;
408         size_t& totalHandoutCount = handOutBufferCounts.editValueFor(streamId);
409         BufferCountMap& attachedBufferCounts = streamSet.attachedBufferCountMap;
410         size_t& totalAttachedCount = attachedBufferCounts.editValueFor(streamId);
411 
412         if (count > totalHandoutCount) {
413             ALOGE("%s: Removed buffer count %zu greater than current handout count %zu",
414                     __FUNCTION__, count, totalHandoutCount);
415             return BAD_VALUE;
416         }
417         if (count > totalAttachedCount) {
418             ALOGE("%s: Removed buffer count %zu greater than current attached count %zu",
419                   __FUNCTION__, count, totalAttachedCount);
420             return BAD_VALUE;
421         }
422 
423         totalHandoutCount -= count;
424         totalAttachedCount -= count;
425         ALOGV("%s: Stream %d set %d: Buffer count now %zu, attached buffer count now %zu",
426                 __FUNCTION__, streamId, streamSetId, totalHandoutCount, totalAttachedCount);
427     } else {
428         // TODO: implement gralloc V1 support
429         return BAD_VALUE;
430     }
431 
432     return OK;
433 }
434 
dump(int fd,const Vector<String16> & args) const435 void Camera3BufferManager::dump(int fd, const Vector<String16>& args) const {
436     Mutex::Autolock l(mLock);
437 
438     (void) args;
439     String8 lines;
440     lines.appendFormat("      Total stream sets: %zu\n", mStreamSetMap.size());
441     for (size_t i = 0; i < mStreamSetMap.size(); i++) {
442         lines.appendFormat("        Stream set %d has below streams:\n", mStreamSetMap.keyAt(i));
443         for (size_t j = 0; j < mStreamSetMap[i].streamInfoMap.size(); j++) {
444             lines.appendFormat("          Stream %d\n", mStreamSetMap[i].streamInfoMap[j].streamId);
445         }
446         lines.appendFormat("          Stream set max allowed buffer count: %zu\n",
447                 mStreamSetMap[i].maxAllowedBufferCount);
448         lines.appendFormat("          Stream set buffer count water mark: %zu\n",
449                 mStreamSetMap[i].allocatedBufferWaterMark);
450         lines.appendFormat("          Handout buffer counts:\n");
451         for (size_t m = 0; m < mStreamSetMap[i].handoutBufferCountMap.size(); m++) {
452             int streamId = mStreamSetMap[i].handoutBufferCountMap.keyAt(m);
453             size_t bufferCount = mStreamSetMap[i].handoutBufferCountMap.valueAt(m);
454             lines.appendFormat("            stream id: %d, buffer count: %zu.\n",
455                     streamId, bufferCount);
456         }
457         lines.appendFormat("          Attached buffer counts:\n");
458         for (size_t m = 0; m < mStreamSetMap[i].attachedBufferCountMap.size(); m++) {
459             int streamId = mStreamSetMap[i].attachedBufferCountMap.keyAt(m);
460             size_t bufferCount = mStreamSetMap[i].attachedBufferCountMap.valueAt(m);
461             lines.appendFormat("            stream id: %d, attached buffer count: %zu.\n",
462                     streamId, bufferCount);
463         }
464     }
465     write(fd, lines.string(), lines.size());
466 }
467 
checkIfStreamRegisteredLocked(int streamId,int streamSetId) const468 bool Camera3BufferManager::checkIfStreamRegisteredLocked(int streamId, int streamSetId) const {
469     ssize_t setIdx = mStreamSetMap.indexOfKey(streamSetId);
470     if (setIdx == NAME_NOT_FOUND) {
471         ALOGV("%s: stream set %d is not registered to stream set map yet!",
472                 __FUNCTION__, streamSetId);
473         return false;
474     }
475 
476     ssize_t streamIdx = mStreamSetMap.valueAt(setIdx).streamInfoMap.indexOfKey(streamId);
477     if (streamIdx == NAME_NOT_FOUND) {
478         ALOGV("%s: stream %d is not registered to stream info map yet!", __FUNCTION__, streamId);
479         return false;
480     }
481 
482     size_t bufferWaterMark = mStreamSetMap[setIdx].maxAllowedBufferCount;
483     if (bufferWaterMark == 0 || bufferWaterMark > kMaxBufferCount) {
484         ALOGW("%s: stream %d with stream set %d is not registered correctly to stream set map,"
485                 " as the water mark (%zu) is wrong!",
486                 __FUNCTION__, streamId, streamSetId, bufferWaterMark);
487         return false;
488     }
489 
490     return true;
491 }
492 
493 } // namespace camera3
494 } // namespace android
495