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