blob: 80df7dbf0ff4b8850e5fd86c9e8811b46b06e262 [file] [log] [blame]
Shuzhen Wang0129d522016-10-30 22:43:41 -07001/*
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
Mathias Agopian05d19b02017-02-28 16:28:19 -080035#include <cutils/atomic.h>
36
Shuzhen Wang0129d522016-10-30 22:43:41 -070037#include "Camera3StreamSplitter.h"
38
39namespace android {
40
Emilian Peev40ead602017-09-26 15:46:36 +010041status_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) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080044 ATRACE_CALL();
45 if (consumer == nullptr) {
46 SP_LOGE("%s: consumer pointer is NULL", __FUNCTION__);
Shuzhen Wang0129d522016-10-30 22:43:41 -070047 return BAD_VALUE;
48 }
49
50 Mutex::Autolock lock(mMutex);
51 status_t res = OK;
52
53 if (mOutputs.size() > 0 || mConsumer != nullptr) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080054 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());
Shuzhen Wang0129d522016-10-30 22:43:41 -070059 return BAD_VALUE;
60 }
61
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080062 mMaxHalBuffers = halMaxBuffers;
63 mConsumerName = getUniqueConsumerName();
Shuzhen Wang0129d522016-10-30 22:43:41 -070064 // Add output surfaces. This has to be before creating internal buffer queue
65 // in order to get max consumer side buffers.
Emilian Peev40ead602017-09-26 15:46:36 +010066 for (auto &it : surfaces) {
67 if (it.second == nullptr) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080068 SP_LOGE("%s: Fatal: surface is NULL", __FUNCTION__);
Shuzhen Wang758c2152017-01-10 18:26:18 -080069 return BAD_VALUE;
70 }
Emilian Peev40ead602017-09-26 15:46:36 +010071 res = addOutputLocked(it.first, it.second);
Shuzhen Wang758c2152017-01-10 18:26:18 -080072 if (res != OK) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080073 SP_LOGE("%s: Failed to add output surface: %s(%d)",
Shuzhen Wang758c2152017-01-10 18:26:18 -080074 __FUNCTION__, strerror(-res), res);
75 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -070076 }
77 }
78
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080079 // Create BufferQueue for input
Shuzhen Wang0129d522016-10-30 22:43:41 -070080 BufferQueue::createBufferQueue(&mProducer, &mConsumer);
81
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080082 // 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().
Emilian Peevf130ad72018-10-11 11:03:07 +010086 mMaxConsumerBuffers++;
87 mBufferItemConsumer = new BufferItemConsumer(mConsumer, consumerUsage, mMaxConsumerBuffers);
Shuzhen Wang0129d522016-10-30 22:43:41 -070088 if (mBufferItemConsumer == nullptr) {
89 return NO_MEMORY;
90 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080091 mConsumer->setConsumerName(mConsumerName);
Shuzhen Wang0129d522016-10-30 22:43:41 -070092
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080093 *consumer = new Surface(mProducer);
94 if (*consumer == nullptr) {
Shuzhen Wang0129d522016-10-30 22:43:41 -070095 return NO_MEMORY;
96 }
Shuzhen Wang0129d522016-10-30 22:43:41 -070097
Emilian Peev40ead602017-09-26 15:46:36 +010098 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
Shuzhen Wang0129d522016-10-30 22:43:41 -0700105 res = mConsumer->consumerConnect(this, /* controlledByApp */ false);
106
Emilian Peev40ead602017-09-26 15:46:36 +0100107 mWidth = width;
108 mHeight = height;
109 mFormat = format;
110 mProducerUsage = producerUsage;
Emilian Peevf130ad72018-10-11 11:03:07 +0100111 mAcquiredInputBuffers = 0;
Emilian Peev40ead602017-09-26 15:46:36 +0100112
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800113 SP_LOGV("%s: connected", __FUNCTION__);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700114 return res;
115}
116
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800117status_t Camera3StreamSplitter::getOnFrameAvailableResult() {
118 ATRACE_CALL();
119 return mOnFrameAvailableRes.load();
120}
121
Shuzhen Wang0129d522016-10-30 22:43:41 -0700122void Camera3StreamSplitter::disconnect() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800123 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700124 Mutex::Autolock lock(mMutex);
125
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800126 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
Shuzhen Wang0129d522016-10-30 22:43:41 -0700133 for (auto& output : mOutputs) {
Emilian Peev40ead602017-09-26 15:46:36 +0100134 if (output.second != nullptr) {
135 output.second->disconnect(NATIVE_WINDOW_API_CAMERA);
136 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700137 }
138 mOutputs.clear();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800139 mOutputSlots.clear();
Emilian Peev40ead602017-09-26 15:46:36 +0100140 mConsumerBufferCount.clear();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700141
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800142 mConsumer->consumerDisconnect();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700143
144 if (mBuffers.size() > 0) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800145 SP_LOGW("%zu buffers still being tracked", mBuffers.size());
146 mBuffers.clear();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700147 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800148
149 mMaxHalBuffers = 0;
150 mMaxConsumerBuffers = 0;
Emilian Peevf130ad72018-10-11 11:03:07 +0100151 mAcquiredInputBuffers = 0;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800152 SP_LOGV("%s: Disconnected", __FUNCTION__);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700153}
154
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700155Camera3StreamSplitter::Camera3StreamSplitter(bool useHalBufManager) :
156 mUseHalBufManager(useHalBufManager) {}
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800157
Shuzhen Wang0129d522016-10-30 22:43:41 -0700158Camera3StreamSplitter::~Camera3StreamSplitter() {
159 disconnect();
160}
161
Emilian Peev40ead602017-09-26 15:46:36 +0100162status_t Camera3StreamSplitter::addOutput(size_t surfaceId, const sp<Surface>& outputQueue) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800163 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700164 Mutex::Autolock lock(mMutex);
Emilian Peev40ead602017-09-26 15:46:36 +0100165 status_t res = addOutputLocked(surfaceId, outputQueue);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800166
167 if (res != OK) {
168 SP_LOGE("%s: addOutputLocked failed %d", __FUNCTION__, res);
169 return res;
170 }
171
Emilian Peevf130ad72018-10-11 11:03:07 +0100172 if (mMaxConsumerBuffers > mAcquiredInputBuffers) {
173 res = mConsumer->setMaxAcquiredBufferCount(mMaxConsumerBuffers);
174 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800175
176 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700177}
178
Emilian Peev40ead602017-09-26 15:46:36 +0100179status_t Camera3StreamSplitter::addOutputLocked(size_t surfaceId, const sp<Surface>& outputQueue) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800180 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700181 if (outputQueue == nullptr) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800182 SP_LOGE("addOutput: outputQueue must not be NULL");
Shuzhen Wang0129d522016-10-30 22:43:41 -0700183 return BAD_VALUE;
184 }
185
Emilian Peev40ead602017-09-26 15:46:36 +0100186 if (mOutputs[surfaceId] != nullptr) {
187 SP_LOGE("%s: surfaceId: %u already taken!", __FUNCTION__, (unsigned) surfaceId);
188 return BAD_VALUE;
189 }
190
Shuzhen Wang9d5c9362018-08-27 11:39:53 -0700191 status_t res = native_window_set_buffers_dimensions(outputQueue.get(),
Emilian Peev40ead602017-09-26 15:46:36 +0100192 mWidth, mHeight);
193 if (res != NO_ERROR) {
194 SP_LOGE("addOutput: failed to set buffer dimensions (%d)", res);
195 return res;
196 }
Shuzhen Wang9d5c9362018-08-27 11:39:53 -0700197 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 }
Emilian Peev40ead602017-09-26 15:46:36 +0100204
Shuzhen Wang0129d522016-10-30 22:43:41 -0700205 sp<IGraphicBufferProducer> gbp = outputQueue->getIGraphicBufferProducer();
206 // Connect to the buffer producer
Shuzhen Wang0129d522016-10-30 22:43:41 -0700207 sp<OutputListener> listener(new OutputListener(this, gbp));
208 IInterface::asBinder(gbp)->linkToDeath(listener);
Emilian Peev40ead602017-09-26 15:46:36 +0100209 res = outputQueue->connect(NATIVE_WINDOW_API_CAMERA, listener);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800210 if (res != NO_ERROR) {
211 SP_LOGE("addOutput: failed to connect (%d)", res);
212 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700213 }
214
215 // Query consumer side buffer count, and update overall buffer count
216 int maxConsumerBuffers = 0;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800217 res = static_cast<ANativeWindow*>(outputQueue.get())->query(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700218 outputQueue.get(),
219 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxConsumerBuffers);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800220 if (res != OK) {
221 SP_LOGE("%s: Unable to query consumer undequeued buffer count"
Shuzhen Wang0129d522016-10-30 22:43:41 -0700222 " for surface", __FUNCTION__);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800223 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700224 }
225
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800226 SP_LOGV("%s: Consumer wants %d buffers, Producer wants %zu", __FUNCTION__,
227 maxConsumerBuffers, mMaxHalBuffers);
Emilian Peev18e3f372018-05-22 18:55:01 +0100228 // 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;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800233 res = native_window_set_buffer_count(outputQueue.get(),
Shuzhen Wang0129d522016-10-30 22:43:41 -0700234 totalBufferCount);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800235 if (res != OK) {
236 SP_LOGE("%s: Unable to set buffer count for surface %p",
Shuzhen Wang0129d522016-10-30 22:43:41 -0700237 __FUNCTION__, outputQueue.get());
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800238 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700239 }
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.
Emilian Peev050f5dc2017-05-18 14:43:56 +0100243 uint64_t usage = 0;
244 res = native_window_get_consumer_usage(static_cast<ANativeWindow*>(outputQueue.get()), &usage);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700245 if (!(usage & (GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_TEXTURE))) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700246 nsecs_t timeout = mUseHalBufManager ?
247 kHalBufMgrDequeueBufferTimeout : kNormalDequeueBufferTimeout;
248 outputQueue->setDequeueTimeout(timeout);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700249 }
250
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800251 res = gbp->allowAllocation(false);
252 if (res != OK) {
253 SP_LOGE("%s: Failed to turn off allocation for outputQueue", __FUNCTION__);
254 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700255 }
256
257 // Add new entry into mOutputs
Emilian Peev40ead602017-09-26 15:46:36 +0100258 mOutputs[surfaceId] = gbp;
259 mConsumerBufferCount[surfaceId] = maxConsumerBuffers;
Emilian Peevf63f1d92018-11-06 16:33:29 +0000260 if (mConsumerBufferCount[surfaceId] > mMaxHalBuffers) {
261 SP_LOGW("%s: Consumer buffer count %zu larger than max. Hal buffers: %zu", __FUNCTION__,
262 mConsumerBufferCount[surfaceId], mMaxHalBuffers);
263 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800264 mNotifiers[gbp] = listener;
265 mOutputSlots[gbp] = std::make_unique<OutputSlots>(totalBufferCount);
266
267 mMaxConsumerBuffers += maxConsumerBuffers;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700268 return NO_ERROR;
269}
270
Emilian Peev40ead602017-09-26 15:46:36 +0100271status_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
Emilian Peevf130ad72018-10-11 11:03:07 +0100281 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 }
Emilian Peev40ead602017-09-26 15:46:36 +0100287 }
288
289 return res;
290}
291
292status_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];
Emilian Peev6f823722017-12-07 18:05:49 +0000303 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 }
Emilian Peev40ead602017-09-26 15:46:36 +0100314 }
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;
Emilian Peevf63f1d92018-11-06 16:33:29 +0000335 mMaxConsumerBuffers -= mConsumerBufferCount[surfaceId];
Emilian Peev40ead602017-09-26 15:46:36 +0100336 mConsumerBufferCount[surfaceId] = 0;
337
338 return res;
339}
340
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800341status_t Camera3StreamSplitter::outputBufferLocked(const sp<IGraphicBufferProducer>& output,
Emilian Peev40ead602017-09-26 15:46:36 +0100342 const BufferItem& bufferItem, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800343 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);
Emilian Peev40ead602017-09-26 15:46:36 +0100367 //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 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800372 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();
Emilian Peev40ead602017-09-26 15:46:36 +0100380 decrementBufRefCountLocked(bufferItem.mGraphicBuffer->getId(), surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800381 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) {
Emilian Peev703e4992018-02-27 11:42:09 +0000388 onBufferReplacedLocked(output, surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800389 }
390
391 return res;
392}
393
Shuzhen Wang0129d522016-10-30 22:43:41 -0700394String8 Camera3StreamSplitter::getUniqueConsumerName() {
395 static volatile int32_t counter = 0;
396 return String8::format("Camera3StreamSplitter-%d", android_atomic_inc(&counter));
397}
398
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800399status_t Camera3StreamSplitter::notifyBufferReleased(const sp<GraphicBuffer>& buffer) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700400 ATRACE_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800401
Shuzhen Wang0129d522016-10-30 22:43:41 -0700402 Mutex::Autolock lock(mMutex);
403
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800404 uint64_t bufferId = buffer->getId();
405 std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[bufferId]);
406 mBuffers.erase(bufferId);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700407
Emilian Peev40ead602017-09-26 15:46:36 +0100408 return OK;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800409}
410
411status_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];
Emilian Peev40ead602017-09-26 15:46:36 +0100426 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 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800435 //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) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700443 SP_LOGE("%s: Cannot attachBuffer from GraphicBufferProducer %p: %s (%d)",
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800444 __FUNCTION__, gbp.get(), strerror(-res), res);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700445 // TODO: might need to detach/cleanup the already attached buffers before return?
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800446 return res;
447 }
Emilian Peev21e79db2018-03-16 18:17:57 +0000448 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 }
Emilian Peev40ead602017-09-26 15:46:36 +0100453 //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 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800458 auto& outputSlots = *mOutputSlots[gbp];
Emilian Peev21e79db2018-03-16 18:17:57 +0000459 if (static_cast<size_t> (slot + 1) > outputSlots.size()) {
460 outputSlots.resize(slot + 1);
461 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800462 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.
Emilian Peev40ead602017-09-26 15:46:36 +0100466 decrementBufRefCountLocked(outputSlots[slot]->getId(), surface_id);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800467 }
468 SP_LOGV("%s: Attached buffer %p to slot %d on output %p.",__FUNCTION__, gb.get(),
469 slot, gbp.get());
470 outputSlots[slot] = gb;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700471 }
472
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800473 mBuffers[bufferId] = std::move(tracker);
474
475 return res;
476}
477
478void Camera3StreamSplitter::onFrameAvailable(const BufferItem& /*item*/) {
479 ATRACE_CALL();
480 Mutex::Autolock lock(mMutex);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700481
482 // Acquire and detach the buffer from the input
483 BufferItem bufferItem;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800484 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 }
Emilian Peev40ead602017-09-26 15:46:36 +0100490
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__);
Yin-Chia Yehda208452019-08-26 15:35:57 -0700499 mOnFrameAvailableRes.store(BAD_VALUE);
Emilian Peev40ead602017-09-26 15:46:36 +0100500 return;
501 }
502 bufferId = bufferItem.mGraphicBuffer->getId();
503
504 if (mBuffers.find(bufferId) == mBuffers.end()) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800505 SP_LOGE("%s: Acquired buffer doesn't exist in attached buffer map",
506 __FUNCTION__);
507 mOnFrameAvailableRes.store(INVALID_OPERATION);
508 return;
509 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700510
Emilian Peevf130ad72018-10-11 11:03:07 +0100511 mAcquiredInputBuffers++;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800512 SP_LOGV("acquired buffer %" PRId64 " from input at slot %d",
513 bufferItem.mGraphicBuffer->getId(), bufferItem.mSlot);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700514
Emilian Peev3bdcdff2018-06-25 14:37:29 +0100515 if (bufferItem.mTransformToDisplayInverse) {
516 bufferItem.mTransform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
517 }
518
Shuzhen Wang0129d522016-10-30 22:43:41 -0700519 // Attach and queue the buffer to each of the outputs
Emilian Peev40ead602017-09-26 15:46:36 +0100520 BufferTracker& tracker = *(mBuffers[bufferId]);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700521
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800522 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()) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700525
Emilian Peev40ead602017-09-26 15:46:36 +0100526 if (mOutputs[id] == nullptr) {
527 //Output surface got likely removed by client.
528 continue;
529 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700530
Emilian Peev40ead602017-09-26 15:46:36 +0100531 res = outputBufferLocked(mOutputs[id], bufferItem, id);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800532 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;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700538 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800539 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700540
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800541 mOnFrameAvailableRes.store(res);
542}
543
Yin-Chia Yehda208452019-08-26 15:35:57 -0700544void Camera3StreamSplitter::onFrameReplaced(const BufferItem& item) {
545 ATRACE_CALL();
546 onFrameAvailable(item);
547}
548
Emilian Peev40ead602017-09-26 15:46:36 +0100549void Camera3StreamSplitter::decrementBufRefCountLocked(uint64_t id, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800550 ATRACE_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800551
Emilian Peev40ead602017-09-26 15:46:36 +0100552 if (mBuffers[id] == nullptr) {
553 return;
554 }
555
556 size_t referenceCount = mBuffers[id]->decrementReferenceCountLocked(surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800557 if (referenceCount > 0) {
558 return;
559 }
560
561 // We no longer need to track the buffer now that it is being returned to the
562 // input. Note that this should happen before we unlock the mutex and call
563 // releaseBuffer, to avoid the case where the same bufferId is acquired in
564 // attachBufferToOutputs resulting in a new BufferTracker with same bufferId
565 // overwrites the current one.
566 std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[id]);
567 mBuffers.erase(id);
568
Emilian Peev40ead602017-09-26 15:46:36 +0100569 uint64_t bufferId = tracker_ptr->getBuffer()->getId();
570 int consumerSlot = -1;
571 uint64_t frameNumber;
Emilian Peev6f823722017-12-07 18:05:49 +0000572 auto inputSlot = mInputSlots.begin();
573 for (; inputSlot != mInputSlots.end(); inputSlot++) {
574 if (inputSlot->second.mGraphicBuffer->getId() == bufferId) {
575 consumerSlot = inputSlot->second.mSlot;
576 frameNumber = inputSlot->second.mFrameNumber;
Emilian Peev40ead602017-09-26 15:46:36 +0100577 break;
578 }
579 }
580 if (consumerSlot == -1) {
581 SP_LOGE("%s: Buffer missing inside input slots!", __FUNCTION__);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800582 return;
583 }
584
Emilian Peev6f823722017-12-07 18:05:49 +0000585 auto detachBuffer = mDetachedBuffers.find(bufferId);
586 bool detach = (detachBuffer != mDetachedBuffers.end());
587 if (detach) {
588 mDetachedBuffers.erase(detachBuffer);
589 mInputSlots.erase(inputSlot);
590 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800591 // Temporarily unlock mutex to avoid circular lock:
592 // 1. This function holds splitter lock, calls releaseBuffer which triggers
593 // onBufferReleased in Camera3OutputStream. onBufferReleased waits on the
594 // OutputStream lock
595 // 2. Camera3SharedOutputStream::getBufferLocked calls
596 // attachBufferToOutputs, which holds the stream lock, and waits for the
597 // splitter lock.
598 sp<IGraphicBufferConsumer> consumer(mConsumer);
599 mMutex.unlock();
Emilian Peev40ead602017-09-26 15:46:36 +0100600 int res = NO_ERROR;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800601 if (consumer != nullptr) {
Emilian Peev6f823722017-12-07 18:05:49 +0000602 if (detach) {
603 res = consumer->detachBuffer(consumerSlot);
604 } else {
605 res = consumer->releaseBuffer(consumerSlot, frameNumber,
606 EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, tracker_ptr->getMergedFence());
607 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800608 } else {
609 SP_LOGE("%s: consumer has become null!", __FUNCTION__);
610 }
611 mMutex.lock();
Emilian Peev6f823722017-12-07 18:05:49 +0000612
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800613 if (res != NO_ERROR) {
Emilian Peev6f823722017-12-07 18:05:49 +0000614 if (detach) {
615 SP_LOGE("%s: detachBuffer returns %d", __FUNCTION__, res);
616 } else {
617 SP_LOGE("%s: releaseBuffer returns %d", __FUNCTION__, res);
618 }
Emilian Peevf130ad72018-10-11 11:03:07 +0100619 } else {
620 if (mAcquiredInputBuffers == 0) {
621 ALOGW("%s: Acquired input buffer count already at zero!", __FUNCTION__);
622 } else {
623 mAcquiredInputBuffers--;
624 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700625 }
626}
627
628void Camera3StreamSplitter::onBufferReleasedByOutput(
629 const sp<IGraphicBufferProducer>& from) {
630 ATRACE_CALL();
Emilian Peev703e4992018-02-27 11:42:09 +0000631 sp<Fence> fence;
632
633 int slot = BufferItem::INVALID_BUFFER_SLOT;
634 auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
635 nullptr, nullptr);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700636 Mutex::Autolock lock(mMutex);
Emilian Peev703e4992018-02-27 11:42:09 +0000637 handleOutputDequeueStatusLocked(res, slot);
638 if (res != OK) {
639 return;
640 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700641
Emilian Peev40ead602017-09-26 15:46:36 +0100642 size_t surfaceId = 0;
643 bool found = false;
644 for (const auto& it : mOutputs) {
645 if (it.second == from) {
646 found = true;
647 surfaceId = it.first;
648 break;
649 }
650 }
651 if (!found) {
652 SP_LOGV("%s: output surface not registered anymore!", __FUNCTION__);
653 return;
654 }
655
Emilian Peev703e4992018-02-27 11:42:09 +0000656 returnOutputBufferLocked(fence, from, surfaceId, slot);
Shuzhen Wanga141c5f2017-01-24 14:51:37 -0800657}
658
Emilian Peev703e4992018-02-27 11:42:09 +0000659void Camera3StreamSplitter::onBufferReplacedLocked(
Emilian Peev40ead602017-09-26 15:46:36 +0100660 const sp<IGraphicBufferProducer>& from, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800661 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700662 sp<Fence> fence;
Emilian Peev40ead602017-09-26 15:46:36 +0100663
664 int slot = BufferItem::INVALID_BUFFER_SLOT;
665 auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
666 nullptr, nullptr);
Emilian Peev703e4992018-02-27 11:42:09 +0000667 handleOutputDequeueStatusLocked(res, slot);
668 if (res != OK) {
Shuzhen Wangafa8a912017-03-15 10:51:27 -0700669 return;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700670 }
671
Emilian Peev703e4992018-02-27 11:42:09 +0000672 returnOutputBufferLocked(fence, from, surfaceId, slot);
673}
674
675void Camera3StreamSplitter::returnOutputBufferLocked(const sp<Fence>& fence,
676 const sp<IGraphicBufferProducer>& from, size_t surfaceId, int slot) {
677 sp<GraphicBuffer> buffer;
678
679 if (mOutputSlots[from] == nullptr) {
680 //Output surface got likely removed by client.
681 return;
682 }
683
684 auto outputSlots = *mOutputSlots[from];
685 buffer = outputSlots[slot];
Shuzhen Wang0129d522016-10-30 22:43:41 -0700686 BufferTracker& tracker = *(mBuffers[buffer->getId()]);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700687 // Merge the release fence of the incoming buffer so that the fence we send
688 // back to the input includes all of the outputs' fences
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800689 if (fence != nullptr && fence->isValid()) {
690 tracker.mergeFence(fence);
691 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700692
Emilian Peev6f823722017-12-07 18:05:49 +0000693 auto detachBuffer = mDetachedBuffers.find(buffer->getId());
694 bool detach = (detachBuffer != mDetachedBuffers.end());
695 if (detach) {
Emilian Peev703e4992018-02-27 11:42:09 +0000696 auto res = from->detachBuffer(slot);
Emilian Peev6f823722017-12-07 18:05:49 +0000697 if (res == NO_ERROR) {
698 outputSlots[slot] = nullptr;
699 } else {
700 SP_LOGE("%s: detach buffer from output failed (%d)", __FUNCTION__, res);
701 }
702 }
703
Shuzhen Wang0129d522016-10-30 22:43:41 -0700704 // Check to see if this is the last outstanding reference to this buffer
Emilian Peev40ead602017-09-26 15:46:36 +0100705 decrementBufRefCountLocked(buffer->getId(), surfaceId);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700706}
707
Emilian Peev703e4992018-02-27 11:42:09 +0000708void Camera3StreamSplitter::handleOutputDequeueStatusLocked(status_t res, int slot) {
709 if (res == NO_INIT) {
710 // If we just discovered that this output has been abandoned, note that,
711 // but we can't do anything else, since buffer is invalid
712 onAbandonedLocked();
713 } else if (res == IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
714 SP_LOGE("%s: Producer needs to re-allocate buffer!", __FUNCTION__);
715 SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
716 } else if (res == IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
717 SP_LOGE("%s: All slot->buffer mapping should be released!", __FUNCTION__);
718 SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
719 } else if (res == NO_MEMORY) {
720 SP_LOGE("%s: No free buffers", __FUNCTION__);
721 } else if (res == WOULD_BLOCK) {
722 SP_LOGE("%s: Dequeue call will block", __FUNCTION__);
723 } else if (res != OK || (slot == BufferItem::INVALID_BUFFER_SLOT)) {
724 SP_LOGE("%s: dequeue buffer from output failed (%d)", __FUNCTION__, res);
725 }
726}
727
Shuzhen Wang0129d522016-10-30 22:43:41 -0700728void Camera3StreamSplitter::onAbandonedLocked() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800729 // If this is called from binderDied callback, it means the app process
730 // holding the binder has died. CameraService will be notified of the binder
731 // death, and camera device will be closed, which in turn calls
732 // disconnect().
733 //
734 // If this is called from onBufferReleasedByOutput or onFrameAvailable, one
735 // consumer being abanoned shouldn't impact the other consumer. So we won't
736 // stop the buffer flow.
737 //
738 // In both cases, we don't need to do anything here.
739 SP_LOGV("One of my outputs has abandoned me");
740}
741
742int Camera3StreamSplitter::getSlotForOutputLocked(const sp<IGraphicBufferProducer>& gbp,
743 const sp<GraphicBuffer>& gb) {
744 auto& outputSlots = *mOutputSlots[gbp];
745
746 for (size_t i = 0; i < outputSlots.size(); i++) {
747 if (outputSlots[i] == gb) {
748 return (int)i;
749 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700750 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800751
Emilian Peev40ead602017-09-26 15:46:36 +0100752 SP_LOGV("%s: Cannot find slot for gb %p on output %p", __FUNCTION__, gb.get(),
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800753 gbp.get());
754 return BufferItem::INVALID_BUFFER_SLOT;
755}
756
Shuzhen Wang0129d522016-10-30 22:43:41 -0700757Camera3StreamSplitter::OutputListener::OutputListener(
758 wp<Camera3StreamSplitter> splitter,
759 wp<IGraphicBufferProducer> output)
760 : mSplitter(splitter), mOutput(output) {}
761
762void Camera3StreamSplitter::OutputListener::onBufferReleased() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800763 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700764 sp<Camera3StreamSplitter> splitter = mSplitter.promote();
765 sp<IGraphicBufferProducer> output = mOutput.promote();
766 if (splitter != nullptr && output != nullptr) {
767 splitter->onBufferReleasedByOutput(output);
768 }
769}
770
771void Camera3StreamSplitter::OutputListener::binderDied(const wp<IBinder>& /* who */) {
772 sp<Camera3StreamSplitter> splitter = mSplitter.promote();
773 if (splitter != nullptr) {
774 Mutex::Autolock lock(splitter->mMutex);
775 splitter->onAbandonedLocked();
776 }
777}
778
779Camera3StreamSplitter::BufferTracker::BufferTracker(
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800780 const sp<GraphicBuffer>& buffer, const std::vector<size_t>& requestedSurfaces)
781 : mBuffer(buffer), mMergedFence(Fence::NO_FENCE), mRequestedSurfaces(requestedSurfaces),
782 mReferenceCount(requestedSurfaces.size()) {}
Shuzhen Wang0129d522016-10-30 22:43:41 -0700783
784void Camera3StreamSplitter::BufferTracker::mergeFence(const sp<Fence>& with) {
785 mMergedFence = Fence::merge(String8("Camera3StreamSplitter"), mMergedFence, with);
786}
787
Emilian Peev40ead602017-09-26 15:46:36 +0100788size_t Camera3StreamSplitter::BufferTracker::decrementReferenceCountLocked(size_t surfaceId) {
789 const auto& it = std::find(mRequestedSurfaces.begin(), mRequestedSurfaces.end(), surfaceId);
790 if (it == mRequestedSurfaces.end()) {
791 return mReferenceCount;
792 } else {
793 mRequestedSurfaces.erase(it);
794 }
795
Shuzhen Wang0129d522016-10-30 22:43:41 -0700796 if (mReferenceCount > 0)
797 --mReferenceCount;
798 return mReferenceCount;
799}
800
801} // namespace android