blob: 13a1567eaa677d9a2373c580d74ea0ef84dbbd5a [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().
Shuzhen Wang0129d522016-10-30 22:43:41 -070086 mBufferItemConsumer = new BufferItemConsumer(mConsumer, consumerUsage,
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -080087 mMaxConsumerBuffers+1);
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;
111
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800112 SP_LOGV("%s: connected", __FUNCTION__);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700113 return res;
114}
115
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800116status_t Camera3StreamSplitter::getOnFrameAvailableResult() {
117 ATRACE_CALL();
118 return mOnFrameAvailableRes.load();
119}
120
Shuzhen Wang0129d522016-10-30 22:43:41 -0700121void Camera3StreamSplitter::disconnect() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800122 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700123 Mutex::Autolock lock(mMutex);
124
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800125 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
Shuzhen Wang0129d522016-10-30 22:43:41 -0700132 for (auto& output : mOutputs) {
Emilian Peev40ead602017-09-26 15:46:36 +0100133 if (output.second != nullptr) {
134 output.second->disconnect(NATIVE_WINDOW_API_CAMERA);
135 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700136 }
137 mOutputs.clear();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800138 mOutputSlots.clear();
Emilian Peev40ead602017-09-26 15:46:36 +0100139 mConsumerBufferCount.clear();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700140
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800141 mConsumer->consumerDisconnect();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700142
143 if (mBuffers.size() > 0) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800144 SP_LOGW("%zu buffers still being tracked", mBuffers.size());
145 mBuffers.clear();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700146 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800147
148 mMaxHalBuffers = 0;
149 mMaxConsumerBuffers = 0;
150 SP_LOGV("%s: Disconnected", __FUNCTION__);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700151}
152
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700153Camera3StreamSplitter::Camera3StreamSplitter(bool useHalBufManager) :
154 mUseHalBufManager(useHalBufManager) {}
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800155
Shuzhen Wang0129d522016-10-30 22:43:41 -0700156Camera3StreamSplitter::~Camera3StreamSplitter() {
157 disconnect();
158}
159
Emilian Peev40ead602017-09-26 15:46:36 +0100160status_t Camera3StreamSplitter::addOutput(size_t surfaceId, const sp<Surface>& outputQueue) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800161 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700162 Mutex::Autolock lock(mMutex);
Emilian Peev40ead602017-09-26 15:46:36 +0100163 status_t res = addOutputLocked(surfaceId, outputQueue);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800164
165 if (res != OK) {
166 SP_LOGE("%s: addOutputLocked failed %d", __FUNCTION__, res);
167 return res;
168 }
169
170 res = mConsumer->setMaxAcquiredBufferCount(mMaxConsumerBuffers+1);
171
172 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700173}
174
Emilian Peev40ead602017-09-26 15:46:36 +0100175status_t Camera3StreamSplitter::addOutputLocked(size_t surfaceId, const sp<Surface>& outputQueue) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800176 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700177 if (outputQueue == nullptr) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800178 SP_LOGE("addOutput: outputQueue must not be NULL");
Shuzhen Wang0129d522016-10-30 22:43:41 -0700179 return BAD_VALUE;
180 }
181
Emilian Peev40ead602017-09-26 15:46:36 +0100182 if (mOutputs[surfaceId] != nullptr) {
183 SP_LOGE("%s: surfaceId: %u already taken!", __FUNCTION__, (unsigned) surfaceId);
184 return BAD_VALUE;
185 }
186
Shuzhen Wang2f074ce2018-08-27 11:39:53 -0700187 status_t res = native_window_set_buffers_dimensions(outputQueue.get(),
Emilian Peev40ead602017-09-26 15:46:36 +0100188 mWidth, mHeight);
189 if (res != NO_ERROR) {
190 SP_LOGE("addOutput: failed to set buffer dimensions (%d)", res);
191 return res;
192 }
Shuzhen Wang2f074ce2018-08-27 11:39:53 -0700193 res = native_window_set_buffers_format(outputQueue.get(),
194 mFormat);
195 if (res != OK) {
196 ALOGE("%s: Unable to configure stream buffer format %#x for surfaceId %zu",
197 __FUNCTION__, mFormat, surfaceId);
198 return res;
199 }
Emilian Peev40ead602017-09-26 15:46:36 +0100200
Shuzhen Wang0129d522016-10-30 22:43:41 -0700201 sp<IGraphicBufferProducer> gbp = outputQueue->getIGraphicBufferProducer();
202 // Connect to the buffer producer
Shuzhen Wang0129d522016-10-30 22:43:41 -0700203 sp<OutputListener> listener(new OutputListener(this, gbp));
204 IInterface::asBinder(gbp)->linkToDeath(listener);
Emilian Peev40ead602017-09-26 15:46:36 +0100205 res = outputQueue->connect(NATIVE_WINDOW_API_CAMERA, listener);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800206 if (res != NO_ERROR) {
207 SP_LOGE("addOutput: failed to connect (%d)", res);
208 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700209 }
210
211 // Query consumer side buffer count, and update overall buffer count
212 int maxConsumerBuffers = 0;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800213 res = static_cast<ANativeWindow*>(outputQueue.get())->query(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700214 outputQueue.get(),
215 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxConsumerBuffers);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800216 if (res != OK) {
217 SP_LOGE("%s: Unable to query consumer undequeued buffer count"
Shuzhen Wang0129d522016-10-30 22:43:41 -0700218 " for surface", __FUNCTION__);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800219 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700220 }
221
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800222 SP_LOGV("%s: Consumer wants %d buffers, Producer wants %zu", __FUNCTION__,
223 maxConsumerBuffers, mMaxHalBuffers);
Emilian Peev18e3f372018-05-22 18:55:01 +0100224 // The output slot count requirement can change depending on the current amount
225 // of outputs and incoming buffer consumption rate. To avoid any issues with
226 // insufficient slots, set their count to the maximum supported. The output
227 // surface buffer allocation is disabled so no real buffers will get allocated.
228 size_t totalBufferCount = BufferQueue::NUM_BUFFER_SLOTS;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800229 res = native_window_set_buffer_count(outputQueue.get(),
Shuzhen Wang0129d522016-10-30 22:43:41 -0700230 totalBufferCount);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800231 if (res != OK) {
232 SP_LOGE("%s: Unable to set buffer count for surface %p",
Shuzhen Wang0129d522016-10-30 22:43:41 -0700233 __FUNCTION__, outputQueue.get());
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800234 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700235 }
236
237 // Set dequeueBuffer/attachBuffer timeout if the consumer is not hw composer or hw texture.
238 // We need skip these cases as timeout will disable the non-blocking (async) mode.
Emilian Peev050f5dc2017-05-18 14:43:56 +0100239 uint64_t usage = 0;
240 res = native_window_get_consumer_usage(static_cast<ANativeWindow*>(outputQueue.get()), &usage);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700241 if (!(usage & (GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_TEXTURE))) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700242 nsecs_t timeout = mUseHalBufManager ?
243 kHalBufMgrDequeueBufferTimeout : kNormalDequeueBufferTimeout;
244 outputQueue->setDequeueTimeout(timeout);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700245 }
246
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800247 res = gbp->allowAllocation(false);
248 if (res != OK) {
249 SP_LOGE("%s: Failed to turn off allocation for outputQueue", __FUNCTION__);
250 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700251 }
252
253 // Add new entry into mOutputs
Emilian Peev40ead602017-09-26 15:46:36 +0100254 mOutputs[surfaceId] = gbp;
255 mConsumerBufferCount[surfaceId] = maxConsumerBuffers;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800256 mNotifiers[gbp] = listener;
257 mOutputSlots[gbp] = std::make_unique<OutputSlots>(totalBufferCount);
258
259 mMaxConsumerBuffers += maxConsumerBuffers;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700260 return NO_ERROR;
261}
262
Emilian Peev40ead602017-09-26 15:46:36 +0100263status_t Camera3StreamSplitter::removeOutput(size_t surfaceId) {
264 ATRACE_CALL();
265 Mutex::Autolock lock(mMutex);
266
267 status_t res = removeOutputLocked(surfaceId);
268 if (res != OK) {
269 SP_LOGE("%s: removeOutputLocked failed %d", __FUNCTION__, res);
270 return res;
271 }
272
273 res = mConsumer->setMaxAcquiredBufferCount(mMaxConsumerBuffers+1);
274 if (res != OK) {
275 SP_LOGE("%s: setMaxAcquiredBufferCount failed %d", __FUNCTION__, res);
276 return res;
277 }
278
279 return res;
280}
281
282status_t Camera3StreamSplitter::removeOutputLocked(size_t surfaceId) {
283 if (mOutputs[surfaceId] == nullptr) {
284 SP_LOGE("%s: output surface is not present!", __FUNCTION__);
285 return BAD_VALUE;
286 }
287
288 sp<IGraphicBufferProducer> gbp = mOutputs[surfaceId];
289 //Search and decrement the ref. count of any buffers that are
290 //still attached to the removed surface.
291 std::vector<uint64_t> pendingBufferIds;
292 auto& outputSlots = *mOutputSlots[gbp];
Emilian Peev6f823722017-12-07 18:05:49 +0000293 for (size_t i = 0; i < outputSlots.size(); i++) {
294 if (outputSlots[i] != nullptr) {
295 pendingBufferIds.push_back(outputSlots[i]->getId());
296 auto rc = gbp->detachBuffer(i);
297 if (rc != NO_ERROR) {
298 //Buffers that fail to detach here will be scheduled for detach in the
299 //input buffer queue and the rest of the registered outputs instead.
300 //This will help ensure that camera stops accessing buffers that still
301 //can get referenced by the disconnected output.
302 mDetachedBuffers.emplace(outputSlots[i]->getId());
303 }
Emilian Peev40ead602017-09-26 15:46:36 +0100304 }
305 }
306 mOutputs[surfaceId] = nullptr;
307 mOutputSlots[gbp] = nullptr;
308 for (const auto &id : pendingBufferIds) {
309 decrementBufRefCountLocked(id, surfaceId);
310 }
311
312 auto res = IInterface::asBinder(gbp)->unlinkToDeath(mNotifiers[gbp]);
313 if (res != OK) {
314 SP_LOGE("%s: Failed to unlink producer death listener: %d ", __FUNCTION__, res);
315 return res;
316 }
317
318 res = gbp->disconnect(NATIVE_WINDOW_API_CAMERA);
319 if (res != OK) {
320 SP_LOGE("%s: Unable disconnect from producer interface: %d ", __FUNCTION__, res);
321 return res;
322 }
323
324 mNotifiers[gbp] = nullptr;
325 if (mConsumerBufferCount[surfaceId] < mMaxHalBuffers) {
326 mMaxConsumerBuffers -= mConsumerBufferCount[surfaceId];
327 } else {
328 SP_LOGE("%s: Cached consumer buffer count mismatch!", __FUNCTION__);
329 }
330 mConsumerBufferCount[surfaceId] = 0;
331
332 return res;
333}
334
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800335status_t Camera3StreamSplitter::outputBufferLocked(const sp<IGraphicBufferProducer>& output,
Emilian Peev40ead602017-09-26 15:46:36 +0100336 const BufferItem& bufferItem, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800337 ATRACE_CALL();
338 status_t res;
339 IGraphicBufferProducer::QueueBufferInput queueInput(
340 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp,
341 bufferItem.mDataSpace, bufferItem.mCrop,
342 static_cast<int32_t>(bufferItem.mScalingMode),
343 bufferItem.mTransform, bufferItem.mFence);
344
345 IGraphicBufferProducer::QueueBufferOutput queueOutput;
346
347 uint64_t bufferId = bufferItem.mGraphicBuffer->getId();
348 const BufferTracker& tracker = *(mBuffers[bufferId]);
349 int slot = getSlotForOutputLocked(output, tracker.getBuffer());
350
351 // In case the output BufferQueue has its own lock, if we hold splitter lock while calling
352 // queueBuffer (which will try to acquire the output lock), the output could be holding its
353 // own lock calling releaseBuffer (which will try to acquire the splitter lock), running into
354 // circular lock situation.
355 mMutex.unlock();
356 res = output->queueBuffer(slot, queueInput, &queueOutput);
357 mMutex.lock();
358
359 SP_LOGV("%s: Queuing buffer to buffer queue %p slot %d returns %d",
360 __FUNCTION__, output.get(), slot, res);
Emilian Peev40ead602017-09-26 15:46:36 +0100361 //During buffer queue 'mMutex' is not held which makes the removal of
362 //"output" possible. Check whether this is the case and return.
363 if (mOutputSlots[output] == nullptr) {
364 return res;
365 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800366 if (res != OK) {
367 if (res != NO_INIT && res != DEAD_OBJECT) {
368 SP_LOGE("Queuing buffer to output failed (%d)", res);
369 }
370 // If we just discovered that this output has been abandoned, note
371 // that, increment the release count so that we still release this
372 // buffer eventually, and move on to the next output
373 onAbandonedLocked();
Emilian Peev40ead602017-09-26 15:46:36 +0100374 decrementBufRefCountLocked(bufferItem.mGraphicBuffer->getId(), surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800375 return res;
376 }
377
378 // If the queued buffer replaces a pending buffer in the async
379 // queue, no onBufferReleased is called by the buffer queue.
380 // Proactively trigger the callback to avoid buffer loss.
381 if (queueOutput.bufferReplaced) {
Emilian Peev703e4992018-02-27 11:42:09 +0000382 onBufferReplacedLocked(output, surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800383 }
384
385 return res;
386}
387
Shuzhen Wang0129d522016-10-30 22:43:41 -0700388String8 Camera3StreamSplitter::getUniqueConsumerName() {
389 static volatile int32_t counter = 0;
390 return String8::format("Camera3StreamSplitter-%d", android_atomic_inc(&counter));
391}
392
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800393status_t Camera3StreamSplitter::notifyBufferReleased(const sp<GraphicBuffer>& buffer) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700394 ATRACE_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800395
Shuzhen Wang0129d522016-10-30 22:43:41 -0700396 Mutex::Autolock lock(mMutex);
397
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800398 uint64_t bufferId = buffer->getId();
399 std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[bufferId]);
400 mBuffers.erase(bufferId);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700401
Emilian Peev40ead602017-09-26 15:46:36 +0100402 return OK;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800403}
404
405status_t Camera3StreamSplitter::attachBufferToOutputs(ANativeWindowBuffer* anb,
406 const std::vector<size_t>& surface_ids) {
407 ATRACE_CALL();
408 status_t res = OK;
409
410 Mutex::Autolock lock(mMutex);
411
412 sp<GraphicBuffer> gb(static_cast<GraphicBuffer*>(anb));
413 uint64_t bufferId = gb->getId();
414
415 // Initialize buffer tracker for this input buffer
416 auto tracker = std::make_unique<BufferTracker>(gb, surface_ids);
417
418 for (auto& surface_id : surface_ids) {
419 sp<IGraphicBufferProducer>& gbp = mOutputs[surface_id];
Emilian Peev40ead602017-09-26 15:46:36 +0100420 if (gbp.get() == nullptr) {
421 //Output surface got likely removed by client.
422 continue;
423 }
424 int slot = getSlotForOutputLocked(gbp, gb);
425 if (slot != BufferItem::INVALID_BUFFER_SLOT) {
426 //Buffer is already attached to this output surface.
427 continue;
428 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800429 //Temporarly Unlock the mutex when trying to attachBuffer to the output
430 //queue, because attachBuffer could block in case of a slow consumer. If
431 //we block while holding the lock, onFrameAvailable and onBufferReleased
432 //will block as well because they need to acquire the same lock.
433 mMutex.unlock();
434 res = gbp->attachBuffer(&slot, gb);
435 mMutex.lock();
436 if (res != OK) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700437 SP_LOGE("%s: Cannot attachBuffer from GraphicBufferProducer %p: %s (%d)",
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800438 __FUNCTION__, gbp.get(), strerror(-res), res);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700439 // TODO: might need to detach/cleanup the already attached buffers before return?
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800440 return res;
441 }
Emilian Peev21e79db2018-03-16 18:17:57 +0000442 if ((slot < 0) || (slot > BufferQueue::NUM_BUFFER_SLOTS)) {
443 SP_LOGE("%s: Slot received %d either bigger than expected maximum %d or negative!",
444 __FUNCTION__, slot, BufferQueue::NUM_BUFFER_SLOTS);
445 return BAD_VALUE;
446 }
Emilian Peev40ead602017-09-26 15:46:36 +0100447 //During buffer attach 'mMutex' is not held which makes the removal of
448 //"gbp" possible. Check whether this is the case and continue.
449 if (mOutputSlots[gbp] == nullptr) {
450 continue;
451 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800452 auto& outputSlots = *mOutputSlots[gbp];
Emilian Peev21e79db2018-03-16 18:17:57 +0000453 if (static_cast<size_t> (slot + 1) > outputSlots.size()) {
454 outputSlots.resize(slot + 1);
455 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800456 if (outputSlots[slot] != nullptr) {
457 // If the buffer is attached to a slot which already contains a buffer,
458 // the previous buffer will be removed from the output queue. Decrement
459 // the reference count accordingly.
Emilian Peev40ead602017-09-26 15:46:36 +0100460 decrementBufRefCountLocked(outputSlots[slot]->getId(), surface_id);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800461 }
462 SP_LOGV("%s: Attached buffer %p to slot %d on output %p.",__FUNCTION__, gb.get(),
463 slot, gbp.get());
464 outputSlots[slot] = gb;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700465 }
466
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800467 mBuffers[bufferId] = std::move(tracker);
468
469 return res;
470}
471
472void Camera3StreamSplitter::onFrameAvailable(const BufferItem& /*item*/) {
473 ATRACE_CALL();
474 Mutex::Autolock lock(mMutex);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700475
476 // Acquire and detach the buffer from the input
477 BufferItem bufferItem;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800478 status_t res = mConsumer->acquireBuffer(&bufferItem, /* presentWhen */ 0);
479 if (res != NO_ERROR) {
480 SP_LOGE("%s: Acquiring buffer from input failed (%d)", __FUNCTION__, res);
481 mOnFrameAvailableRes.store(res);
482 return;
483 }
Emilian Peev40ead602017-09-26 15:46:36 +0100484
485 uint64_t bufferId;
486 if (bufferItem.mGraphicBuffer != nullptr) {
487 mInputSlots[bufferItem.mSlot] = bufferItem;
488 } else if (bufferItem.mAcquireCalled) {
489 bufferItem.mGraphicBuffer = mInputSlots[bufferItem.mSlot].mGraphicBuffer;
490 mInputSlots[bufferItem.mSlot].mFrameNumber = bufferItem.mFrameNumber;
491 } else {
492 SP_LOGE("%s: Invalid input graphic buffer!", __FUNCTION__);
493 res = BAD_VALUE;
494 return;
495 }
496 bufferId = bufferItem.mGraphicBuffer->getId();
497
498 if (mBuffers.find(bufferId) == mBuffers.end()) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800499 SP_LOGE("%s: Acquired buffer doesn't exist in attached buffer map",
500 __FUNCTION__);
501 mOnFrameAvailableRes.store(INVALID_OPERATION);
502 return;
503 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700504
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800505 SP_LOGV("acquired buffer %" PRId64 " from input at slot %d",
506 bufferItem.mGraphicBuffer->getId(), bufferItem.mSlot);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700507
Emilian Peev3bdcdff2018-06-25 14:37:29 +0100508 if (bufferItem.mTransformToDisplayInverse) {
509 bufferItem.mTransform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
510 }
511
Shuzhen Wang0129d522016-10-30 22:43:41 -0700512 // Attach and queue the buffer to each of the outputs
Emilian Peev40ead602017-09-26 15:46:36 +0100513 BufferTracker& tracker = *(mBuffers[bufferId]);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700514
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800515 SP_LOGV("%s: BufferTracker for buffer %" PRId64 ", number of requests %zu",
516 __FUNCTION__, bufferItem.mGraphicBuffer->getId(), tracker.requestedSurfaces().size());
517 for (const auto id : tracker.requestedSurfaces()) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700518
Emilian Peev40ead602017-09-26 15:46:36 +0100519 if (mOutputs[id] == nullptr) {
520 //Output surface got likely removed by client.
521 continue;
522 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700523
Emilian Peev40ead602017-09-26 15:46:36 +0100524 res = outputBufferLocked(mOutputs[id], bufferItem, id);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800525 if (res != OK) {
526 SP_LOGE("%s: outputBufferLocked failed %d", __FUNCTION__, res);
527 mOnFrameAvailableRes.store(res);
528 // If we fail to send buffer to certain output, keep sending to
529 // other outputs.
530 continue;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700531 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800532 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700533
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800534 mOnFrameAvailableRes.store(res);
535}
536
Emilian Peev40ead602017-09-26 15:46:36 +0100537void Camera3StreamSplitter::decrementBufRefCountLocked(uint64_t id, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800538 ATRACE_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800539
Emilian Peev40ead602017-09-26 15:46:36 +0100540 if (mBuffers[id] == nullptr) {
541 return;
542 }
543
544 size_t referenceCount = mBuffers[id]->decrementReferenceCountLocked(surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800545 if (referenceCount > 0) {
546 return;
547 }
548
549 // We no longer need to track the buffer now that it is being returned to the
550 // input. Note that this should happen before we unlock the mutex and call
551 // releaseBuffer, to avoid the case where the same bufferId is acquired in
552 // attachBufferToOutputs resulting in a new BufferTracker with same bufferId
553 // overwrites the current one.
554 std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[id]);
555 mBuffers.erase(id);
556
Emilian Peev40ead602017-09-26 15:46:36 +0100557 uint64_t bufferId = tracker_ptr->getBuffer()->getId();
558 int consumerSlot = -1;
559 uint64_t frameNumber;
Emilian Peev6f823722017-12-07 18:05:49 +0000560 auto inputSlot = mInputSlots.begin();
561 for (; inputSlot != mInputSlots.end(); inputSlot++) {
562 if (inputSlot->second.mGraphicBuffer->getId() == bufferId) {
563 consumerSlot = inputSlot->second.mSlot;
564 frameNumber = inputSlot->second.mFrameNumber;
Emilian Peev40ead602017-09-26 15:46:36 +0100565 break;
566 }
567 }
568 if (consumerSlot == -1) {
569 SP_LOGE("%s: Buffer missing inside input slots!", __FUNCTION__);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800570 return;
571 }
572
Emilian Peev6f823722017-12-07 18:05:49 +0000573 auto detachBuffer = mDetachedBuffers.find(bufferId);
574 bool detach = (detachBuffer != mDetachedBuffers.end());
575 if (detach) {
576 mDetachedBuffers.erase(detachBuffer);
577 mInputSlots.erase(inputSlot);
578 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800579 // Temporarily unlock mutex to avoid circular lock:
580 // 1. This function holds splitter lock, calls releaseBuffer which triggers
581 // onBufferReleased in Camera3OutputStream. onBufferReleased waits on the
582 // OutputStream lock
583 // 2. Camera3SharedOutputStream::getBufferLocked calls
584 // attachBufferToOutputs, which holds the stream lock, and waits for the
585 // splitter lock.
586 sp<IGraphicBufferConsumer> consumer(mConsumer);
587 mMutex.unlock();
Emilian Peev40ead602017-09-26 15:46:36 +0100588 int res = NO_ERROR;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800589 if (consumer != nullptr) {
Emilian Peev6f823722017-12-07 18:05:49 +0000590 if (detach) {
591 res = consumer->detachBuffer(consumerSlot);
592 } else {
593 res = consumer->releaseBuffer(consumerSlot, frameNumber,
594 EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, tracker_ptr->getMergedFence());
595 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800596 } else {
597 SP_LOGE("%s: consumer has become null!", __FUNCTION__);
598 }
599 mMutex.lock();
Emilian Peev6f823722017-12-07 18:05:49 +0000600
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800601 if (res != NO_ERROR) {
Emilian Peev6f823722017-12-07 18:05:49 +0000602 if (detach) {
603 SP_LOGE("%s: detachBuffer returns %d", __FUNCTION__, res);
604 } else {
605 SP_LOGE("%s: releaseBuffer returns %d", __FUNCTION__, res);
606 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700607 }
608}
609
610void Camera3StreamSplitter::onBufferReleasedByOutput(
611 const sp<IGraphicBufferProducer>& from) {
612 ATRACE_CALL();
Emilian Peev703e4992018-02-27 11:42:09 +0000613 sp<Fence> fence;
614
615 int slot = BufferItem::INVALID_BUFFER_SLOT;
616 auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
617 nullptr, nullptr);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700618 Mutex::Autolock lock(mMutex);
Emilian Peev703e4992018-02-27 11:42:09 +0000619 handleOutputDequeueStatusLocked(res, slot);
620 if (res != OK) {
621 return;
622 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700623
Emilian Peev40ead602017-09-26 15:46:36 +0100624 size_t surfaceId = 0;
625 bool found = false;
626 for (const auto& it : mOutputs) {
627 if (it.second == from) {
628 found = true;
629 surfaceId = it.first;
630 break;
631 }
632 }
633 if (!found) {
634 SP_LOGV("%s: output surface not registered anymore!", __FUNCTION__);
635 return;
636 }
637
Emilian Peev703e4992018-02-27 11:42:09 +0000638 returnOutputBufferLocked(fence, from, surfaceId, slot);
Shuzhen Wanga141c5f2017-01-24 14:51:37 -0800639}
640
Emilian Peev703e4992018-02-27 11:42:09 +0000641void Camera3StreamSplitter::onBufferReplacedLocked(
Emilian Peev40ead602017-09-26 15:46:36 +0100642 const sp<IGraphicBufferProducer>& from, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800643 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700644 sp<Fence> fence;
Emilian Peev40ead602017-09-26 15:46:36 +0100645
646 int slot = BufferItem::INVALID_BUFFER_SLOT;
647 auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
648 nullptr, nullptr);
Emilian Peev703e4992018-02-27 11:42:09 +0000649 handleOutputDequeueStatusLocked(res, slot);
650 if (res != OK) {
Shuzhen Wangafa8a912017-03-15 10:51:27 -0700651 return;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700652 }
653
Emilian Peev703e4992018-02-27 11:42:09 +0000654 returnOutputBufferLocked(fence, from, surfaceId, slot);
655}
656
657void Camera3StreamSplitter::returnOutputBufferLocked(const sp<Fence>& fence,
658 const sp<IGraphicBufferProducer>& from, size_t surfaceId, int slot) {
659 sp<GraphicBuffer> buffer;
660
661 if (mOutputSlots[from] == nullptr) {
662 //Output surface got likely removed by client.
663 return;
664 }
665
666 auto outputSlots = *mOutputSlots[from];
667 buffer = outputSlots[slot];
Shuzhen Wang0129d522016-10-30 22:43:41 -0700668 BufferTracker& tracker = *(mBuffers[buffer->getId()]);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700669 // Merge the release fence of the incoming buffer so that the fence we send
670 // back to the input includes all of the outputs' fences
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800671 if (fence != nullptr && fence->isValid()) {
672 tracker.mergeFence(fence);
673 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700674
Emilian Peev6f823722017-12-07 18:05:49 +0000675 auto detachBuffer = mDetachedBuffers.find(buffer->getId());
676 bool detach = (detachBuffer != mDetachedBuffers.end());
677 if (detach) {
Emilian Peev703e4992018-02-27 11:42:09 +0000678 auto res = from->detachBuffer(slot);
Emilian Peev6f823722017-12-07 18:05:49 +0000679 if (res == NO_ERROR) {
680 outputSlots[slot] = nullptr;
681 } else {
682 SP_LOGE("%s: detach buffer from output failed (%d)", __FUNCTION__, res);
683 }
684 }
685
Shuzhen Wang0129d522016-10-30 22:43:41 -0700686 // Check to see if this is the last outstanding reference to this buffer
Emilian Peev40ead602017-09-26 15:46:36 +0100687 decrementBufRefCountLocked(buffer->getId(), surfaceId);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700688}
689
Emilian Peev703e4992018-02-27 11:42:09 +0000690void Camera3StreamSplitter::handleOutputDequeueStatusLocked(status_t res, int slot) {
691 if (res == NO_INIT) {
692 // If we just discovered that this output has been abandoned, note that,
693 // but we can't do anything else, since buffer is invalid
694 onAbandonedLocked();
695 } else if (res == IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
696 SP_LOGE("%s: Producer needs to re-allocate buffer!", __FUNCTION__);
697 SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
698 } else if (res == IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
699 SP_LOGE("%s: All slot->buffer mapping should be released!", __FUNCTION__);
700 SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
701 } else if (res == NO_MEMORY) {
702 SP_LOGE("%s: No free buffers", __FUNCTION__);
703 } else if (res == WOULD_BLOCK) {
704 SP_LOGE("%s: Dequeue call will block", __FUNCTION__);
705 } else if (res != OK || (slot == BufferItem::INVALID_BUFFER_SLOT)) {
706 SP_LOGE("%s: dequeue buffer from output failed (%d)", __FUNCTION__, res);
707 }
708}
709
Shuzhen Wang0129d522016-10-30 22:43:41 -0700710void Camera3StreamSplitter::onAbandonedLocked() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800711 // If this is called from binderDied callback, it means the app process
712 // holding the binder has died. CameraService will be notified of the binder
713 // death, and camera device will be closed, which in turn calls
714 // disconnect().
715 //
716 // If this is called from onBufferReleasedByOutput or onFrameAvailable, one
717 // consumer being abanoned shouldn't impact the other consumer. So we won't
718 // stop the buffer flow.
719 //
720 // In both cases, we don't need to do anything here.
721 SP_LOGV("One of my outputs has abandoned me");
722}
723
724int Camera3StreamSplitter::getSlotForOutputLocked(const sp<IGraphicBufferProducer>& gbp,
725 const sp<GraphicBuffer>& gb) {
726 auto& outputSlots = *mOutputSlots[gbp];
727
728 for (size_t i = 0; i < outputSlots.size(); i++) {
729 if (outputSlots[i] == gb) {
730 return (int)i;
731 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700732 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800733
Emilian Peev40ead602017-09-26 15:46:36 +0100734 SP_LOGV("%s: Cannot find slot for gb %p on output %p", __FUNCTION__, gb.get(),
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800735 gbp.get());
736 return BufferItem::INVALID_BUFFER_SLOT;
737}
738
Shuzhen Wang0129d522016-10-30 22:43:41 -0700739Camera3StreamSplitter::OutputListener::OutputListener(
740 wp<Camera3StreamSplitter> splitter,
741 wp<IGraphicBufferProducer> output)
742 : mSplitter(splitter), mOutput(output) {}
743
744void Camera3StreamSplitter::OutputListener::onBufferReleased() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800745 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700746 sp<Camera3StreamSplitter> splitter = mSplitter.promote();
747 sp<IGraphicBufferProducer> output = mOutput.promote();
748 if (splitter != nullptr && output != nullptr) {
749 splitter->onBufferReleasedByOutput(output);
750 }
751}
752
753void Camera3StreamSplitter::OutputListener::binderDied(const wp<IBinder>& /* who */) {
754 sp<Camera3StreamSplitter> splitter = mSplitter.promote();
755 if (splitter != nullptr) {
756 Mutex::Autolock lock(splitter->mMutex);
757 splitter->onAbandonedLocked();
758 }
759}
760
761Camera3StreamSplitter::BufferTracker::BufferTracker(
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800762 const sp<GraphicBuffer>& buffer, const std::vector<size_t>& requestedSurfaces)
763 : mBuffer(buffer), mMergedFence(Fence::NO_FENCE), mRequestedSurfaces(requestedSurfaces),
764 mReferenceCount(requestedSurfaces.size()) {}
Shuzhen Wang0129d522016-10-30 22:43:41 -0700765
766void Camera3StreamSplitter::BufferTracker::mergeFence(const sp<Fence>& with) {
767 mMergedFence = Fence::merge(String8("Camera3StreamSplitter"), mMergedFence, with);
768}
769
Emilian Peev40ead602017-09-26 15:46:36 +0100770size_t Camera3StreamSplitter::BufferTracker::decrementReferenceCountLocked(size_t surfaceId) {
771 const auto& it = std::find(mRequestedSurfaces.begin(), mRequestedSurfaces.end(), surfaceId);
772 if (it == mRequestedSurfaces.end()) {
773 return mReferenceCount;
774 } else {
775 mRequestedSurfaces.erase(it);
776 }
777
Shuzhen Wang0129d522016-10-30 22:43:41 -0700778 if (mReferenceCount > 0)
779 --mReferenceCount;
780 return mReferenceCount;
781}
782
783} // namespace android