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