blob: 3560d1f11783d3c5c87c86f8e47a44285a638fd6 [file]
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#undef LOG_TAG
#define LOG_TAG "BLASTBufferQueue"
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
//#define LOG_NDEBUG 0
#include <atomic>
#include <com_android_graphics_libgui_flags.h>
#include <cutils/atomic.h>
#include <ftl/fake_guard.h>
#include <gui/BLASTBufferQueue.h>
#include <gui/BufferItemConsumer.h>
#include <gui/BufferQueueConsumer.h>
#include <gui/BufferQueueCore.h>
#include <gui/BufferQueueProducer.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <android/gui/ITransactionHangCallback.h>
#include <android/gui/ITransactionReadyCallback.h>
#include <gui/FrameRateUtils.h>
#include <gui/GLConsumer.h>
#include <gui/IProducerListener.h>
#include <gui/Surface.h>
#include <gui/TraceUtils.h>
#include <utils/Errors.h>
#include <utils/Singleton.h>
#include <utils/Trace.h>
#include <private/gui/ComposerService.h>
#include <private/gui/ComposerServiceAIDL.h>
#include <android-base/thread_annotations.h>
#include "AsyncWorker.h"
using namespace com::android::graphics::libgui;
using namespace std::chrono_literals;
namespace {
template <class Mutex>
class UnlockGuard {
public:
explicit UnlockGuard(Mutex& lock) : mLock{lock} { mLock.unlock(); }
~UnlockGuard() { mLock.lock(); }
UnlockGuard(const UnlockGuard&) = delete;
UnlockGuard& operator=(const UnlockGuard&) = delete;
private:
Mutex& mLock;
};
inline const char* boolToString(bool b) {
return b ? "true" : "false";
}
} // namespace
namespace android {
// Macros to include adapter info in log messages
#define BQA_LOGD(x, ...) \
ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
#define BQA_LOGV(x, ...) \
ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
// enable logs for a single layer
//#define BQA_LOGV(x, ...) \
// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
#define BQA_LOGE(x, ...) \
ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
#define BBQ_TRACE(x, ...) \
ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
mNumAcquired, ##__VA_ARGS__)
#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
std::unique_lock _lock{mutex}; \
base::ScopedLockAssertion assumeLocked(mutex);
void BLASTBufferItemConsumer::onDisconnect() {
{
Mutex::Autolock lock(mMutex);
onDisconnectLocked();
}
BufferItemConsumer::onDisconnect();
}
void BLASTBufferItemConsumer::onDisconnectLocked() {
mPreviouslyConnected = mCurrentlyConnected;
mCurrentlyConnected = false;
if (mPreviouslyConnected) {
mDisconnectEvents.push(mCurrentFrameNumber);
}
mFrameEventHistory.onDisconnect();
}
void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
FrameEventHistoryDelta* outDelta) {
Mutex::Autolock lock(mMutex);
if (newTimestamps) {
// BufferQueueProducer only adds a new timestamp on
// queueBuffer
mCurrentFrameNumber = newTimestamps->frameNumber;
mFrameEventHistory.addQueue(*newTimestamps);
}
if (outDelta) {
// frame event histories will be processed
// only after the producer connects and requests
// deltas for the first time. Forward this intent
// to SF-side to turn event processing back on
mPreviouslyConnected = mCurrentlyConnected;
mCurrentlyConnected = true;
mFrameEventHistory.getAndResetDelta(outDelta);
}
}
void BLASTBufferItemConsumer::updateFrameTimestamps(
uint64_t frameNumber, uint64_t previousFrameNumber, nsecs_t refreshStartTime,
const sp<Fence>& glDoneFence, const sp<Fence>& presentFence,
const sp<Fence>& prevReleaseFence, CompositorTiming compositorTiming, nsecs_t latchTime,
nsecs_t dequeueReadyTime) {
Mutex::Autolock lock(mMutex);
// if the producer is not connected, don't bother updating,
// the next producer that connects won't access this frame event
if (!mCurrentlyConnected) return;
std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
mFrameEventHistory.addLatch(frameNumber, latchTime);
if (flags::frametimestamps_previousrelease()) {
if (previousFrameNumber > 0) {
mFrameEventHistory.addRelease(previousFrameNumber, dequeueReadyTime,
std::move(releaseFenceTime));
}
} else {
mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
}
mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
compositorTiming);
}
void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
bool disconnect = false;
Mutex::Autolock lock(mMutex);
while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
disconnect = true;
mDisconnectEvents.pop();
}
if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
}
void BLASTBufferItemConsumer::onSidebandStreamChanged() {
sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
if (bbq != nullptr) {
sp<NativeHandle> stream = getSidebandStream();
bbq->setSidebandStream(stream);
}
}
void BLASTBufferItemConsumer::onSetFrameRate(float frameRate, int8_t compatibility,
int8_t changeFrameRateStrategy) {
sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
if (bbq != nullptr) {
bbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
}
}
void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
Mutex::Autolock lock(mMutex);
mFrameEventHistory.resize(newSize);
}
sp<gui::IBLASTBufferQueue> BLASTBufferItemConsumer::getBLASTBufferQueue() const {
return mBLASTBufferQueue.promote();
}
void BLASTBufferQueue::initialize() {
std::lock_guard _lock{mMutex};
createBufferQueue(&mProducer, &mConsumer);
mBufferItemConsumer =
sp<BLASTBufferItemConsumer>::make(mProducer, mConsumer,
GraphicBuffer::USAGE_HW_COMPOSER |
GraphicBuffer::USAGE_HW_TEXTURE,
1, false, wp<BLASTBufferQueue>::fromExisting(this));
// since the adapter is in the client process, set dequeue timeout
// explicitly so that dequeueBuffer will block
mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mState.producerId);
mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mState.producerId);
mBufferItemConsumer->setName(String8(consumerName.c_str()));
mBufferItemConsumer->setFrameAvailableListener(wp<BLASTBufferQueue>::fromExisting(this));
ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
TransactionCompletedListener::getInstance()->addQueueStallListener(
[&](const std::string& reason) {
sp<gui::ITransactionHangCallback> callbackCopy;
{
std::lock_guard _lock{mMutex};
callbackCopy = mState.transactionHangCallback;
}
if (callbackCopy) {
callTransactionHangCallback(*callbackCopy, reason);
}
},
this);
// safe default, most producers are expected to override this
mProducer->setMaxDequeuedBufferCount(2);
BQA_LOGV("BLASTBufferQueue created");
}
static std::atomic<uint32_t> sNextId = 0;
BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame) {
mState.producerId = sNextId++;
mState.name = String16(name.c_str());
mState.applyToken = sp<BBinder>::make();
mState.updateDestinationFrame = updateDestinationFrame;
mName = name + "#" + std::to_string(mState.producerId);
}
// AIDL interface methods
binder::Status BLASTBufferQueue::syncNextTransaction(
bool acquireSingleBuffer, const sp<gui::ITransactionReadyCallback>& callback,
bool* outSuccess) {
return forwardOrExecute(
[&](const sp<gui::IBLASTBufferQueue>& remote) {
return remote->syncNextTransaction(acquireSingleBuffer, callback, outSuccess);
},
[&]() REQUIRES(mMutex) {
*outSuccess = syncNextTransactionLocked(callback, acquireSingleBuffer);
return binder::Status::ok();
});
}
binder::Status BLASTBufferQueue::mergeWithNextTransaction(
SurfaceComposerClient::Transaction* transaction) {
return forwardOrExecute(
[&](const sp<gui::IBLASTBufferQueue>& remote) {
return remote->mergeWithNextTransaction(transaction);
},
[&]() REQUIRES(mMutex) {
mergeWithNextTransactionLocked(transaction, getLastAcquiredFrameNumLocked() + 1);
return binder::Status::ok();
});
}
binder::Status BLASTBufferQueue::setRemote(const sp<gui::IBLASTBufferQueue>& remoteBBQ,
gui::BLASTBufferQueueState* outState) {
// Never proxy this method
std::lock_guard _lock{mMutex};
if (remoteBBQ == nullptr) {
return binder::Status::fromExceptionCode(binder::Status::EX_NULL_POINTER);
}
if (mRemoteBBQ == nullptr) {
drainBufferReleaseConsumerLocked();
}
mRemoteBBQ = remoteBBQ;
*outState = mState;
return binder::Status::ok();
}
binder::Status BLASTBufferQueue::clearRemote(const gui::BLASTBufferQueueState& state) {
// Never proxy this method
std::lock_guard _lock{mMutex};
mRemoteBBQ = nullptr;
mState = state;
mState.producerId += 1;
sNextId = mState.producerId + 1;
updateBufferReleaseProducer();
return binder::Status::ok();
}
binder::Status BLASTBufferQueue::getSurfaceForPixelCopy(android::view::Surface* outSurface) {
return forwardOrExecute(
[&](const sp<gui::IBLASTBufferQueue>& remote) {
return remote->getSurfaceForPixelCopy(outSurface);
},
[&]() REQUIRES(mMutex) {
sp<Surface> localSurface =
getSurfaceLocked(false /* includeSurfaceControlHandle */);
if (localSurface == nullptr) {
return binder::Status::fromExceptionCode(binder::Status::EX_NULL_POINTER);
}
*outSurface = android::view::Surface::fromSurface(localSurface);
return binder::Status::ok();
});
}
status_t BLASTBufferQueue::setAsRemoteFor(const sp<gui::IBLASTBufferQueue>& host) {
std::lock_guard _lock{mMutex};
if (host != nullptr) {
if (mHostBBQ != nullptr) {
BQA_LOGE("Already set as a remote");
return ALREADY_EXISTS;
}
gui::BLASTBufferQueueState state;
auto result = host->setRemote(sp<gui::IBLASTBufferQueue>::fromExisting(this), &state);
if (!result.isOk()) {
BQA_LOGE("Failed to set self as remote BBQ: %s", result.toString8().c_str());
return NO_INIT;
}
mHostBBQ = host;
mState = state;
mState.producerId += 1;
sNextId = mState.producerId + 1;
std::string name = String8(mState.name).c_str();
mName = name + "#" + std::to_string(mState.producerId);
updateBufferReleaseProducer();
mQueuedBufferTrace =
"QueuedBuffer - " + mName + "BLAST#" + std::to_string(mState.producerId);
auto consumerName = mName + " (BLAST Consumer) " + std::to_string(mState.producerId);
mBufferItemConsumer->setName(String8(consumerName.c_str()));
} else {
if (mHostBBQ == nullptr) {
BQA_LOGE("Trying to clear remote BBQ when none is set");
return INVALID_OPERATION;
}
drainBufferReleaseConsumerLocked();
auto result = mHostBBQ->clearRemote(mState);
if (!result.isOk()) {
BQA_LOGE("Failed to clear remote BBQ: %s", result.toString8().c_str());
return FAILED_TRANSACTION;
}
mHostBBQ = nullptr;
}
return OK;
}
BLASTBufferQueue::~BLASTBufferQueue() {
TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
// Clear all IBinder references on a thread with a valid JNIEnv (assuming this BBQ was created
// on a thread with a valid JNIEnv). This includes not only the explicit member variables
// cleared at the end of this block, but also the local temporary variables.
performOnJVMAttachedThread([this]() {
sp<gui::ITransactionReadyCallback> callback;
std::optional<SurfaceComposerClient::Transaction> transaction;
{
std::lock_guard<std::mutex> lock(mMutex);
callback = std::move(mState.transactionReadyCallback);
transaction = std::move(mState.syncTransaction);
}
if (callback) {
callTransactionReadyCallback(*callback, *transaction);
}
bool hasPendingTransactions = false;
{
std::lock_guard _lock{mMutex};
hasPendingTransactions = !mPendingTransactions.empty();
}
if (hasPendingTransactions) {
SurfaceComposerClient::Transaction t;
sp<IBinder> applyToken;
{
std::lock_guard _lock{mMutex};
BQA_LOGE("Applying pending transactions on dtor %d",
static_cast<uint32_t>(mPendingTransactions.size()));
mergePendingTransactions(&t,
std::numeric_limits<uint64_t>::max() /* frameNumber */);
applyToken = mState.applyToken;
}
// All transactions on our apply token are one-way. See comment on
// mLastAppliedFrameNumber
t.setApplyToken(applyToken).apply(false, true);
}
// Explicitly clear all IBinder-related members while this thread is still attached
// to the JVM
std::lock_guard _lock{mMutex};
mState.applyToken.clear();
mState.transactionHangCallback.clear();
mState.transactionReadyCallback.clear();
});
}
void BLASTBufferQueue::onFirstRef() {
initialize();
}
binder::Status BLASTBufferQueue::update(const view::SurfaceControl& newSurfaceControl,
int32_t width, int32_t height, int32_t format) {
LOG_ALWAYS_FATAL_IF(!newSurfaceControl, "BLASTBufferQueue: newSurfaceControl must not be NULL");
return forwardOrExecute(
[&](const sp<gui::IBLASTBufferQueue>& remote) {
return remote->update(newSurfaceControl, width, height, format);
},
[&]() REQUIRES(mMutex) {
return updateLocked(newSurfaceControl, width, height, format);
});
}
binder::Status BLASTBufferQueue::updateLocked(const view::SurfaceControl& newSurfaceControl,
int32_t width, int32_t height, int32_t format) {
if (mState.format != format) {
mState.format = format;
mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
}
const bool surfaceControlChanged =
!SurfaceControl::isSameSurface(mState.surfaceControl, newSurfaceControl);
if (surfaceControlChanged && mState.surfaceControl) {
BQA_LOGD("Updating SurfaceControl without recreating BBQ");
mState.setBufferHasBarrier = false;
}
// Always update the native object even though they might have the same layer handle, so we can
// get the updated transform hint from WM.
mState.surfaceControl = newSurfaceControl;
SurfaceComposerClient::Transaction t;
bool applyTransaction = false;
if (surfaceControlChanged) {
updateBufferReleaseProducer();
t.setFlags(mState.surfaceControl, layer_state_t::eEnableBackpressure,
layer_state_t::eEnableBackpressure);
// Migrate the picture profile handle to the new surface control.
if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
mPictureProfileHandle.has_value()) {
t.setPictureProfileHandle(mState.surfaceControl, *mPictureProfileHandle);
}
applyTransaction = true;
}
mState.transformHint = mState.surfaceControl->getTransformHint();
mBufferItemConsumer->setTransformHint(mState.transformHint);
BQA_LOGV("update width=%d height=%d format=%d transformHint=%d", width, height, format,
mState.transformHint);
gui::Size newSize;
newSize.width = width;
newSize.height = height;
if (mState.requestedSize != newSize) {
mState.requestedSize = newSize;
mBufferItemConsumer->setDefaultBufferSize(mState.requestedSize.width,
mState.requestedSize.height);
if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
// If the buffer supports scaling, update the frame immediately since the client may
// want to scale the existing buffer to the new size.
mState.size = mState.requestedSize;
if (mState.updateDestinationFrame) {
t.setDestinationFrame(mState.surfaceControl, Rect(newSize.width, newSize.height));
applyTransaction = true;
}
}
}
if (applyTransaction) {
// All transactions on our apply token are one-way. See comment on mLastAppliedFrameNumber
t.setApplyToken(mState.applyToken).apply(false /* synchronous */, true /* oneWay */);
}
return binder::Status::ok();
}
static std::optional<SurfaceControlStats> findMatchingStat(
const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
for (auto stat : stats) {
if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
return stat;
}
}
return std::nullopt;
}
TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCommittedCallbackThunk() {
return [bbq = sp<BLASTBufferQueue>::fromExisting(
this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
const std::vector<SurfaceControlStats>& stats) {
bbq->transactionCommittedCallback(latchTime, presentFence, stats);
};
}
void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
const sp<Fence>& /*presentFence*/,
const std::vector<SurfaceControlStats>& stats) {
{
std::lock_guard _lock{mMutex};
BBQ_TRACE();
BQA_LOGV("transactionCommittedCallback");
if (!mSurfaceControlsWithPendingCallback.empty()) {
sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
if (stat) {
uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
// We need to check if we were waiting for a transaction callback in order to
// process any pending buffers and unblock. It's possible to get transaction
// callbacks for previous requests so we need to ensure that there are no pending
// frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
// set and then check if it's empty. If there are no more pending syncs, we can
// proceed with flushing the shadow queue.
mSyncedFrameNumbers.erase(currFrameNumber);
if (mSyncedFrameNumbers.empty()) {
flushShadowQueue();
}
} else {
BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
}
} else {
BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
"empty.");
}
}
}
TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCallbackThunk() {
return [bbq = sp<BLASTBufferQueue>::fromExisting(
this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
const std::vector<SurfaceControlStats>& stats) {
bbq->transactionCallback(latchTime, presentFence, stats);
};
}
void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
const std::vector<SurfaceControlStats>& stats) {
{
std::lock_guard _lock{mMutex};
BBQ_TRACE();
BQA_LOGV("transactionCallback");
if (!mSurfaceControlsWithPendingCallback.empty()) {
sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
mSurfaceControlsWithPendingCallback.pop();
std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
if (statsOptional) {
SurfaceControlStats stat = *statsOptional;
if (stat.transformHint) {
mState.transformHint = *stat.transformHint;
mBufferItemConsumer->setTransformHint(mState.transformHint);
BQA_LOGV("updated transformHint=%d", mState.transformHint);
}
if (stat.cornerRadii.has_value()) {
const gui::CornerRadii& newRadii = stat.cornerRadii.value();
if (mLastCornerRadii != newRadii) {
mLastCornerRadii = newRadii;
std::function<void(const gui::CornerRadii)> callbackCopy =
getCornerRadiiCallback();
if (callbackCopy) callbackCopy(newRadii);
BQA_LOGV("updated cornerRadii=%s", newRadii.toString().c_str());
}
}
// Update frametime stamps if the frame was latched and presented, indicated by a
// valid latch time.
if (stat.latchTime > 0) {
mBufferItemConsumer
->updateFrameTimestamps(stat.frameEventStats.frameNumber,
stat.frameEventStats.previousFrameNumber,
stat.frameEventStats.refreshStartTime,
stat.frameEventStats.gpuCompositionDoneFence,
stat.presentFence, stat.previousReleaseFence,
stat.frameEventStats.compositorTiming,
stat.latchTime,
stat.frameEventStats.dequeueReadyTime);
}
auto currFrameNumber = stat.frameEventStats.frameNumber;
// Release stale buffers.
for (const auto& [key, _] : mSubmitted) {
if (currFrameNumber <= key.framenumber) {
continue; // not stale.
}
releaseBufferCallbackLocked(key,
stat.previousReleaseFence
? stat.previousReleaseFence
: Fence::NO_FENCE,
stat.currentMaxAcquiredBufferCount,
true /* fakeRelease */);
}
} else {
BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
}
} else {
BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
"empty.");
}
}
}
void BLASTBufferQueue::flushShadowQueue() {
BQA_LOGV("flushShadowQueue");
int32_t numFramesToFlush = mNumFrameAvailable;
while (numFramesToFlush > 0) {
acquireNextBufferLocked(nullptr);
numFramesToFlush--;
}
}
// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
// Otherwise, this is a no-op.
ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
std::optional<uint32_t> currentMaxAcquiredBufferCount) {
sp<BLASTBufferQueue> bbq = weakBbq.promote();
if (!bbq) {
ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
return;
}
bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
bbq->drainBufferReleaseConsumer();
};
}
void BLASTBufferQueue::releaseBufferCallback(
const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
std::optional<uint32_t> currentMaxAcquiredBufferCount) {
std::lock_guard _lock{mMutex};
BBQ_TRACE();
releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
false /* fakeRelease */);
}
void BLASTBufferQueue::releaseBufferCallbackLocked(
const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
ATRACE_CALL();
BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
// Calculate how many buffers we need to hold before we release them back
// to the buffer queue. This will prevent higher latency when we are running
// on a lower refresh rate than the max supported. We only do that for EGL
// clients as others don't care about latency
const auto it = mSubmitted.find(id);
const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
if (currentMaxAcquiredBufferCount) {
mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
}
const uint32_t numPendingBuffersToHold =
isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
auto rb = ReleasedBuffer{id, releaseFence};
if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
mPendingRelease.emplace_back(rb);
if (fakeRelease) {
BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
id.framenumber);
BBQ_TRACE("FakeReleaseCallback");
}
}
// Release all buffers that are beyond the ones that we need to hold
while (mPendingRelease.size() > numPendingBuffersToHold) {
const auto releasedBuffer = mPendingRelease.front();
mPendingRelease.pop_front();
releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
// Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
// are still transactions that have sync buffers in them that have not been applied or
// dropped. Instead, let onFrameAvailable handle processing them since it will merge with
// the syncTransaction.
if (mSyncedFrameNumbers.empty()) {
acquireNextBufferLocked(nullptr);
}
}
ATRACE_INT("PendingRelease", mPendingRelease.size());
ATRACE_INT(mQueuedBufferTrace.c_str(),
mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
mCallbackCV.notify_all();
}
void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
const sp<Fence>& releaseFence) {
auto it = mSubmitted.find(callbackId);
if (it == mSubmitted.end()) {
return;
}
mNumAcquired--;
BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
BQA_LOGV("released %s", callbackId.to_string().c_str());
mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
mSubmitted.erase(it);
// Remove the frame number from mSyncedFrameNumbers since we can get a release callback
// without getting a transaction committed if the buffer was dropped.
mSyncedFrameNumbers.erase(callbackId.framenumber);
}
static gui::Size getBufferSize(const BufferItem& item) {
uint32_t bufWidth = item.mGraphicBuffer->getWidth();
uint32_t bufHeight = item.mGraphicBuffer->getHeight();
// Take the buffer's orientation into account
if (item.mTransform & ui::Transform::ROT_90) {
std::swap(bufWidth, bufHeight);
}
gui::Size size;
size.width = bufWidth;
size.height = bufHeight;
return size;
}
status_t BLASTBufferQueue::acquireNextBufferLocked(
SurfaceComposerClient::Transaction* const transaction) {
// Check if we have frames available and we have not acquired the maximum number of buffers.
// Even with this check, the consumer can fail to acquire an additional buffer if the consumer
// has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
// case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
if (mNumFrameAvailable == 0) {
BQA_LOGV("Can't acquire next buffer. No available frames");
return BufferQueue::NO_BUFFER_AVAILABLE;
}
if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
mNumAcquired, mMaxAcquiredBuffers);
return BufferQueue::NO_BUFFER_AVAILABLE;
}
const sp<SurfaceControl> surfaceControl = mState.surfaceControl;
if (surfaceControl == nullptr) {
BQA_LOGE("ERROR : surface control is null");
return NAME_NOT_FOUND;
}
SurfaceComposerClient::Transaction localTransaction;
bool applyTransaction = true;
SurfaceComposerClient::Transaction* t = &localTransaction;
if (transaction) {
t = transaction;
applyTransaction = false;
}
BufferItem bufferItem;
status_t status =
mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
return status;
} else if (status != OK) {
BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
return status;
}
auto buffer = bufferItem.mGraphicBuffer;
int32_t totalProcessed = 1 + static_cast<int32_t>(bufferItem.mCountOfDroppedBuffers);
if (mNumFrameAvailable >= totalProcessed) {
mNumFrameAvailable -= totalProcessed;
} else {
BQA_LOGE("mNumFrameAvailable (%u) is smaller than processed frames (%u)",
mNumFrameAvailable, totalProcessed);
mNumFrameAvailable = 0;
}
BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
if (buffer == nullptr) {
mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
BQA_LOGE("Buffer was empty");
return BAD_VALUE;
}
if (buffer->getId() == mLastAcquiredBufferId &&
bufferItem.mFrameNumber == mLastAcquiredFrameNumber) {
BQA_LOGV("acquireNextBufferLocked skipping already acquired bufferId:%" PRIu64
" frameNumber:%" PRIu64,
buffer->getId(), bufferItem.mFrameNumber);
mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
return acquireNextBufferLocked(transaction);
}
if (rejectBuffer(bufferItem)) {
BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
"buffer{size=%dx%d transform=%d}",
mState.size.width, mState.size.height, mState.requestedSize.width,
mState.requestedSize.height, buffer->getWidth(), buffer->getHeight(),
bufferItem.mTransform);
mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
return acquireNextBufferLocked(transaction);
}
mNumAcquired++;
mLastAcquiredBufferId = buffer->getId();
mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
ReleaseCallbackId releaseCallbackId(mLastAcquiredBufferId, mLastAcquiredFrameNumber);
mSubmitted.emplace_or_replace(releaseCallbackId, bufferItem);
bool needsDisconnect = false;
mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
// if producer disconnected before, notify SurfaceFlinger
if (needsDisconnect) {
t->notifyProducerDisconnect(surfaceControl);
}
// Only update mSize for destination bounds if the incoming buffer matches the requested size.
// Otherwise, it could cause stretching since the destination bounds will update before the
// buffer with the new size is acquired.
if (mState.requestedSize == getBufferSize(bufferItem) ||
bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
mState.size = mState.requestedSize;
}
Rect crop = computeCrop(bufferItem);
mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
bufferItem.mScalingMode, crop);
auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
sp<Fence> fence =
bufferItem.mFence ? sp<Fence>::make(bufferItem.mFence->dup()) : Fence::NO_FENCE;
nsecs_t dequeueTime = -1;
{
std::lock_guard _lock{mTimestampMutex};
auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
if (dequeueTimeIt != mDequeueTimestamps.end()) {
dequeueTime = dequeueTimeIt->second;
mDequeueTimestamps.erase(dequeueTimeIt);
}
}
t->setBuffer(surfaceControl, buffer, fence, bufferItem.mFrameNumber, mState.producerId,
releaseBufferCallback, dequeueTime);
t->setDataspace(surfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
t->setHdrMetadata(surfaceControl, bufferItem.mHdrMetadata);
t->setSurfaceDamageRegion(surfaceControl, bufferItem.mSurfaceDamage);
t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
mSurfaceControlsWithPendingCallback.push(surfaceControl);
if (mState.updateDestinationFrame) {
t->setDestinationFrame(surfaceControl, Rect(mState.size.width, mState.size.height));
}
bool ignoreDestinationFrame = bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
if (flags::bbq_support_scaling_modes()) {
ignoreDestinationFrame |=
bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP;
}
t->setFlags(surfaceControl, ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
layer_state_t::eIgnoreDestinationFrame);
t->setBufferCrop(surfaceControl, crop);
t->setTransform(surfaceControl, bufferItem.mTransform);
t->setTransformToDisplayInverse(surfaceControl, bufferItem.mTransformToDisplayInverse);
t->setAutoRefresh(surfaceControl, bufferItem.mAutoRefresh);
if (!bufferItem.mIsAutoTimestamp) {
t->setDesiredPresentTime(bufferItem.mTimestamp);
}
if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
bufferItem.mPictureProfileHandle.has_value()) {
t->setPictureProfileHandle(surfaceControl, *bufferItem.mPictureProfileHandle);
// The current picture profile must be maintained in case the BBQ gets its
// SurfaceControl switched out.
mPictureProfileHandle = bufferItem.mPictureProfileHandle;
// Clear out the picture profile if the requestor has asked for it to be cleared
if (mPictureProfileHandle == PictureProfileHandle::NONE) {
mPictureProfileHandle = std::nullopt;
}
}
// Drop stale frame timeline infos
while (!mPendingFrameTimelines.empty() &&
mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
mPendingFrameTimelines.front().first,
mPendingFrameTimelines.front().second.vsyncId);
mPendingFrameTimelines.pop();
}
if (!mPendingFrameTimelines.empty() &&
mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
" vsyncId: %" PRId64,
bufferItem.mFrameNumber,
mPendingFrameTimelines.front().second.vsyncId);
t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
mPendingFrameTimelines.pop();
}
mergePendingTransactions(t, bufferItem.mFrameNumber);
if (applyTransaction) {
// All transactions on our apply token are one-way. See comment on mLastAppliedFrameNumber
status_t status = t->setApplyToken(mState.applyToken).apply(false, true);
if (status != OK) {
BQA_LOGE("Transaction Failure Details: Status: %d (%s), Pending Transactions Merged: "
"%zu, Transaction ID: %" PRIu64 ", Frame Number: %" PRIu64
", Buffer Size: %dx%d",
status, statusToString(status).c_str(), mPendingTransactions.size(),
t->getId(), bufferItem.mFrameNumber, bufferItem.mGraphicBuffer->getWidth(),
bufferItem.mGraphicBuffer->getHeight());
}
LOG_ALWAYS_FATAL_IF(status != OK,
"[%s] acquireNextBufferLocked failed to apply transaction. status=%s",
mName.c_str(), statusToString(status).c_str());
mLastAppliedFrameNumber = bufferItem.mFrameNumber;
mState.setBufferHasBarrier = true;
} else {
if (mState.setBufferHasBarrier) {
t->setBufferHasBarrier(surfaceControl, mLastAppliedFrameNumber);
}
}
BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
" applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
" graphicBufferId=%" PRIu64 "%s transform=%d",
mState.size.width, mState.size.height, bufferItem.mFrameNumber,
boolToString(applyTransaction), bufferItem.mTimestamp,
bufferItem.mIsAutoTimestamp ? "(auto)" : "",
static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
return OK;
}
Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
if (flags::bbq_support_scaling_modes()) {
if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Rect crop = item.mCrop;
if (crop.isEmpty() && item.mGraphicBuffer != nullptr) {
crop = Rect(0, 0, item.mGraphicBuffer->getWidth(),
item.mGraphicBuffer->getHeight());
}
return GLConsumer::scaleDownCrop(crop, mState.size.width, mState.size.height);
} else if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP) {
Rect crop = item.mCrop;
if (crop.isEmpty() && item.mGraphicBuffer != nullptr) {
crop = Rect(0, 0, item.mGraphicBuffer->getWidth(),
item.mGraphicBuffer->getHeight());
}
int32_t cropWidth = std::min(crop.width(), mState.size.width);
int32_t cropHeight = std::min(crop.height(), mState.size.height);
int32_t left = crop.left + (crop.width() - cropWidth) / 2;
int32_t top = crop.top + (crop.height() - cropHeight) / 2;
return Rect(left, top, left + cropWidth, top + cropHeight);
}
} else {
if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
return GLConsumer::scaleDownCrop(item.mCrop, mState.size.width, mState.size.height);
}
}
return item.mCrop;
}
status_t BLASTBufferQueue::acquireAndReleaseBuffer() {
BBQ_TRACE();
BufferItem bufferItem;
status_t status =
mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
if (status != OK) {
if (status != BufferQueue::NO_BUFFER_AVAILABLE) {
BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
statusToString(status).c_str());
}
return status;
}
int32_t totalProcessed = 1 + static_cast<int32_t>(bufferItem.mCountOfDroppedBuffers);
if (mNumFrameAvailable >= totalProcessed) {
mNumFrameAvailable -= totalProcessed;
} else {
BQA_LOGE("mNumFrameAvailable (%u) is smaller than processed frames (%u)",
mNumFrameAvailable, totalProcessed);
mNumFrameAvailable = 0;
}
mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
return OK;
}
void BLASTBufferQueue::onDisconnect() {
UNIQUE_LOCK_WITH_ASSERTION(mMutex);
BQA_LOGV("onDisconnect: clearing state");
// Flush the shadow queue to safely drain any stale buffers left in the
// BufferQueueCore queue by the disconnected producer.
while (mNumFrameAvailable > 0) {
if (acquireAndReleaseBuffer() != OK) {
BQA_LOGV("Stopped flushing shadow queue (consumer likely full). %u remaining.",
mNumFrameAvailable);
break;
}
}
mCallbackCV.notify_all();
}
void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
sp<gui::ITransactionReadyCallback> prevCallback;
std::optional<SurfaceComposerClient::Transaction> prevTransaction;
{
UNIQUE_LOCK_WITH_ASSERTION(mMutex);
BBQ_TRACE();
bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
const bool syncTransactionSet = mState.transactionReadyCallback != nullptr;
BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
if (syncTransactionSet) {
// If we are going to re-use the same syncTransaction, release the buffer that may
// already be set in the Transaction. This is to allow us a free slot early to continue
// processing a new buffer.
if (!mState.acquireSingleBuffer) {
auto bufferData = mState.syncTransaction->getAndClearBuffer(mState.surfaceControl);
if (bufferData) {
BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
bufferData->frameNumber);
releaseBuffer(bufferData->generateReleaseCallbackId(),
bufferData->acquireFence);
}
}
if (waitForTransactionCallback) {
// We are waiting on a previous sync's transaction callback so allow another sync
// transaction to proceed.
//
// We need to first flush out the transactions that were in between the two syncs.
// We do this by merging them into syncTransaction so any buffer merging will get
// a release callback invoked.
while (mNumFrameAvailable > 0) {
// flush out the shadow queue
if (acquireAndReleaseBuffer() != OK) break;
}
} else {
// Make sure the frame available count is 0 before proceeding with a sync to ensure
// the correct frame is used for the sync. The only way mNumFrameAvailable would be
// greater than 0 is if we already ran out of buffers previously. This means we
// need to flush the buffers before proceeding with the sync.
while (mNumFrameAvailable > 0) {
BQA_LOGD("waiting until no queued buffers");
mCallbackCV.wait(_lock);
}
}
}
// add to shadow queue
mNumFrameAvailable++;
if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
acquireAndReleaseBuffer();
}
ATRACE_INT(mQueuedBufferTrace.c_str(),
mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
item.mFrameNumber, boolToString(syncTransactionSet));
if (syncTransactionSet) {
// Add to mSyncedFrameNumbers before waiting in case any buffers are released
// while waiting for a free buffer. The release and commit callback will try to
// acquire buffers if there are any available, but we don't want it to acquire
// in the case where a sync transaction wants the buffer.
mSyncedFrameNumbers.emplace(item.mFrameNumber);
// If there's no available buffer and we're in a sync transaction, we need to wait
// instead of returning since we guarantee a buffer will be acquired for the sync.
SurfaceComposerClient::Transaction* syncTransaction =
mState.syncTransaction.has_value() ? &mState.syncTransaction.value() : nullptr;
while (acquireNextBufferLocked(syncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
BQA_LOGD("waiting for available buffer");
mCallbackCV.wait(_lock);
}
// Only need a commit callback when syncing to ensure the buffer that's synced has been
// sent to SF
mState.syncTransaction
->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
nullptr);
if (mState.acquireSingleBuffer) {
prevCallback = std::move(mState.transactionReadyCallback);
prevTransaction = std::move(mState.syncTransaction);
}
} else if (!waitForTransactionCallback) {
acquireNextBufferLocked(nullptr);
}
}
if (prevCallback) {
callTransactionReadyCallback(*prevCallback, *prevTransaction);
}
}
void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
ALOGV("[%s] onFrameReplaced framenumber=%" PRIu64, mName.c_str(), item.mFrameNumber);
// Do nothing since we are not storing unacquired buffer items locally.
}
void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
std::lock_guard _lock{mTimestampMutex};
mDequeueTimestamps.emplace_or_replace(bufferId, systemTime());
};
void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
std::lock_guard _lock{mTimestampMutex};
mDequeueTimestamps.erase(bufferId);
}
bool BLASTBufferQueue::syncNextTransaction(
std::function<void(SurfaceComposerClient::Transaction*)> callback,
bool acquireSingleBuffer) {
class CallbackWrapper : public gui::BnTransactionReadyCallback {
public:
CallbackWrapper(std::function<void(SurfaceComposerClient::Transaction*)> callback)
: mCallback(callback) {}
binder::Status onTransactionReady(
const SurfaceComposerClient::Transaction& transaction) override {
// Make a local mutable copy of the transaction to send to the client callback
// This is sound from a mutability point of view because BBQ only ever calls
// this callback with a transaction that is going to be dropped after the
// callback anyway.
//
// While the raw pointer looks scary, the contract for this callback is that
// the callee will take ownership of the native pointer and take responsibility
// for eventually deleting it. In practice this involves passing the pointer
// through JNI into a new Java SurfaceControl.Transaction, which will delete
// it upon finalization.
mCallback(new SurfaceComposerClient::Transaction(transaction));
return binder::Status::ok();
}
private:
std::function<void(SurfaceComposerClient::Transaction*)> mCallback;
};
auto wrapper = sp<CallbackWrapper>::make(callback);
return syncNextTransaction(wrapper, acquireSingleBuffer);
}
bool BLASTBufferQueue::syncNextTransaction(sp<gui::ITransactionReadyCallback> callback,
bool acquireSingleBuffer) {
std::lock_guard _lock{mMutex};
return syncNextTransactionLocked(callback, acquireSingleBuffer);
}
bool BLASTBufferQueue::syncNextTransactionLocked(sp<gui::ITransactionReadyCallback> callback,
bool acquireSingleBuffer) {
LOG_ALWAYS_FATAL_IF(!callback,
"BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
"NULL");
BBQ_TRACE();
if (mState.transactionReadyCallback) {
ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
return false;
}
mState.transactionReadyCallback = std::move(callback);
mState.syncTransaction = SurfaceComposerClient::Transaction();
mState.acquireSingleBuffer = acquireSingleBuffer;
return true;
}
binder::Status BLASTBufferQueue::stopContinuousSyncTransaction() {
// We need to maintain the local/host lock order (where mMutex is held for local operations
// but dropped when forwarding to a remote BBQ), but since the locked local body of this method
// would need to drop the mutex to call the transaction ready callback, we cannot use
// forwardOrExecute directly since it holds the mutex for the entire time
sp<gui::IBLASTBufferQueue> remote;
sp<gui::ITransactionReadyCallback> prevCallback;
std::optional<SurfaceComposerClient::Transaction> prevTransaction;
{
std::lock_guard _lock{mMutex};
if (mRemoteBBQ != nullptr) {
remote = mRemoteBBQ;
} else {
if (mState.acquireSingleBuffer || !mState.transactionReadyCallback) {
ALOGW("Attempting to stop continuous sync when none are active");
return binder::Status::ok();
}
prevCallback = std::move(mState.transactionReadyCallback);
prevTransaction = std::move(mState.syncTransaction);
mState.acquireSingleBuffer = true;
}
}
if (remote != nullptr) {
return remote->stopContinuousSyncTransaction();
}
if (prevCallback) {
callTransactionReadyCallback(*prevCallback, *prevTransaction);
}
return binder::Status::ok();
}
void BLASTBufferQueue::clearSyncTransaction() {
std::lock_guard _lock{mMutex};
if (!mState.acquireSingleBuffer) {
ALOGW("Attempting to clear sync transaction when none are active");
return;
}
mState.transactionReadyCallback = nullptr;
mState.syncTransaction = std::nullopt;
}
bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
// Only reject buffers if scaling mode is freeze.
return false;
}
gui::Size bufferSize = getBufferSize(item);
if (mState.requestedSize != mState.size && mState.requestedSize == bufferSize) {
return false;
}
// reject buffers if the buffer size doesn't match.
return mState.size != bufferSize;
}
class BBQSurface : public Surface {
private:
std::mutex mMutex;
sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
bool mDestroyed GUARDED_BY(mMutex) = false;
bool mStarted GUARDED_BY(mMutex) = false;
AsyncWorker mAllocWorker;
std::atomic<pid_t> mAllocWorkerTid{-1};
public:
BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
const sp<IBinder>& scHandle,
std::optional<IGraphicBufferProducer::SurfaceConfig>&& surfaceConfig,
const sp<BLASTBufferQueue>& bbq)
: Surface(igbp, controlledByApp, scHandle, std::move(surfaceConfig)), mBbq(bbq) {}
~BBQSurface() {
if (com_android_graphics_libgui_flags_allocate_buffer_priority_inheritance()) {
mAllocWorker.exitNoFlush();
}
}
void allocateBuffers() override {
ATRACE_CALL();
uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
if (com_android_graphics_libgui_flags_allocate_buffer_priority_inheritance()) {
allocateBuffersCallerPriority(reqWidth, reqHeight);
} else {
allocateBuffersStaticPriority(reqWidth, reqHeight);
}
}
void allocateBuffersStaticPriority(uint32_t reqWidth, uint32_t reqHeight) {
auto gbp = getIGraphicBufferProducer();
std::thread allocateThread([reqWidth, reqHeight, gbp = getIGraphicBufferProducer(),
reqFormat = mReqFormat, reqUsage = mReqUsage]() {
androidSetThreadName("allocateBuffers");
pid_t tid = gettid();
androidSetThreadPriority(tid, ANDROID_PRIORITY_DISPLAY);
gbp->allocateBuffers(reqWidth, reqHeight, reqFormat, reqUsage);
});
allocateThread.detach();
}
void allocateBuffersCallerPriority(uint32_t reqWidth, uint32_t reqHeight) {
std::optional<int> callerPriority;
std::optional<pid_t> workerTid = ensureWorkerStarted();
int callerScheduler = sched_getscheduler(0);
switch (callerScheduler & ~SCHED_RESET_ON_FORK) {
// For fair policies, we can set worker thread's priority
// to the caller thread's priority.
case SCHED_OTHER: // i.e. SCHED_NORMAL
case SCHED_BATCH:
case SCHED_EXT:
callerPriority = androidGetThreadPriority(gettid());
break;
// For realtime policies, this process doesn't necessarily have
// the capability to switch the worker thread to a realtime
// policy. As such, just use the highest generic priority.
case SCHED_FIFO:
case SCHED_RR:
case SCHED_DEADLINE:
callerPriority = -10; // Process.THREAD_PRIORITY_TOP_APP_BOOST
break;
// Priority doesn't matter for SCHED_IDLE.
case SCHED_IDLE:
break;
default:
ALOGW("Unknown scheduling class %d", callerScheduler);
}
// If the allocation thread is already running, set its priority here so that the
// scheduler has the right priority when we wake it up. If the allocation thread
// hasn't finished starting yet, the best we can do is have the allocation thread
// update its own priority. Note that in that case, it probably inherited the
// correct priority anyway - unless the calling thread had SCHED_RESET_ON_FORK.
if (callerPriority.has_value() && workerTid.has_value()) {
androidSetThreadPriority(*workerTid, *callerPriority);
}
auto gbp = getIGraphicBufferProducer();
mAllocWorker.post([reqWidth, reqHeight, gbp = getIGraphicBufferProducer(),
reqFormat = mReqFormat, reqUsage = mReqUsage, workerTid,
callerPriority]() {
if (callerPriority.has_value() && !workerTid.has_value()) {
androidSetThreadPriority(gettid(), *callerPriority);
}
gbp->allocateBuffers(reqWidth, reqHeight, reqFormat, reqUsage);
});
}
std::optional<pid_t> ensureWorkerStarted() {
std::lock_guard _lock{mMutex};
if (!mStarted) {
mStarted = true;
mAllocWorker.post([this] {
androidSetThreadName("allocateBuffers");
mAllocWorkerTid.store(gettid(), std::memory_order_relaxed);
});
return std::nullopt;
}
pid_t workerTid = mAllocWorkerTid.load(std::memory_order_relaxed);
return workerTid != -1 ? std::optional(workerTid) : std::nullopt;
}
status_t setFrameTimelineInfo(uint64_t frameNumber,
const FrameTimelineInfo& frameTimelineInfo) override {
std::lock_guard _lock{mMutex};
if (mDestroyed) {
return DEAD_OBJECT;
}
return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
}
void destroy() override {
Surface::destroy();
std::lock_guard _lock{mMutex};
mDestroyed = true;
mBbq = nullptr;
}
};
// TODO: Can we coalesce this with frame updates? Need to confirm
// no timing issues.
status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
bool shouldBeSeamless) {
std::lock_guard _lock{mMutex};
SurfaceComposerClient::Transaction t;
return t.setFrameRate(mState.surfaceControl, frameRate, compatibility, shouldBeSeamless)
.apply();
}
status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
const FrameTimelineInfo& frameTimelineInfo) {
ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
frameNumber, frameTimelineInfo.vsyncId);
std::lock_guard _lock{mMutex};
mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
return OK;
}
void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
std::lock_guard _lock{mMutex};
SurfaceComposerClient::Transaction t;
t.setSidebandStream(mState.surfaceControl, stream).apply();
}
sp<Surface> BLASTBufferQueue::getSurfaceLocked(
bool includeSurfaceControlHandle,
std::optional<IGraphicBufferProducer::SurfaceConfig>&& surfaceConfig) {
sp<IBinder> scHandle = nullptr;
if (includeSurfaceControlHandle && mState.surfaceControl) {
scHandle = mState.surfaceControl->getHandle();
}
return sp<BBQSurface>::make(mProducer, true, scHandle, std::move(surfaceConfig),
sp<BLASTBufferQueue>::fromExisting(this));
}
sp<Surface> BLASTBufferQueue::getSurface(
bool includeSurfaceControlHandle,
std::optional<IGraphicBufferProducer::SurfaceConfig>&& surfaceConfig) {
std::lock_guard _lock{mMutex};
return getSurfaceLocked(includeSurfaceControlHandle, std::move(surfaceConfig));
}
void BLASTBufferQueue::mergeWithNextTransactionLocked(SurfaceComposerClient::Transaction* t,
uint64_t frameNumber) {
if (mLastAcquiredFrameNumber >= frameNumber) {
// Apply the transaction since we have already acquired the desired frame.
t->setApplyToken(mState.applyToken).apply();
} else {
mPendingTransactions.emplace_back(frameNumber, *t);
// Clear the transaction so it can't be applied elsewhere.
t->clear();
}
}
void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
uint64_t frameNumber) {
std::lock_guard _lock{mMutex};
mergeWithNextTransactionLocked(t, frameNumber);
}
void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
std::lock_guard _lock{mMutex};
SurfaceComposerClient::Transaction t;
mergePendingTransactions(&t, frameNumber);
// All transactions on our apply token are one-way. See comment on mLastAppliedFrameNumber
t.setApplyToken(mState.applyToken).apply(false, true);
}
void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
uint64_t frameNumber) {
auto mergeTransaction =
[&t, currentFrameNumber = frameNumber](
std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
auto& [targetFrameNumber, transaction] = pendingTransaction;
if (currentFrameNumber < targetFrameNumber) {
return false;
}
t->merge(std::move(transaction));
return true;
};
mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
mPendingTransactions.end(), mergeTransaction),
mPendingTransactions.end());
}
SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
uint64_t frameNumber) {
std::lock_guard _lock{mMutex};
SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
mergePendingTransactions(t, frameNumber);
return t;
}
// Per-process AsyncWorker that emulates a single 'binder thread'.
class AsyncProducerListenerWorker : public AsyncWorker,
public Singleton<AsyncProducerListenerWorker> {};
ANDROID_SINGLETON_STATIC_INSTANCE(AsyncProducerListenerWorker);
// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
class AsyncProducerListener : public BnProducerListener {
private:
const sp<IProducerListener> mListener;
AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
friend class sp<AsyncProducerListener>;
public:
bool needsAcquiredNotify() override { return mListener->needsAcquiredNotify(); }
bool needsDroppedNotify() override { return mListener->needsDroppedNotify(); }
void onBufferReleased() override {
AsyncProducerListenerWorker::getInstance().post(
[listener = mListener]() { listener->onBufferReleased(); });
}
void onBuffersDiscarded(const std::vector<int32_t>& slots,
const std::vector<uint64_t>& bufferIds) override {
AsyncProducerListenerWorker::getInstance().post(
[listener = mListener, slots = slots, bufferIds = bufferIds]() {
listener->onBuffersDiscarded(slots, bufferIds);
});
}
void onBufferDetached(int slot, uint64_t bufferId) override {
AsyncProducerListenerWorker::getInstance().post(
[listener = mListener, slot = slot, bufferId = bufferId]() {
listener->onBufferDetached(slot, bufferId);
});
}
void onBufferAcquired(uint64_t bufferId, uint64_t frameNumber) override {
AsyncProducerListenerWorker::getInstance().post(
[listener = mListener, bufferId = bufferId, frameNumber = frameNumber]() {
listener->onBufferAcquired(bufferId, frameNumber);
});
};
void onBufferDropped(uint64_t bufferId, uint64_t frameNumber) override {
AsyncProducerListenerWorker::getInstance().post(
[listener = mListener, bufferId = bufferId, frameNumber = frameNumber]() {
listener->onBufferDropped(bufferId, frameNumber);
});
};
void onBufferAttached() override {
AsyncProducerListenerWorker::getInstance().post(
[listener = mListener]() { listener->onBufferAttached(); });
}
};
// BufferReleaseReader is used to do blocking but interruptible reads from the buffer
// release channel. To implement this, BufferReleaseReader owns an epoll file descriptor that
// is configured to wake up when either the BufferReleaseReader::ConsumerEndpoint or an eventfd
// becomes readable. Interrupts are necessary because a free buffer may become available for
// reasons other than a buffer release from the producer.
class BufferReleaseReader {
public:
explicit BufferReleaseReader(std::unique_ptr<gui::BufferReleaseChannel::ConsumerEndpoint>);
BufferReleaseReader(const BufferReleaseReader&) = delete;
BufferReleaseReader& operator=(const BufferReleaseReader&) = delete;
// Block until we can read a buffer release message.
//
// Returns:
// * OK if a ReleaseCallbackId and Fence were successfully read.
// * WOULD_BLOCK if the blocking read was interrupted by interruptBlockingRead.
// * TIMED_OUT if the blocking read timed out.
// * UNKNOWN_ERROR if something went wrong.
status_t readBlocking(ReleaseCallbackId& outId, sp<Fence>& outReleaseFence,
uint32_t& outMaxAcquiredBufferCount, nsecs_t timeout);
status_t readNonBlocking(ReleaseCallbackId& outId, sp<Fence>& outReleaseFence,
uint32_t& outMaxAcquiredBufferCount);
void interruptBlockingRead();
void clearInterrupts();
private:
std::unique_ptr<gui::BufferReleaseChannel::ConsumerEndpoint> mConsumerEndpoint;
android::base::unique_fd mEpollFd;
android::base::unique_fd mEventFd;
};
class BBQBufferQueueCore : public BufferQueueCore {
public:
explicit BBQBufferQueueCore(std::shared_ptr<BufferReleaseReader> bufferReleaseReader)
: mBufferReleaseReader{std::move(bufferReleaseReader)} {}
void notifyBufferReleased() const override { mBufferReleaseReader->interruptBlockingRead(); }
private:
std::shared_ptr<BufferReleaseReader> mBufferReleaseReader;
};
// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
// can be non-blocking when the producer is in the client process.
class BBQBufferQueueProducer : public BufferQueueProducer {
public:
BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq,
std::shared_ptr<BufferReleaseReader> bufferReleaseReader)
: BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
mBLASTBufferQueue(bbq),
mBufferReleaseReader(std::move(bufferReleaseReader)) {}
status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
QueueBufferOutput* output) override {
if (!listener) {
return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
}
return BufferQueueProducer::connect(sp<AsyncProducerListener>::make(listener), api,
producerControlledByApp, output);
}
// We want to resize the frame history when changing the size of the buffer queue
status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
int maxBufferCount;
if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
&maxBufferCount);
status != OK) {
return status;
}
sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
if (!bbq) {
return OK;
}
// if we can't determine the max buffer count, then just skip growing the history size
size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
// optimize away resizing the frame history unless it will grow
if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
ALOGV("increasing frame history size to %zu", newFrameHistorySize);
bbq->resizeFrameEventHistory(newFrameHistorySize);
}
return OK;
}
int query(int what, int* value) override {
if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
*value = 1;
return OK;
}
return BufferQueueProducer::query(what, value);
}
status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
nsecs_t timeout) const override {
ATRACE_CALL();
const auto startTime = std::chrono::steady_clock::now();
// BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
// we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
// we don't miss an interrupt.
mBufferReleaseReader->clearInterrupts();
UnlockGuard unlockGuard{bufferQueueLock};
ReleaseCallbackId id;
sp<Fence> fence;
uint32_t maxAcquiredBufferCount;
status_t status =
mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
if (status == TIMED_OUT) {
return TIMED_OUT;
} else if (status != OK) {
// Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
// have a free buffer and call this method again if not.
return OK;
}
sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
if (!bbq) {
return OK;
}
bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
const nsecs_t durationNanos = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - startTime)
.count();
// Provide a callback for Choreographer to start buffer stuffing recovery when blocked
// on buffer release.
std::function<void(const nsecs_t)> callbackCopy = bbq->getWaitForBufferReleaseCallback();
if (callbackCopy) callbackCopy(durationNanos);
return OK;
}
private:
const wp<BLASTBufferQueue> mBLASTBufferQueue;
std::shared_ptr<BufferReleaseReader> mBufferReleaseReader;
};
// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
// we can deadlock.
void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
sp<IGraphicBufferConsumer>* outConsumer) {
LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
std::unique_ptr<gui::BufferReleaseChannel::ConsumerEndpoint> bufferReleaseConsumer;
gui::BufferReleaseChannel::open(mName, bufferReleaseConsumer, mBufferReleaseProducer);
mBufferReleaseReader = std::make_shared<BufferReleaseReader>(std::move(bufferReleaseConsumer));
auto core = sp<BBQBufferQueueCore>::make(mBufferReleaseReader);
LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
auto producer = sp<BBQBufferQueueProducer>::make(core, wp<BLASTBufferQueue>::fromExisting(this),
mBufferReleaseReader);
LOG_ALWAYS_FATAL_IF(producer == nullptr,
"BLASTBufferQueue: failed to create BBQBufferQueueProducer");
auto consumer = sp<BufferQueueConsumer>::make(core);
consumer->setAllowExtraAcquire(true);
LOG_ALWAYS_FATAL_IF(consumer == nullptr,
"BLASTBufferQueue: failed to create BufferQueueConsumer");
*outProducer = producer;
*outConsumer = consumer;
}
void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
// This can be null during creation of the buffer queue, but resizing won't do anything at that
// point in time, so just ignore. This can go away once the class relationships and lifetimes of
// objects are cleaned up with a major refactor of BufferQueue as a whole.
if (mBufferItemConsumer != nullptr) {
mBufferItemConsumer->resizeFrameEventHistory(newSize);
}
}
PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
PixelFormat convertedFormat = format;
switch (format) {
case PIXEL_FORMAT_TRANSPARENT:
case PIXEL_FORMAT_TRANSLUCENT:
convertedFormat = PIXEL_FORMAT_RGBA_8888;
break;
case PIXEL_FORMAT_OPAQUE:
convertedFormat = PIXEL_FORMAT_RGBX_8888;
break;
}
return convertedFormat;
}
uint32_t BLASTBufferQueue::getLastTransformHint() const {
std::lock_guard _lock{mMutex};
if (mState.surfaceControl) {
return mState.surfaceControl->getTransformHint();
} else {
return 0;
}
}
uint64_t BLASTBufferQueue::getLastAcquiredFrameNumLocked() {
return mLastAcquiredFrameNumber;
}
uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
std::lock_guard _lock{mMutex};
return getLastAcquiredFrameNumLocked();
}
bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
std::lock_guard _lock{mMutex};
return SurfaceControl::isSameSurface(mState.surfaceControl, surfaceControl);
}
void BLASTBufferQueue::setTransactionHangCallback(sp<gui::ITransactionHangCallback> callback) {
std::lock_guard _lock{mMutex};
mState.transactionHangCallback = std::move(callback);
}
void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
std::lock_guard _lock{mMutex};
mState.applyToken = std::move(applyToken);
}
void BLASTBufferQueue::setCornerRadiiCallback(
std::function<void(const gui::CornerRadii)> callback) {
std::lock_guard _lock{mCornerRadiiCallbackMutex};
mCornerRadiiCallback = std::move(callback);
}
std::function<void(const gui::CornerRadii)> BLASTBufferQueue::getCornerRadiiCallback() const {
std::lock_guard _lock{mCornerRadiiCallbackMutex};
return mCornerRadiiCallback;
}
void BLASTBufferQueue::setWaitForBufferReleaseCallback(
std::function<void(const nsecs_t)> callback) {
std::lock_guard _lock{mWaitForBufferReleaseMutex};
mWaitForBufferReleaseCallback = std::move(callback);
}
std::function<void(const nsecs_t)> BLASTBufferQueue::getWaitForBufferReleaseCallback() const {
std::lock_guard _lock{mWaitForBufferReleaseMutex};
return mWaitForBufferReleaseCallback;
}
void BLASTBufferQueue::updateBufferReleaseProducer() {
if (!mState.surfaceControl) {
return;
}
// SELinux policy may prevent this process from sending the BufferReleaseChannel's file
// descriptor to SurfaceFlinger, causing the entire transaction to be dropped. We send this
// transaction independently of any other updates to ensure those updates aren't lost.
SurfaceComposerClient::Transaction()
.setApplyToken(mState.applyToken)
.setBufferReleaseChannel(mState.surfaceControl, mBufferReleaseProducer)
.apply(false /* synchronous */, true /* oneWay */);
}
void BLASTBufferQueue::drainBufferReleaseConsumer() {
std::lock_guard _lock{mMutex};
drainBufferReleaseConsumerLocked();
}
void BLASTBufferQueue::drainBufferReleaseConsumerLocked() {
ATRACE_CALL();
while (true) {
ReleaseCallbackId id;
sp<Fence> fence;
uint32_t maxAcquiredBufferCount;
status_t status = mBufferReleaseReader->readNonBlocking(id, fence, maxAcquiredBufferCount);
if (status != OK) {
return;
}
releaseBufferCallbackLocked(id, fence, maxAcquiredBufferCount, false /* fakeRelease */);
}
}
void BLASTBufferQueue::callTransactionHangCallback(gui::ITransactionHangCallback& callback,
const std::string& reason) {
performOnJVMAttachedThread([&]() { callback.onTransactionHang(String16(reason.c_str())); });
}
void BLASTBufferQueue::callTransactionReadyCallback(gui::ITransactionReadyCallback& callback,
const SurfaceComposerClient::Transaction& t) {
performOnJVMAttachedThread([&]() { callback.onTransactionReady(t); });
}
BufferReleaseReader::BufferReleaseReader(
std::unique_ptr<gui::BufferReleaseChannel::ConsumerEndpoint> consumerEndpoint)
: mConsumerEndpoint{std::move(consumerEndpoint)} {
mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
"Failed to create buffer release epoll file descriptor. errno=%d "
"message='%s'",
errno, strerror(errno));
epoll_event registerEndpointFd{};
registerEndpointFd.events = EPOLLIN;
registerEndpointFd.data.fd = mConsumerEndpoint->getFd();
status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mConsumerEndpoint->getFd(),
&registerEndpointFd);
LOG_ALWAYS_FATAL_IF(status == -1,
"Failed to register buffer release consumer file descriptor with epoll. "
"errno=%d message='%s'",
errno, strerror(errno));
mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
"Failed to create buffer release event file descriptor. errno=%d "
"message='%s'",
errno, strerror(errno));
epoll_event registerEventFd{};
registerEventFd.events = EPOLLIN;
registerEventFd.data.fd = mEventFd.get();
status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
LOG_ALWAYS_FATAL_IF(status == -1,
"Failed to register buffer release event file descriptor with epoll. "
"errno=%d message='%s'",
errno, strerror(errno));
}
status_t BufferReleaseReader::readBlocking(ReleaseCallbackId& outId, sp<Fence>& outFence,
uint32_t& outMaxAcquiredBufferCount, nsecs_t timeout) {
// TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
// 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
// millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
// precision.
int timeoutMs = -1;
if (timeout == 0) {
timeoutMs = 0;
} else if (timeout > 0) {
const int nsPerMs = 1000000;
if (timeout < nsPerMs) {
timeoutMs = 1;
} else {
timeoutMs = static_cast<int>(
std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
.count());
}
}
epoll_event event{};
int eventCount;
do {
eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
} while (eventCount == -1 && errno == EINTR);
if (eventCount == -1) {
ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
strerror(errno));
return UNKNOWN_ERROR;
}
if (eventCount == 0) {
return TIMED_OUT;
}
if (event.data.fd == mEventFd.get()) {
clearInterrupts();
return WOULD_BLOCK;
}
return mConsumerEndpoint->readReleaseFence(outId, outFence, outMaxAcquiredBufferCount);
}
status_t BufferReleaseReader::readNonBlocking(ReleaseCallbackId& outId, sp<Fence>& outFence,
uint32_t& outMaxAcquiredBufferCount) {
return mConsumerEndpoint->readReleaseFence(outId, outFence, outMaxAcquiredBufferCount);
}
void BufferReleaseReader::interruptBlockingRead() {
if (eventfd_write(mEventFd.get(), 1) == -1) {
ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
}
}
void BufferReleaseReader::clearInterrupts() {
eventfd_t value;
if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
}
}
} // namespace android