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