blob: 8bc208dfa758ad9f9bba0f5f4410053c49c571cc [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
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800153
Shuzhen Wang0129d522016-10-30 22:43:41 -0700154Camera3StreamSplitter::~Camera3StreamSplitter() {
155 disconnect();
156}
157
Emilian Peev40ead602017-09-26 15:46:36 +0100158status_t Camera3StreamSplitter::addOutput(size_t surfaceId, const sp<Surface>& outputQueue) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800159 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700160 Mutex::Autolock lock(mMutex);
Emilian Peev40ead602017-09-26 15:46:36 +0100161 status_t res = addOutputLocked(surfaceId, outputQueue);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800162
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;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700171}
172
Emilian Peev40ead602017-09-26 15:46:36 +0100173status_t Camera3StreamSplitter::addOutputLocked(size_t surfaceId, const sp<Surface>& outputQueue) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800174 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700175 if (outputQueue == nullptr) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800176 SP_LOGE("addOutput: outputQueue must not be NULL");
Shuzhen Wang0129d522016-10-30 22:43:41 -0700177 return BAD_VALUE;
178 }
179
Emilian Peev40ead602017-09-26 15:46:36 +0100180 if (mOutputs[surfaceId] != nullptr) {
181 SP_LOGE("%s: surfaceId: %u already taken!", __FUNCTION__, (unsigned) surfaceId);
182 return BAD_VALUE;
183 }
184
Shuzhen Wang2f074ce2018-08-27 11:39:53 -0700185 status_t res = native_window_set_buffers_dimensions(outputQueue.get(),
Emilian Peev40ead602017-09-26 15:46:36 +0100186 mWidth, mHeight);
187 if (res != NO_ERROR) {
188 SP_LOGE("addOutput: failed to set buffer dimensions (%d)", res);
189 return res;
190 }
Shuzhen Wang2f074ce2018-08-27 11:39:53 -0700191 res = native_window_set_buffers_format(outputQueue.get(),
192 mFormat);
193 if (res != OK) {
194 ALOGE("%s: Unable to configure stream buffer format %#x for surfaceId %zu",
195 __FUNCTION__, mFormat, surfaceId);
196 return res;
197 }
Emilian Peev40ead602017-09-26 15:46:36 +0100198
Shuzhen Wang0129d522016-10-30 22:43:41 -0700199 sp<IGraphicBufferProducer> gbp = outputQueue->getIGraphicBufferProducer();
200 // Connect to the buffer producer
Shuzhen Wang0129d522016-10-30 22:43:41 -0700201 sp<OutputListener> listener(new OutputListener(this, gbp));
202 IInterface::asBinder(gbp)->linkToDeath(listener);
Emilian Peev40ead602017-09-26 15:46:36 +0100203 res = outputQueue->connect(NATIVE_WINDOW_API_CAMERA, listener);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800204 if (res != NO_ERROR) {
205 SP_LOGE("addOutput: failed to connect (%d)", res);
206 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700207 }
208
209 // Query consumer side buffer count, and update overall buffer count
210 int maxConsumerBuffers = 0;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800211 res = static_cast<ANativeWindow*>(outputQueue.get())->query(
Shuzhen Wang0129d522016-10-30 22:43:41 -0700212 outputQueue.get(),
213 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxConsumerBuffers);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800214 if (res != OK) {
215 SP_LOGE("%s: Unable to query consumer undequeued buffer count"
Shuzhen Wang0129d522016-10-30 22:43:41 -0700216 " for surface", __FUNCTION__);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800217 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700218 }
219
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800220 SP_LOGV("%s: Consumer wants %d buffers, Producer wants %zu", __FUNCTION__,
221 maxConsumerBuffers, mMaxHalBuffers);
Emilian Peev18e3f372018-05-22 18:55:01 +0100222 // The output slot count requirement can change depending on the current amount
223 // of outputs and incoming buffer consumption rate. To avoid any issues with
224 // insufficient slots, set their count to the maximum supported. The output
225 // surface buffer allocation is disabled so no real buffers will get allocated.
226 size_t totalBufferCount = BufferQueue::NUM_BUFFER_SLOTS;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800227 res = native_window_set_buffer_count(outputQueue.get(),
Shuzhen Wang0129d522016-10-30 22:43:41 -0700228 totalBufferCount);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800229 if (res != OK) {
230 SP_LOGE("%s: Unable to set buffer count for surface %p",
Shuzhen Wang0129d522016-10-30 22:43:41 -0700231 __FUNCTION__, outputQueue.get());
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800232 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700233 }
234
235 // Set dequeueBuffer/attachBuffer timeout if the consumer is not hw composer or hw texture.
236 // We need skip these cases as timeout will disable the non-blocking (async) mode.
Emilian Peev050f5dc2017-05-18 14:43:56 +0100237 uint64_t usage = 0;
238 res = native_window_get_consumer_usage(static_cast<ANativeWindow*>(outputQueue.get()), &usage);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700239 if (!(usage & (GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_TEXTURE))) {
240 outputQueue->setDequeueTimeout(kDequeueBufferTimeout);
241 }
242
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800243 res = gbp->allowAllocation(false);
244 if (res != OK) {
245 SP_LOGE("%s: Failed to turn off allocation for outputQueue", __FUNCTION__);
246 return res;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700247 }
248
249 // Add new entry into mOutputs
Emilian Peev40ead602017-09-26 15:46:36 +0100250 mOutputs[surfaceId] = gbp;
251 mConsumerBufferCount[surfaceId] = maxConsumerBuffers;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800252 mNotifiers[gbp] = listener;
253 mOutputSlots[gbp] = std::make_unique<OutputSlots>(totalBufferCount);
254
255 mMaxConsumerBuffers += maxConsumerBuffers;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700256 return NO_ERROR;
257}
258
Emilian Peev40ead602017-09-26 15:46:36 +0100259status_t Camera3StreamSplitter::removeOutput(size_t surfaceId) {
260 ATRACE_CALL();
261 Mutex::Autolock lock(mMutex);
262
263 status_t res = removeOutputLocked(surfaceId);
264 if (res != OK) {
265 SP_LOGE("%s: removeOutputLocked failed %d", __FUNCTION__, res);
266 return res;
267 }
268
269 res = mConsumer->setMaxAcquiredBufferCount(mMaxConsumerBuffers+1);
270 if (res != OK) {
271 SP_LOGE("%s: setMaxAcquiredBufferCount failed %d", __FUNCTION__, res);
272 return res;
273 }
274
275 return res;
276}
277
278status_t Camera3StreamSplitter::removeOutputLocked(size_t surfaceId) {
279 if (mOutputs[surfaceId] == nullptr) {
280 SP_LOGE("%s: output surface is not present!", __FUNCTION__);
281 return BAD_VALUE;
282 }
283
284 sp<IGraphicBufferProducer> gbp = mOutputs[surfaceId];
285 //Search and decrement the ref. count of any buffers that are
286 //still attached to the removed surface.
287 std::vector<uint64_t> pendingBufferIds;
288 auto& outputSlots = *mOutputSlots[gbp];
Emilian Peev6f823722017-12-07 18:05:49 +0000289 for (size_t i = 0; i < outputSlots.size(); i++) {
290 if (outputSlots[i] != nullptr) {
291 pendingBufferIds.push_back(outputSlots[i]->getId());
292 auto rc = gbp->detachBuffer(i);
293 if (rc != NO_ERROR) {
294 //Buffers that fail to detach here will be scheduled for detach in the
295 //input buffer queue and the rest of the registered outputs instead.
296 //This will help ensure that camera stops accessing buffers that still
297 //can get referenced by the disconnected output.
298 mDetachedBuffers.emplace(outputSlots[i]->getId());
299 }
Emilian Peev40ead602017-09-26 15:46:36 +0100300 }
301 }
302 mOutputs[surfaceId] = nullptr;
303 mOutputSlots[gbp] = nullptr;
304 for (const auto &id : pendingBufferIds) {
305 decrementBufRefCountLocked(id, surfaceId);
306 }
307
308 auto res = IInterface::asBinder(gbp)->unlinkToDeath(mNotifiers[gbp]);
309 if (res != OK) {
310 SP_LOGE("%s: Failed to unlink producer death listener: %d ", __FUNCTION__, res);
311 return res;
312 }
313
314 res = gbp->disconnect(NATIVE_WINDOW_API_CAMERA);
315 if (res != OK) {
316 SP_LOGE("%s: Unable disconnect from producer interface: %d ", __FUNCTION__, res);
317 return res;
318 }
319
320 mNotifiers[gbp] = nullptr;
321 if (mConsumerBufferCount[surfaceId] < mMaxHalBuffers) {
322 mMaxConsumerBuffers -= mConsumerBufferCount[surfaceId];
323 } else {
324 SP_LOGE("%s: Cached consumer buffer count mismatch!", __FUNCTION__);
325 }
326 mConsumerBufferCount[surfaceId] = 0;
327
328 return res;
329}
330
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800331status_t Camera3StreamSplitter::outputBufferLocked(const sp<IGraphicBufferProducer>& output,
Emilian Peev40ead602017-09-26 15:46:36 +0100332 const BufferItem& bufferItem, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800333 ATRACE_CALL();
334 status_t res;
335 IGraphicBufferProducer::QueueBufferInput queueInput(
336 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp,
337 bufferItem.mDataSpace, bufferItem.mCrop,
338 static_cast<int32_t>(bufferItem.mScalingMode),
339 bufferItem.mTransform, bufferItem.mFence);
340
341 IGraphicBufferProducer::QueueBufferOutput queueOutput;
342
343 uint64_t bufferId = bufferItem.mGraphicBuffer->getId();
344 const BufferTracker& tracker = *(mBuffers[bufferId]);
345 int slot = getSlotForOutputLocked(output, tracker.getBuffer());
346
347 // In case the output BufferQueue has its own lock, if we hold splitter lock while calling
348 // queueBuffer (which will try to acquire the output lock), the output could be holding its
349 // own lock calling releaseBuffer (which will try to acquire the splitter lock), running into
350 // circular lock situation.
351 mMutex.unlock();
352 res = output->queueBuffer(slot, queueInput, &queueOutput);
353 mMutex.lock();
354
355 SP_LOGV("%s: Queuing buffer to buffer queue %p slot %d returns %d",
356 __FUNCTION__, output.get(), slot, res);
Emilian Peev40ead602017-09-26 15:46:36 +0100357 //During buffer queue 'mMutex' is not held which makes the removal of
358 //"output" possible. Check whether this is the case and return.
359 if (mOutputSlots[output] == nullptr) {
360 return res;
361 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800362 if (res != OK) {
363 if (res != NO_INIT && res != DEAD_OBJECT) {
364 SP_LOGE("Queuing buffer to output failed (%d)", res);
365 }
366 // If we just discovered that this output has been abandoned, note
367 // that, increment the release count so that we still release this
368 // buffer eventually, and move on to the next output
369 onAbandonedLocked();
Emilian Peev40ead602017-09-26 15:46:36 +0100370 decrementBufRefCountLocked(bufferItem.mGraphicBuffer->getId(), surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800371 return res;
372 }
373
374 // If the queued buffer replaces a pending buffer in the async
375 // queue, no onBufferReleased is called by the buffer queue.
376 // Proactively trigger the callback to avoid buffer loss.
377 if (queueOutput.bufferReplaced) {
Emilian Peev703e4992018-02-27 11:42:09 +0000378 onBufferReplacedLocked(output, surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800379 }
380
381 return res;
382}
383
Shuzhen Wang0129d522016-10-30 22:43:41 -0700384String8 Camera3StreamSplitter::getUniqueConsumerName() {
385 static volatile int32_t counter = 0;
386 return String8::format("Camera3StreamSplitter-%d", android_atomic_inc(&counter));
387}
388
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800389status_t Camera3StreamSplitter::notifyBufferReleased(const sp<GraphicBuffer>& buffer) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700390 ATRACE_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800391
Shuzhen Wang0129d522016-10-30 22:43:41 -0700392 Mutex::Autolock lock(mMutex);
393
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800394 uint64_t bufferId = buffer->getId();
395 std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[bufferId]);
396 mBuffers.erase(bufferId);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700397
Emilian Peev40ead602017-09-26 15:46:36 +0100398 return OK;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800399}
400
401status_t Camera3StreamSplitter::attachBufferToOutputs(ANativeWindowBuffer* anb,
402 const std::vector<size_t>& surface_ids) {
403 ATRACE_CALL();
404 status_t res = OK;
405
406 Mutex::Autolock lock(mMutex);
407
408 sp<GraphicBuffer> gb(static_cast<GraphicBuffer*>(anb));
409 uint64_t bufferId = gb->getId();
410
411 // Initialize buffer tracker for this input buffer
412 auto tracker = std::make_unique<BufferTracker>(gb, surface_ids);
413
414 for (auto& surface_id : surface_ids) {
415 sp<IGraphicBufferProducer>& gbp = mOutputs[surface_id];
Emilian Peev40ead602017-09-26 15:46:36 +0100416 if (gbp.get() == nullptr) {
417 //Output surface got likely removed by client.
418 continue;
419 }
420 int slot = getSlotForOutputLocked(gbp, gb);
421 if (slot != BufferItem::INVALID_BUFFER_SLOT) {
422 //Buffer is already attached to this output surface.
423 continue;
424 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800425 //Temporarly Unlock the mutex when trying to attachBuffer to the output
426 //queue, because attachBuffer could block in case of a slow consumer. If
427 //we block while holding the lock, onFrameAvailable and onBufferReleased
428 //will block as well because they need to acquire the same lock.
429 mMutex.unlock();
430 res = gbp->attachBuffer(&slot, gb);
431 mMutex.lock();
432 if (res != OK) {
433 SP_LOGE("%s: Cannot acquireBuffer from GraphicBufferProducer %p: %s (%d)",
434 __FUNCTION__, gbp.get(), strerror(-res), res);
435 return res;
436 }
Emilian Peev21e79db2018-03-16 18:17:57 +0000437 if ((slot < 0) || (slot > BufferQueue::NUM_BUFFER_SLOTS)) {
438 SP_LOGE("%s: Slot received %d either bigger than expected maximum %d or negative!",
439 __FUNCTION__, slot, BufferQueue::NUM_BUFFER_SLOTS);
440 return BAD_VALUE;
441 }
Emilian Peev40ead602017-09-26 15:46:36 +0100442 //During buffer attach 'mMutex' is not held which makes the removal of
443 //"gbp" possible. Check whether this is the case and continue.
444 if (mOutputSlots[gbp] == nullptr) {
445 continue;
446 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800447 auto& outputSlots = *mOutputSlots[gbp];
Emilian Peev21e79db2018-03-16 18:17:57 +0000448 if (static_cast<size_t> (slot + 1) > outputSlots.size()) {
449 outputSlots.resize(slot + 1);
450 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800451 if (outputSlots[slot] != nullptr) {
452 // If the buffer is attached to a slot which already contains a buffer,
453 // the previous buffer will be removed from the output queue. Decrement
454 // the reference count accordingly.
Emilian Peev40ead602017-09-26 15:46:36 +0100455 decrementBufRefCountLocked(outputSlots[slot]->getId(), surface_id);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800456 }
457 SP_LOGV("%s: Attached buffer %p to slot %d on output %p.",__FUNCTION__, gb.get(),
458 slot, gbp.get());
459 outputSlots[slot] = gb;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700460 }
461
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800462 mBuffers[bufferId] = std::move(tracker);
463
464 return res;
465}
466
467void Camera3StreamSplitter::onFrameAvailable(const BufferItem& /*item*/) {
468 ATRACE_CALL();
469 Mutex::Autolock lock(mMutex);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700470
471 // Acquire and detach the buffer from the input
472 BufferItem bufferItem;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800473 status_t res = mConsumer->acquireBuffer(&bufferItem, /* presentWhen */ 0);
474 if (res != NO_ERROR) {
475 SP_LOGE("%s: Acquiring buffer from input failed (%d)", __FUNCTION__, res);
476 mOnFrameAvailableRes.store(res);
477 return;
478 }
Emilian Peev40ead602017-09-26 15:46:36 +0100479
480 uint64_t bufferId;
481 if (bufferItem.mGraphicBuffer != nullptr) {
482 mInputSlots[bufferItem.mSlot] = bufferItem;
483 } else if (bufferItem.mAcquireCalled) {
484 bufferItem.mGraphicBuffer = mInputSlots[bufferItem.mSlot].mGraphicBuffer;
485 mInputSlots[bufferItem.mSlot].mFrameNumber = bufferItem.mFrameNumber;
486 } else {
487 SP_LOGE("%s: Invalid input graphic buffer!", __FUNCTION__);
488 res = BAD_VALUE;
489 return;
490 }
491 bufferId = bufferItem.mGraphicBuffer->getId();
492
493 if (mBuffers.find(bufferId) == mBuffers.end()) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800494 SP_LOGE("%s: Acquired buffer doesn't exist in attached buffer map",
495 __FUNCTION__);
496 mOnFrameAvailableRes.store(INVALID_OPERATION);
497 return;
498 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700499
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800500 SP_LOGV("acquired buffer %" PRId64 " from input at slot %d",
501 bufferItem.mGraphicBuffer->getId(), bufferItem.mSlot);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700502
Emilian Peev3bdcdff2018-06-25 14:37:29 +0100503 if (bufferItem.mTransformToDisplayInverse) {
504 bufferItem.mTransform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
505 }
506
Shuzhen Wang0129d522016-10-30 22:43:41 -0700507 // Attach and queue the buffer to each of the outputs
Emilian Peev40ead602017-09-26 15:46:36 +0100508 BufferTracker& tracker = *(mBuffers[bufferId]);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700509
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800510 SP_LOGV("%s: BufferTracker for buffer %" PRId64 ", number of requests %zu",
511 __FUNCTION__, bufferItem.mGraphicBuffer->getId(), tracker.requestedSurfaces().size());
512 for (const auto id : tracker.requestedSurfaces()) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700513
Emilian Peev40ead602017-09-26 15:46:36 +0100514 if (mOutputs[id] == nullptr) {
515 //Output surface got likely removed by client.
516 continue;
517 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700518
Emilian Peev40ead602017-09-26 15:46:36 +0100519 res = outputBufferLocked(mOutputs[id], bufferItem, id);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800520 if (res != OK) {
521 SP_LOGE("%s: outputBufferLocked failed %d", __FUNCTION__, res);
522 mOnFrameAvailableRes.store(res);
523 // If we fail to send buffer to certain output, keep sending to
524 // other outputs.
525 continue;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700526 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800527 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700528
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800529 mOnFrameAvailableRes.store(res);
530}
531
Emilian Peev40ead602017-09-26 15:46:36 +0100532void Camera3StreamSplitter::decrementBufRefCountLocked(uint64_t id, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800533 ATRACE_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800534
Emilian Peev40ead602017-09-26 15:46:36 +0100535 if (mBuffers[id] == nullptr) {
536 return;
537 }
538
539 size_t referenceCount = mBuffers[id]->decrementReferenceCountLocked(surfaceId);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800540 if (referenceCount > 0) {
541 return;
542 }
543
544 // We no longer need to track the buffer now that it is being returned to the
545 // input. Note that this should happen before we unlock the mutex and call
546 // releaseBuffer, to avoid the case where the same bufferId is acquired in
547 // attachBufferToOutputs resulting in a new BufferTracker with same bufferId
548 // overwrites the current one.
549 std::unique_ptr<BufferTracker> tracker_ptr = std::move(mBuffers[id]);
550 mBuffers.erase(id);
551
Emilian Peev40ead602017-09-26 15:46:36 +0100552 uint64_t bufferId = tracker_ptr->getBuffer()->getId();
553 int consumerSlot = -1;
554 uint64_t frameNumber;
Emilian Peev6f823722017-12-07 18:05:49 +0000555 auto inputSlot = mInputSlots.begin();
556 for (; inputSlot != mInputSlots.end(); inputSlot++) {
557 if (inputSlot->second.mGraphicBuffer->getId() == bufferId) {
558 consumerSlot = inputSlot->second.mSlot;
559 frameNumber = inputSlot->second.mFrameNumber;
Emilian Peev40ead602017-09-26 15:46:36 +0100560 break;
561 }
562 }
563 if (consumerSlot == -1) {
564 SP_LOGE("%s: Buffer missing inside input slots!", __FUNCTION__);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800565 return;
566 }
567
Emilian Peev6f823722017-12-07 18:05:49 +0000568 auto detachBuffer = mDetachedBuffers.find(bufferId);
569 bool detach = (detachBuffer != mDetachedBuffers.end());
570 if (detach) {
571 mDetachedBuffers.erase(detachBuffer);
572 mInputSlots.erase(inputSlot);
573 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800574 // Temporarily unlock mutex to avoid circular lock:
575 // 1. This function holds splitter lock, calls releaseBuffer which triggers
576 // onBufferReleased in Camera3OutputStream. onBufferReleased waits on the
577 // OutputStream lock
578 // 2. Camera3SharedOutputStream::getBufferLocked calls
579 // attachBufferToOutputs, which holds the stream lock, and waits for the
580 // splitter lock.
581 sp<IGraphicBufferConsumer> consumer(mConsumer);
582 mMutex.unlock();
Emilian Peev40ead602017-09-26 15:46:36 +0100583 int res = NO_ERROR;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800584 if (consumer != nullptr) {
Emilian Peev6f823722017-12-07 18:05:49 +0000585 if (detach) {
586 res = consumer->detachBuffer(consumerSlot);
587 } else {
588 res = consumer->releaseBuffer(consumerSlot, frameNumber,
589 EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, tracker_ptr->getMergedFence());
590 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800591 } else {
592 SP_LOGE("%s: consumer has become null!", __FUNCTION__);
593 }
594 mMutex.lock();
Emilian Peev6f823722017-12-07 18:05:49 +0000595
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800596 if (res != NO_ERROR) {
Emilian Peev6f823722017-12-07 18:05:49 +0000597 if (detach) {
598 SP_LOGE("%s: detachBuffer returns %d", __FUNCTION__, res);
599 } else {
600 SP_LOGE("%s: releaseBuffer returns %d", __FUNCTION__, res);
601 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700602 }
603}
604
605void Camera3StreamSplitter::onBufferReleasedByOutput(
606 const sp<IGraphicBufferProducer>& from) {
607 ATRACE_CALL();
Emilian Peev703e4992018-02-27 11:42:09 +0000608 sp<Fence> fence;
609
610 int slot = BufferItem::INVALID_BUFFER_SLOT;
611 auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
612 nullptr, nullptr);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700613 Mutex::Autolock lock(mMutex);
Emilian Peev703e4992018-02-27 11:42:09 +0000614 handleOutputDequeueStatusLocked(res, slot);
615 if (res != OK) {
616 return;
617 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700618
Emilian Peev40ead602017-09-26 15:46:36 +0100619 size_t surfaceId = 0;
620 bool found = false;
621 for (const auto& it : mOutputs) {
622 if (it.second == from) {
623 found = true;
624 surfaceId = it.first;
625 break;
626 }
627 }
628 if (!found) {
629 SP_LOGV("%s: output surface not registered anymore!", __FUNCTION__);
630 return;
631 }
632
Emilian Peev703e4992018-02-27 11:42:09 +0000633 returnOutputBufferLocked(fence, from, surfaceId, slot);
Shuzhen Wanga141c5f2017-01-24 14:51:37 -0800634}
635
Emilian Peev703e4992018-02-27 11:42:09 +0000636void Camera3StreamSplitter::onBufferReplacedLocked(
Emilian Peev40ead602017-09-26 15:46:36 +0100637 const sp<IGraphicBufferProducer>& from, size_t surfaceId) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800638 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700639 sp<Fence> fence;
Emilian Peev40ead602017-09-26 15:46:36 +0100640
641 int slot = BufferItem::INVALID_BUFFER_SLOT;
642 auto res = from->dequeueBuffer(&slot, &fence, mWidth, mHeight, mFormat, mProducerUsage,
643 nullptr, nullptr);
Emilian Peev703e4992018-02-27 11:42:09 +0000644 handleOutputDequeueStatusLocked(res, slot);
645 if (res != OK) {
Shuzhen Wangafa8a912017-03-15 10:51:27 -0700646 return;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700647 }
648
Emilian Peev703e4992018-02-27 11:42:09 +0000649 returnOutputBufferLocked(fence, from, surfaceId, slot);
650}
651
652void Camera3StreamSplitter::returnOutputBufferLocked(const sp<Fence>& fence,
653 const sp<IGraphicBufferProducer>& from, size_t surfaceId, int slot) {
654 sp<GraphicBuffer> buffer;
655
656 if (mOutputSlots[from] == nullptr) {
657 //Output surface got likely removed by client.
658 return;
659 }
660
661 auto outputSlots = *mOutputSlots[from];
662 buffer = outputSlots[slot];
Shuzhen Wang0129d522016-10-30 22:43:41 -0700663 BufferTracker& tracker = *(mBuffers[buffer->getId()]);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700664 // Merge the release fence of the incoming buffer so that the fence we send
665 // back to the input includes all of the outputs' fences
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800666 if (fence != nullptr && fence->isValid()) {
667 tracker.mergeFence(fence);
668 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700669
Emilian Peev6f823722017-12-07 18:05:49 +0000670 auto detachBuffer = mDetachedBuffers.find(buffer->getId());
671 bool detach = (detachBuffer != mDetachedBuffers.end());
672 if (detach) {
Emilian Peev703e4992018-02-27 11:42:09 +0000673 auto res = from->detachBuffer(slot);
Emilian Peev6f823722017-12-07 18:05:49 +0000674 if (res == NO_ERROR) {
675 outputSlots[slot] = nullptr;
676 } else {
677 SP_LOGE("%s: detach buffer from output failed (%d)", __FUNCTION__, res);
678 }
679 }
680
Shuzhen Wang0129d522016-10-30 22:43:41 -0700681 // Check to see if this is the last outstanding reference to this buffer
Emilian Peev40ead602017-09-26 15:46:36 +0100682 decrementBufRefCountLocked(buffer->getId(), surfaceId);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700683}
684
Emilian Peev703e4992018-02-27 11:42:09 +0000685void Camera3StreamSplitter::handleOutputDequeueStatusLocked(status_t res, int slot) {
686 if (res == NO_INIT) {
687 // If we just discovered that this output has been abandoned, note that,
688 // but we can't do anything else, since buffer is invalid
689 onAbandonedLocked();
690 } else if (res == IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
691 SP_LOGE("%s: Producer needs to re-allocate buffer!", __FUNCTION__);
692 SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
693 } else if (res == IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
694 SP_LOGE("%s: All slot->buffer mapping should be released!", __FUNCTION__);
695 SP_LOGE("%s: This should not happen with buffer allocation disabled!", __FUNCTION__);
696 } else if (res == NO_MEMORY) {
697 SP_LOGE("%s: No free buffers", __FUNCTION__);
698 } else if (res == WOULD_BLOCK) {
699 SP_LOGE("%s: Dequeue call will block", __FUNCTION__);
700 } else if (res != OK || (slot == BufferItem::INVALID_BUFFER_SLOT)) {
701 SP_LOGE("%s: dequeue buffer from output failed (%d)", __FUNCTION__, res);
702 }
703}
704
Shuzhen Wang0129d522016-10-30 22:43:41 -0700705void Camera3StreamSplitter::onAbandonedLocked() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800706 // If this is called from binderDied callback, it means the app process
707 // holding the binder has died. CameraService will be notified of the binder
708 // death, and camera device will be closed, which in turn calls
709 // disconnect().
710 //
711 // If this is called from onBufferReleasedByOutput or onFrameAvailable, one
712 // consumer being abanoned shouldn't impact the other consumer. So we won't
713 // stop the buffer flow.
714 //
715 // In both cases, we don't need to do anything here.
716 SP_LOGV("One of my outputs has abandoned me");
717}
718
719int Camera3StreamSplitter::getSlotForOutputLocked(const sp<IGraphicBufferProducer>& gbp,
720 const sp<GraphicBuffer>& gb) {
721 auto& outputSlots = *mOutputSlots[gbp];
722
723 for (size_t i = 0; i < outputSlots.size(); i++) {
724 if (outputSlots[i] == gb) {
725 return (int)i;
726 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700727 }
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800728
Emilian Peev40ead602017-09-26 15:46:36 +0100729 SP_LOGV("%s: Cannot find slot for gb %p on output %p", __FUNCTION__, gb.get(),
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800730 gbp.get());
731 return BufferItem::INVALID_BUFFER_SLOT;
732}
733
Shuzhen Wang0129d522016-10-30 22:43:41 -0700734Camera3StreamSplitter::OutputListener::OutputListener(
735 wp<Camera3StreamSplitter> splitter,
736 wp<IGraphicBufferProducer> output)
737 : mSplitter(splitter), mOutput(output) {}
738
739void Camera3StreamSplitter::OutputListener::onBufferReleased() {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800740 ATRACE_CALL();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700741 sp<Camera3StreamSplitter> splitter = mSplitter.promote();
742 sp<IGraphicBufferProducer> output = mOutput.promote();
743 if (splitter != nullptr && output != nullptr) {
744 splitter->onBufferReleasedByOutput(output);
745 }
746}
747
748void Camera3StreamSplitter::OutputListener::binderDied(const wp<IBinder>& /* who */) {
749 sp<Camera3StreamSplitter> splitter = mSplitter.promote();
750 if (splitter != nullptr) {
751 Mutex::Autolock lock(splitter->mMutex);
752 splitter->onAbandonedLocked();
753 }
754}
755
756Camera3StreamSplitter::BufferTracker::BufferTracker(
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800757 const sp<GraphicBuffer>& buffer, const std::vector<size_t>& requestedSurfaces)
758 : mBuffer(buffer), mMergedFence(Fence::NO_FENCE), mRequestedSurfaces(requestedSurfaces),
759 mReferenceCount(requestedSurfaces.size()) {}
Shuzhen Wang0129d522016-10-30 22:43:41 -0700760
761void Camera3StreamSplitter::BufferTracker::mergeFence(const sp<Fence>& with) {
762 mMergedFence = Fence::merge(String8("Camera3StreamSplitter"), mMergedFence, with);
763}
764
Emilian Peev40ead602017-09-26 15:46:36 +0100765size_t Camera3StreamSplitter::BufferTracker::decrementReferenceCountLocked(size_t surfaceId) {
766 const auto& it = std::find(mRequestedSurfaces.begin(), mRequestedSurfaces.end(), surfaceId);
767 if (it == mRequestedSurfaces.end()) {
768 return mReferenceCount;
769 } else {
770 mRequestedSurfaces.erase(it);
771 }
772
Shuzhen Wang0129d522016-10-30 22:43:41 -0700773 if (mReferenceCount > 0)
774 --mReferenceCount;
775 return mReferenceCount;
776}
777
778} // namespace android