• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014,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 #include <inttypes.h>
18 
19 #define LOG_TAG "Camera3StreamSplitter"
20 #define ATRACE_TAG ATRACE_TAG_CAMERA
21 //#define LOG_NDEBUG 0
22 
23 #include <gui/BufferItem.h>
24 #include <gui/IGraphicBufferConsumer.h>
25 #include <gui/IGraphicBufferProducer.h>
26 #include <gui/BufferQueue.h>
27 #include <gui/Surface.h>
28 
29 #include <ui/GraphicBuffer.h>
30 
31 #include <binder/ProcessState.h>
32 
33 #include <utils/Trace.h>
34 
35 #include <cutils/atomic.h>
36 
37 #include "Camera3Stream.h"
38 
39 #include "Camera3StreamSplitter.h"
40 
41 namespace android {
42 
connect(const std::unordered_map<size_t,sp<Surface>> & surfaces,uint64_t consumerUsage,uint64_t producerUsage,size_t halMaxBuffers,uint32_t width,uint32_t height,android::PixelFormat format,sp<Surface> * consumer,int64_t dynamicRangeProfile)43 status_t Camera3StreamSplitter::connect(const std::unordered_map<size_t, sp<Surface>> &surfaces,
44         uint64_t consumerUsage, uint64_t producerUsage, size_t halMaxBuffers, uint32_t width,
45         uint32_t height, android::PixelFormat format, sp<Surface>* consumer,
46         int64_t dynamicRangeProfile) {
47     ATRACE_CALL();
48     if (consumer == nullptr) {
49         SP_LOGE("%s: consumer pointer is NULL", __FUNCTION__);
50         return BAD_VALUE;
51     }
52 
53     Mutex::Autolock lock(mMutex);
54     status_t res = OK;
55 
56     if (mOutputs.size() > 0 || mConsumer != nullptr) {
57         SP_LOGE("%s: already connected", __FUNCTION__);
58         return BAD_VALUE;
59     }
60     if (mBuffers.size() > 0) {
61         SP_LOGE("%s: still has %zu pending buffers", __FUNCTION__, mBuffers.size());
62         return BAD_VALUE;
63     }
64 
65     mMaxHalBuffers = halMaxBuffers;
66     mConsumerName = getUniqueConsumerName();
67     mDynamicRangeProfile = dynamicRangeProfile;
68     // Add output surfaces. This has to be before creating internal buffer queue
69     // in order to get max consumer side buffers.
70     for (auto &it : surfaces) {
71         if (it.second == nullptr) {
72             SP_LOGE("%s: Fatal: surface is NULL", __FUNCTION__);
73             return BAD_VALUE;
74         }
75         res = addOutputLocked(it.first, it.second);
76         if (res != OK) {
77             SP_LOGE("%s: Failed to add output surface: %s(%d)",
78                     __FUNCTION__, strerror(-res), res);
79             return res;
80         }
81     }
82 
83     // Create BufferQueue for input
84     BufferQueue::createBufferQueue(&mProducer, &mConsumer);
85 
86     // Allocate 1 extra buffer to handle the case where all buffers are detached
87     // from input, and attached to the outputs. In this case, the input queue's
88     // dequeueBuffer can still allocate 1 extra buffer before being blocked by
89     // the output's attachBuffer().
90     mMaxConsumerBuffers++;
91     mBufferItemConsumer = new BufferItemConsumer(mConsumer, consumerUsage, mMaxConsumerBuffers);
92     if (mBufferItemConsumer == nullptr) {
93         return NO_MEMORY;
94     }
95     mConsumer->setConsumerName(mConsumerName);
96 
97     *consumer = new Surface(mProducer);
98     if (*consumer == nullptr) {
99         return NO_MEMORY;
100     }
101 
102     res = mProducer->setAsyncMode(true);
103     if (res != OK) {
104         SP_LOGE("%s: Failed to enable input queue async mode: %s(%d)", __FUNCTION__,
105                 strerror(-res), res);
106         return res;
107     }
108 
109     res = mConsumer->consumerConnect(this, /* controlledByApp */ false);
110 
111     mWidth = width;
112     mHeight = height;
113     mFormat = format;
114     mProducerUsage = producerUsage;
115     mAcquiredInputBuffers = 0;
116 
117     SP_LOGV("%s: connected", __FUNCTION__);
118     return res;
119 }
120 
getOnFrameAvailableResult()121 status_t Camera3StreamSplitter::getOnFrameAvailableResult() {
122     ATRACE_CALL();
123     return mOnFrameAvailableRes.load();
124 }
125 
disconnect()126 void Camera3StreamSplitter::disconnect() {
127     ATRACE_CALL();
128     Mutex::Autolock lock(mMutex);
129 
130     for (auto& notifier : mNotifiers) {
131         sp<IGraphicBufferProducer> producer = notifier.first;
132         sp<OutputListener> listener = notifier.second;
133         IInterface::asBinder(producer)->unlinkToDeath(listener);
134     }
135     mNotifiers.clear();
136 
137     for (auto& output : mOutputs) {
138         if (output.second != nullptr) {
139             output.second->disconnect(NATIVE_WINDOW_API_CAMERA);
140         }
141     }
142     mOutputs.clear();
143     mOutputSurfaces.clear();
144     mOutputSlots.clear();
145     mConsumerBufferCount.clear();
146 
147     if (mConsumer.get() != nullptr) {
148         mConsumer->consumerDisconnect();
149     }
150 
151     if (mBuffers.size() > 0) {
152         SP_LOGW("%zu buffers still being tracked", mBuffers.size());
153         mBuffers.clear();
154     }
155 
156     mMaxHalBuffers = 0;
157     mMaxConsumerBuffers = 0;
158     mAcquiredInputBuffers = 0;
159     SP_LOGV("%s: Disconnected", __FUNCTION__);
160 }
161 
Camera3StreamSplitter(bool useHalBufManager)162 Camera3StreamSplitter::Camera3StreamSplitter(bool useHalBufManager) :
163         mUseHalBufManager(useHalBufManager) {}
164 
~Camera3StreamSplitter()165 Camera3StreamSplitter::~Camera3StreamSplitter() {
166     disconnect();
167 }
168 
addOutput(size_t surfaceId,const sp<Surface> & outputQueue)169 status_t Camera3StreamSplitter::addOutput(size_t surfaceId, const sp<Surface>& outputQueue) {
170     ATRACE_CALL();
171     Mutex::Autolock lock(mMutex);
172     status_t res = addOutputLocked(surfaceId, outputQueue);
173 
174     if (res != OK) {
175         SP_LOGE("%s: addOutputLocked failed %d", __FUNCTION__, res);
176         return res;
177     }
178 
179     if (mMaxConsumerBuffers > mAcquiredInputBuffers) {
180         res = mConsumer->setMaxAcquiredBufferCount(mMaxConsumerBuffers);
181     }
182 
183     return res;
184 }
185 
addOutputLocked(size_t surfaceId,const sp<Surface> & outputQueue)186 status_t Camera3StreamSplitter::addOutputLocked(size_t surfaceId, const sp<Surface>& outputQueue) {
187     ATRACE_CALL();
188     if (outputQueue == nullptr) {
189         SP_LOGE("addOutput: outputQueue must not be NULL");
190         return BAD_VALUE;
191     }
192 
193     if (mOutputs[surfaceId] != nullptr) {
194         SP_LOGE("%s: surfaceId: %u already taken!", __FUNCTION__, (unsigned) surfaceId);
195         return BAD_VALUE;
196     }
197 
198     status_t res = native_window_set_buffers_dimensions(outputQueue.get(),
199             mWidth, mHeight);
200     if (res != NO_ERROR) {
201         SP_LOGE("addOutput: failed to set buffer dimensions (%d)", res);
202         return res;
203     }
204     res = native_window_set_buffers_format(outputQueue.get(),
205             mFormat);
206     if (res != OK) {
207         ALOGE("%s: Unable to configure stream buffer format %#x for surfaceId %zu",
208                 __FUNCTION__, mFormat, surfaceId);
209         return res;
210     }
211 
212     sp<IGraphicBufferProducer> gbp = outputQueue->getIGraphicBufferProducer();
213     // Connect to the buffer producer
214     sp<OutputListener> listener(new OutputListener(this, gbp));
215     IInterface::asBinder(gbp)->linkToDeath(listener);
216     res = outputQueue->connect(NATIVE_WINDOW_API_CAMERA, listener);
217     if (res != NO_ERROR) {
218         SP_LOGE("addOutput: failed to connect (%d)", res);
219         return res;
220     }
221 
222     // Query consumer side buffer count, and update overall buffer count
223     int maxConsumerBuffers = 0;
224     res = static_cast<ANativeWindow*>(outputQueue.get())->query(
225             outputQueue.get(),
226             NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxConsumerBuffers);
227     if (res != OK) {
228         SP_LOGE("%s: Unable to query consumer undequeued buffer count"
229               " for surface", __FUNCTION__);
230         return res;
231     }
232 
233     SP_LOGV("%s: Consumer wants %d buffers, Producer wants %zu", __FUNCTION__,
234             maxConsumerBuffers, mMaxHalBuffers);
235     // The output slot count requirement can change depending on the current amount
236     // of outputs and incoming buffer consumption rate. To avoid any issues with
237     // insufficient slots, set their count to the maximum supported. The output
238     // surface buffer allocation is disabled so no real buffers will get allocated.
239     size_t totalBufferCount = BufferQueue::NUM_BUFFER_SLOTS;
240     res = native_window_set_buffer_count(outputQueue.get(),
241             totalBufferCount);
242     if (res != OK) {
243         SP_LOGE("%s: Unable to set buffer count for surface %p",
244                 __FUNCTION__, outputQueue.get());
245         return res;
246     }
247 
248     // Set dequeueBuffer/attachBuffer timeout if the consumer is not hw composer or hw texture.
249     // We need skip these cases as timeout will disable the non-blocking (async) mode.
250     uint64_t usage = 0;
251     res = native_window_get_consumer_usage(static_cast<ANativeWindow*>(outputQueue.get()), &usage);
252     if (!(usage & (GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_TEXTURE))) {
253         nsecs_t timeout = mUseHalBufManager ?
254                 kHalBufMgrDequeueBufferTimeout : kNormalDequeueBufferTimeout;
255         outputQueue->setDequeueTimeout(timeout);
256     }
257 
258     res = gbp->allowAllocation(false);
259     if (res != OK) {
260         SP_LOGE("%s: Failed to turn off allocation for outputQueue", __FUNCTION__);
261         return res;
262     }
263 
264     // Add new entry into mOutputs
265     mOutputs[surfaceId] = gbp;
266     mOutputSurfaces[surfaceId] = outputQueue;
267     mConsumerBufferCount[surfaceId] = maxConsumerBuffers;
268     if (mConsumerBufferCount[surfaceId] > mMaxHalBuffers) {
269         SP_LOGW("%s: Consumer buffer count %zu larger than max. Hal buffers: %zu", __FUNCTION__,
270                 mConsumerBufferCount[surfaceId], mMaxHalBuffers);
271     }
272     mNotifiers[gbp] = listener;
273     mOutputSlots[gbp] = std::make_unique<OutputSlots>(totalBufferCount);
274 
275     mMaxConsumerBuffers += maxConsumerBuffers;
276     return NO_ERROR;
277 }
278 
removeOutput(size_t surfaceId)279 status_t Camera3StreamSplitter::removeOutput(size_t surfaceId) {
280     ATRACE_CALL();
281     Mutex::Autolock lock(mMutex);
282 
283     status_t res = removeOutputLocked(surfaceId);
284     if (res != OK) {
285         SP_LOGE("%s: removeOutputLocked failed %d", __FUNCTION__, res);
286         return res;
287     }
288 
289     if (mAcquiredInputBuffers < mMaxConsumerBuffers) {
290         res = mConsumer->setMaxAcquiredBufferCount(mMaxConsumerBuffers);
291         if (res != OK) {
292             SP_LOGE("%s: setMaxAcquiredBufferCount failed %d", __FUNCTION__, res);
293             return res;
294         }
295     }
296 
297     return res;
298 }
299 
removeOutputLocked(size_t surfaceId)300 status_t Camera3StreamSplitter::removeOutputLocked(size_t surfaceId) {
301     if (mOutputs[surfaceId] == nullptr) {
302         SP_LOGE("%s: output surface is not present!", __FUNCTION__);
303         return BAD_VALUE;
304     }
305 
306     sp<IGraphicBufferProducer> gbp = mOutputs[surfaceId];
307     //Search and decrement the ref. count of any buffers that are
308     //still attached to the removed surface.
309     std::vector<uint64_t> pendingBufferIds;
310     auto& outputSlots = *mOutputSlots[gbp];
311     for (size_t i = 0; i < outputSlots.size(); i++) {
312         if (outputSlots[i] != nullptr) {
313             pendingBufferIds.push_back(outputSlots[i]->getId());
314             auto rc = gbp->detachBuffer(i);
315             if (rc != NO_ERROR) {
316                 //Buffers that fail to detach here will be scheduled for detach in the
317                 //input buffer queue and the rest of the registered outputs instead.
318                 //This will help ensure that camera stops accessing buffers that still
319                 //can get referenced by the disconnected output.
320                 mDetachedBuffers.emplace(outputSlots[i]->getId());
321             }
322         }
323     }
324     mOutputs[surfaceId] = nullptr;
325     mOutputSurfaces[surfaceId] = nullptr;
326     mOutputSlots[gbp] = nullptr;
327     for (const auto &id : pendingBufferIds) {
328         decrementBufRefCountLocked(id, surfaceId);
329     }
330 
331     auto res = IInterface::asBinder(gbp)->unlinkToDeath(mNotifiers[gbp]);
332     if (res != OK) {
333         SP_LOGE("%s: Failed to unlink producer death listener: %d ", __FUNCTION__, res);
334         return res;
335     }
336 
337     res = gbp->disconnect(NATIVE_WINDOW_API_CAMERA);
338     if (res != OK) {
339         SP_LOGE("%s: Unable disconnect from producer interface: %d ", __FUNCTION__, res);
340         return res;
341     }
342 
343     mNotifiers[gbp] = nullptr;
344     mMaxConsumerBuffers -= mConsumerBufferCount[surfaceId];
345     mConsumerBufferCount[surfaceId] = 0;
346 
347     return res;
348 }
349 
outputBufferLocked(const sp<IGraphicBufferProducer> & output,const BufferItem & bufferItem,size_t surfaceId)350 status_t Camera3StreamSplitter::outputBufferLocked(const sp<IGraphicBufferProducer>& output,
351         const BufferItem& bufferItem, size_t surfaceId) {
352     ATRACE_CALL();
353     status_t res;
354     IGraphicBufferProducer::QueueBufferInput queueInput(
355             bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp,
356             bufferItem.mDataSpace, bufferItem.mCrop,
357             static_cast<int32_t>(bufferItem.mScalingMode),
358             bufferItem.mTransform, bufferItem.mFence);
359 
360     IGraphicBufferProducer::QueueBufferOutput queueOutput;
361 
362     uint64_t bufferId = bufferItem.mGraphicBuffer->getId();
363     const BufferTracker& tracker = *(mBuffers[bufferId]);
364     int slot = getSlotForOutputLocked(output, tracker.getBuffer());
365 
366     if (mOutputSurfaces[surfaceId] != nullptr) {
367         sp<ANativeWindow> anw = mOutputSurfaces[surfaceId];
368         camera3::Camera3Stream::queueHDRMetadata(
369                 bufferItem.mGraphicBuffer->getNativeBuffer()->handle, anw, mDynamicRangeProfile);
370     } else {
371         SP_LOGE("%s: Invalid surface id: %zu!", __FUNCTION__, surfaceId);
372     }
373 
374     // In case the output BufferQueue has its own lock, if we hold splitter lock while calling
375     // queueBuffer (which will try to acquire the output lock), the output could be holding its
376     // own lock calling releaseBuffer (which  will try to acquire the splitter lock), running into
377     // circular lock situation.
378     mMutex.unlock();
379     res = output->queueBuffer(slot, queueInput, &queueOutput);
380     mMutex.lock();
381 
382     SP_LOGV("%s: Queuing buffer to buffer queue %p slot %d returns %d",
383             __FUNCTION__, output.get(), slot, res);
384     //During buffer queue 'mMutex' is not held which makes the removal of
385     //"output" possible. Check whether this is the case and return.
386     if (mOutputSlots[output] == nullptr) {
387         return res;
388     }
389     if (res != OK) {
390         if (res != NO_INIT && res != DEAD_OBJECT) {
391             SP_LOGE("Queuing buffer to output failed (%d)", res);
392         }
393         // If we just discovered that this output has been abandoned, note
394         // that, increment the release count so that we still release this
395         // buffer eventually, and move on to the next output
396         onAbandonedLocked();
397         decrementBufRefCountLocked(bufferItem.mGraphicBuffer->getId(), surfaceId);
398         return res;
399     }
400 
401     // If the queued buffer replaces a pending buffer in the async
402     // queue, no onBufferReleased is called by the buffer queue.
403     // Proactively trigger the callback to avoid buffer loss.
404     if (queueOutput.bufferReplaced) {
405         onBufferReplacedLocked(output, surfaceId);
406     }
407 
408     return res;
409 }
410 
getUniqueConsumerName()411 String8 Camera3StreamSplitter::getUniqueConsumerName() {
412     static volatile int32_t counter = 0;
413     return String8::format("Camera3StreamSplitter-%d", android_atomic_inc(&counter));
414 }
415 
notifyBufferReleased(const sp<GraphicBuffer> & buffer)416 status_t Camera3StreamSplitter::notifyBufferReleased(const sp<GraphicBuffer>& buffer) {
417     ATRACE_CALL();
418 
419     Mutex::Autolock lock(mMutex);
420 
421     uint64_t bufferId = buffer->getId();
422     std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[bufferId]);
423     mBuffers.erase(bufferId);
424 
425     return OK;
426 }
427 
attachBufferToOutputs(ANativeWindowBuffer * anb,const std::vector<size_t> & surface_ids)428 status_t Camera3StreamSplitter::attachBufferToOutputs(ANativeWindowBuffer* anb,
429         const std::vector<size_t>& surface_ids) {
430     ATRACE_CALL();
431     status_t res = OK;
432 
433     Mutex::Autolock lock(mMutex);
434 
435     sp<GraphicBuffer> gb(static_cast<GraphicBuffer*>(anb));
436     uint64_t bufferId = gb->getId();
437 
438     // Initialize buffer tracker for this input buffer
439     auto tracker = std::make_unique<BufferTracker>(gb, surface_ids);
440 
441     for (auto& surface_id : surface_ids) {
442         sp<IGraphicBufferProducer>& gbp = mOutputs[surface_id];
443         if (gbp.get() == nullptr) {
444             //Output surface got likely removed by client.
445             continue;
446         }
447         int slot = getSlotForOutputLocked(gbp, gb);
448         if (slot != BufferItem::INVALID_BUFFER_SLOT) {
449             //Buffer is already attached to this output surface.
450             continue;
451         }
452         //Temporarly Unlock the mutex when trying to attachBuffer to the output
453         //queue, because attachBuffer could block in case of a slow consumer. If
454         //we block while holding the lock, onFrameAvailable and onBufferReleased
455         //will block as well because they need to acquire the same lock.
456         mMutex.unlock();
457         res = gbp->attachBuffer(&slot, gb);
458         mMutex.lock();
459         if (res != OK) {
460             SP_LOGE("%s: Cannot attachBuffer from GraphicBufferProducer %p: %s (%d)",
461                     __FUNCTION__, gbp.get(), strerror(-res), res);
462             // TODO: might need to detach/cleanup the already attached buffers before return?
463             return res;
464         }
465         if ((slot < 0) || (slot > BufferQueue::NUM_BUFFER_SLOTS)) {
466             SP_LOGE("%s: Slot received %d either bigger than expected maximum %d or negative!",
467                     __FUNCTION__, slot, BufferQueue::NUM_BUFFER_SLOTS);
468             return BAD_VALUE;
469         }
470         //During buffer attach 'mMutex' is not held which makes the removal of
471         //"gbp" possible. Check whether this is the case and continue.
472         if (mOutputSlots[gbp] == nullptr) {
473             continue;
474         }
475         auto& outputSlots = *mOutputSlots[gbp];
476         if (static_cast<size_t> (slot + 1) > outputSlots.size()) {
477             outputSlots.resize(slot + 1);
478         }
479         if (outputSlots[slot] != nullptr) {
480             // If the buffer is attached to a slot which already contains a buffer,
481             // the previous buffer will be removed from the output queue. Decrement
482             // the reference count accordingly.
483             decrementBufRefCountLocked(outputSlots[slot]->getId(), surface_id);
484         }
485         SP_LOGV("%s: Attached buffer %p to slot %d on output %p.",__FUNCTION__, gb.get(),
486                 slot, gbp.get());
487         outputSlots[slot] = gb;
488     }
489 
490     mBuffers[bufferId] = std::move(tracker);
491 
492     return res;
493 }
494 
onFrameAvailable(const BufferItem &)495 void Camera3StreamSplitter::onFrameAvailable(const BufferItem& /*item*/) {
496     ATRACE_CALL();
497     Mutex::Autolock lock(mMutex);
498 
499     // Acquire and detach the buffer from the input
500     BufferItem bufferItem;
501     status_t res = mConsumer->acquireBuffer(&bufferItem, /* presentWhen */ 0);
502     if (res != NO_ERROR) {
503         SP_LOGE("%s: Acquiring buffer from input failed (%d)", __FUNCTION__, res);
504         mOnFrameAvailableRes.store(res);
505         return;
506     }
507 
508     uint64_t bufferId;
509     if (bufferItem.mGraphicBuffer != nullptr) {
510         mInputSlots[bufferItem.mSlot] = bufferItem;
511     } else if (bufferItem.mAcquireCalled) {
512         bufferItem.mGraphicBuffer = mInputSlots[bufferItem.mSlot].mGraphicBuffer;
513         mInputSlots[bufferItem.mSlot].mFrameNumber = bufferItem.mFrameNumber;
514     } else {
515         SP_LOGE("%s: Invalid input graphic buffer!", __FUNCTION__);
516         mOnFrameAvailableRes.store(BAD_VALUE);
517         return;
518     }
519     bufferId = bufferItem.mGraphicBuffer->getId();
520 
521     if (mBuffers.find(bufferId) == mBuffers.end()) {
522         SP_LOGE("%s: Acquired buffer doesn't exist in attached buffer map",
523                 __FUNCTION__);
524         mOnFrameAvailableRes.store(INVALID_OPERATION);
525         return;
526     }
527 
528     mAcquiredInputBuffers++;
529     SP_LOGV("acquired buffer %" PRId64 " from input at slot %d",
530             bufferItem.mGraphicBuffer->getId(), bufferItem.mSlot);
531 
532     if (bufferItem.mTransformToDisplayInverse) {
533         bufferItem.mTransform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
534     }
535 
536     // Attach and queue the buffer to each of the outputs
537     BufferTracker& tracker = *(mBuffers[bufferId]);
538 
539     SP_LOGV("%s: BufferTracker for buffer %" PRId64 ", number of requests %zu",
540            __FUNCTION__, bufferItem.mGraphicBuffer->getId(), tracker.requestedSurfaces().size());
541     for (const auto id : tracker.requestedSurfaces()) {
542 
543         if (mOutputs[id] == nullptr) {
544             //Output surface got likely removed by client.
545             continue;
546         }
547 
548         res = outputBufferLocked(mOutputs[id], bufferItem, id);
549         if (res != OK) {
550             SP_LOGE("%s: outputBufferLocked failed %d", __FUNCTION__, res);
551             mOnFrameAvailableRes.store(res);
552             // If we fail to send buffer to certain output, keep sending to
553             // other outputs.
554             continue;
555         }
556     }
557 
558     mOnFrameAvailableRes.store(res);
559 }
560 
onFrameReplaced(const BufferItem & item)561 void Camera3StreamSplitter::onFrameReplaced(const BufferItem& item) {
562     ATRACE_CALL();
563     onFrameAvailable(item);
564 }
565 
decrementBufRefCountLocked(uint64_t id,size_t surfaceId)566 void Camera3StreamSplitter::decrementBufRefCountLocked(uint64_t id, size_t surfaceId) {
567     ATRACE_CALL();
568 
569     if (mBuffers[id] == nullptr) {
570         return;
571     }
572 
573     size_t referenceCount = mBuffers[id]->decrementReferenceCountLocked(surfaceId);
574     if (referenceCount > 0) {
575         return;
576     }
577 
578     // We no longer need to track the buffer now that it is being returned to the
579     // input. Note that this should happen before we unlock the mutex and call
580     // releaseBuffer, to avoid the case where the same bufferId is acquired in
581     // attachBufferToOutputs resulting in a new BufferTracker with same bufferId
582     // overwrites the current one.
583     std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[id]);
584     mBuffers.erase(id);
585 
586     uint64_t bufferId = tracker_ptr->getBuffer()->getId();
587     int consumerSlot = -1;
588     uint64_t frameNumber;
589     auto inputSlot = mInputSlots.begin();
590     for (; inputSlot != mInputSlots.end(); inputSlot++) {
591         if (inputSlot->second.mGraphicBuffer->getId() == bufferId) {
592             consumerSlot = inputSlot->second.mSlot;
593             frameNumber = inputSlot->second.mFrameNumber;
594             break;
595         }
596     }
597     if (consumerSlot == -1) {
598         SP_LOGE("%s: Buffer missing inside input slots!", __FUNCTION__);
599         return;
600     }
601 
602     auto detachBuffer = mDetachedBuffers.find(bufferId);
603     bool detach = (detachBuffer != mDetachedBuffers.end());
604     if (detach) {
605         mDetachedBuffers.erase(detachBuffer);
606         mInputSlots.erase(inputSlot);
607     }
608     // Temporarily unlock mutex to avoid circular lock:
609     // 1. This function holds splitter lock, calls releaseBuffer which triggers
610     // onBufferReleased in Camera3OutputStream. onBufferReleased waits on the
611     // OutputStream lock
612     // 2. Camera3SharedOutputStream::getBufferLocked calls
613     // attachBufferToOutputs, which holds the stream lock, and waits for the
614     // splitter lock.
615     sp<IGraphicBufferConsumer> consumer(mConsumer);
616     mMutex.unlock();
617     int res = NO_ERROR;
618     if (consumer != nullptr) {
619         if (detach) {
620             res = consumer->detachBuffer(consumerSlot);
621         } else {
622             res = consumer->releaseBuffer(consumerSlot, frameNumber,
623                     EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, tracker_ptr->getMergedFence());
624         }
625     } else {
626         SP_LOGE("%s: consumer has become null!", __FUNCTION__);
627     }
628     mMutex.lock();
629 
630     if (res != NO_ERROR) {
631         if (detach) {
632             SP_LOGE("%s: detachBuffer returns %d", __FUNCTION__, res);
633         } else {
634             SP_LOGE("%s: releaseBuffer returns %d", __FUNCTION__, res);
635         }
636     } else {
637         if (mAcquiredInputBuffers == 0) {
638             ALOGW("%s: Acquired input buffer count already at zero!", __FUNCTION__);
639         } else {
640             mAcquiredInputBuffers--;
641         }
642     }
643 }
644 
onBufferReleasedByOutput(const sp<IGraphicBufferProducer> & from)645 void Camera3StreamSplitter::onBufferReleasedByOutput(
646         const sp<IGraphicBufferProducer>& from) {
647     ATRACE_CALL();
648     sp<Fence> fence;
649 
650     int slot = BufferItem::INVALID_BUFFER_SLOT;
651     auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
652             nullptr, nullptr);
653     Mutex::Autolock lock(mMutex);
654     handleOutputDequeueStatusLocked(res, slot);
655     if (res != OK) {
656         return;
657     }
658 
659     size_t surfaceId = 0;
660     bool found = false;
661     for (const auto& it : mOutputs) {
662         if (it.second == from) {
663             found = true;
664             surfaceId = it.first;
665             break;
666         }
667     }
668     if (!found) {
669         SP_LOGV("%s: output surface not registered anymore!", __FUNCTION__);
670         return;
671     }
672 
673     returnOutputBufferLocked(fence, from, surfaceId, slot);
674 }
675 
onBufferReplacedLocked(const sp<IGraphicBufferProducer> & from,size_t surfaceId)676 void Camera3StreamSplitter::onBufferReplacedLocked(
677         const sp<IGraphicBufferProducer>& from, size_t surfaceId) {
678     ATRACE_CALL();
679     sp<Fence> fence;
680 
681     int slot = BufferItem::INVALID_BUFFER_SLOT;
682     auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
683             nullptr, nullptr);
684     handleOutputDequeueStatusLocked(res, slot);
685     if (res != OK) {
686         return;
687     }
688 
689     returnOutputBufferLocked(fence, from, surfaceId, slot);
690 }
691 
returnOutputBufferLocked(const sp<Fence> & fence,const sp<IGraphicBufferProducer> & from,size_t surfaceId,int slot)692 void Camera3StreamSplitter::returnOutputBufferLocked(const sp<Fence>& fence,
693         const sp<IGraphicBufferProducer>& from, size_t surfaceId, int slot) {
694     sp<GraphicBuffer> buffer;
695 
696     if (mOutputSlots[from] == nullptr) {
697         //Output surface got likely removed by client.
698         return;
699     }
700 
701     auto outputSlots = *mOutputSlots[from];
702     buffer = outputSlots[slot];
703     BufferTracker& tracker = *(mBuffers[buffer->getId()]);
704     // Merge the release fence of the incoming buffer so that the fence we send
705     // back to the input includes all of the outputs' fences
706     if (fence != nullptr && fence->isValid()) {
707         tracker.mergeFence(fence);
708     }
709 
710     auto detachBuffer = mDetachedBuffers.find(buffer->getId());
711     bool detach = (detachBuffer != mDetachedBuffers.end());
712     if (detach) {
713         auto res = from->detachBuffer(slot);
714         if (res == NO_ERROR) {
715             outputSlots[slot] = nullptr;
716         } else {
717             SP_LOGE("%s: detach buffer from output failed (%d)", __FUNCTION__, res);
718         }
719     }
720 
721     // Check to see if this is the last outstanding reference to this buffer
722     decrementBufRefCountLocked(buffer->getId(), surfaceId);
723 }
724 
handleOutputDequeueStatusLocked(status_t res,int slot)725 void Camera3StreamSplitter::handleOutputDequeueStatusLocked(status_t res, int slot) {
726     if (res == NO_INIT) {
727         // If we just discovered that this output has been abandoned, note that,
728         // but we can't do anything else, since buffer is invalid
729         onAbandonedLocked();
730     } else if (res == IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
731         SP_LOGE("%s: Producer needs to re-allocate buffer!", __FUNCTION__);
732         SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
733     } else if (res == IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
734         SP_LOGE("%s: All slot->buffer mapping should be released!", __FUNCTION__);
735         SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
736     } else if (res == NO_MEMORY) {
737         SP_LOGE("%s: No free buffers", __FUNCTION__);
738     } else if (res == WOULD_BLOCK) {
739         SP_LOGE("%s: Dequeue call will block", __FUNCTION__);
740     } else if (res != OK || (slot == BufferItem::INVALID_BUFFER_SLOT)) {
741         SP_LOGE("%s: dequeue buffer from output failed (%d)", __FUNCTION__, res);
742     }
743 }
744 
onAbandonedLocked()745 void Camera3StreamSplitter::onAbandonedLocked() {
746     // If this is called from binderDied callback, it means the app process
747     // holding the binder has died. CameraService will be notified of the binder
748     // death, and camera device will be closed, which in turn calls
749     // disconnect().
750     //
751     // If this is called from onBufferReleasedByOutput or onFrameAvailable, one
752     // consumer being abanoned shouldn't impact the other consumer. So we won't
753     // stop the buffer flow.
754     //
755     // In both cases, we don't need to do anything here.
756     SP_LOGV("One of my outputs has abandoned me");
757 }
758 
getSlotForOutputLocked(const sp<IGraphicBufferProducer> & gbp,const sp<GraphicBuffer> & gb)759 int Camera3StreamSplitter::getSlotForOutputLocked(const sp<IGraphicBufferProducer>& gbp,
760         const sp<GraphicBuffer>& gb) {
761     auto& outputSlots = *mOutputSlots[gbp];
762 
763     for (size_t i = 0; i < outputSlots.size(); i++) {
764         if (outputSlots[i] == gb) {
765             return (int)i;
766         }
767     }
768 
769     SP_LOGV("%s: Cannot find slot for gb %p on output %p", __FUNCTION__, gb.get(),
770             gbp.get());
771     return BufferItem::INVALID_BUFFER_SLOT;
772 }
773 
OutputListener(wp<Camera3StreamSplitter> splitter,wp<IGraphicBufferProducer> output)774 Camera3StreamSplitter::OutputListener::OutputListener(
775         wp<Camera3StreamSplitter> splitter,
776         wp<IGraphicBufferProducer> output)
777       : mSplitter(splitter), mOutput(output) {}
778 
onBufferReleased()779 void Camera3StreamSplitter::OutputListener::onBufferReleased() {
780     ATRACE_CALL();
781     sp<Camera3StreamSplitter> splitter = mSplitter.promote();
782     sp<IGraphicBufferProducer> output = mOutput.promote();
783     if (splitter != nullptr && output != nullptr) {
784         splitter->onBufferReleasedByOutput(output);
785     }
786 }
787 
binderDied(const wp<IBinder> &)788 void Camera3StreamSplitter::OutputListener::binderDied(const wp<IBinder>& /* who */) {
789     sp<Camera3StreamSplitter> splitter = mSplitter.promote();
790     if (splitter != nullptr) {
791         Mutex::Autolock lock(splitter->mMutex);
792         splitter->onAbandonedLocked();
793     }
794 }
795 
BufferTracker(const sp<GraphicBuffer> & buffer,const std::vector<size_t> & requestedSurfaces)796 Camera3StreamSplitter::BufferTracker::BufferTracker(
797         const sp<GraphicBuffer>& buffer, const std::vector<size_t>& requestedSurfaces)
798       : mBuffer(buffer), mMergedFence(Fence::NO_FENCE), mRequestedSurfaces(requestedSurfaces),
799         mReferenceCount(requestedSurfaces.size()) {}
800 
mergeFence(const sp<Fence> & with)801 void Camera3StreamSplitter::BufferTracker::mergeFence(const sp<Fence>& with) {
802     mMergedFence = Fence::merge(String8("Camera3StreamSplitter"), mMergedFence, with);
803 }
804 
decrementReferenceCountLocked(size_t surfaceId)805 size_t Camera3StreamSplitter::BufferTracker::decrementReferenceCountLocked(size_t surfaceId) {
806     const auto& it = std::find(mRequestedSurfaces.begin(), mRequestedSurfaces.end(), surfaceId);
807     if (it == mRequestedSurfaces.end()) {
808         return mReferenceCount;
809     } else {
810         mRequestedSurfaces.erase(it);
811     }
812 
813     if (mReferenceCount > 0)
814         --mReferenceCount;
815     return mReferenceCount;
816 }
817 
818 } // namespace android
819