blob: 40656ff62a1da9c1294961828126b99bf892b18f [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, 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//#define LOG_NDEBUG 0
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
Arun Johnson326166e2023-07-28 19:11:52 +000028#include <thread>
29#include <chrono>
Pawin Vongmasa36653902018-11-15 00:10:25 -080030
31#include <C2AllocatorGralloc.h>
32#include <C2PlatformSupport.h>
33#include <C2BlockInternal.h>
34#include <C2Config.h>
35#include <C2Debug.h>
36
37#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070038#include <android/hardware/drm/1.0/types.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070039#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080040#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080042#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070044#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070046#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047#include <media/openmax/OMX_Core.h>
48#include <media/stagefright/foundation/ABuffer.h>
49#include <media/stagefright/foundation/ALookup.h>
50#include <media/stagefright/foundation/AMessage.h>
51#include <media/stagefright/foundation/AUtils.h>
52#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070054#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010055#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080056#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070057#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070058#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080059#include <system/window.h>
60
61#include "CCodecBufferChannel.h"
62#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080063
64namespace android {
65
66using android::base::StringPrintf;
67using hardware::hidl_handle;
68using hardware::hidl_string;
69using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070070using hardware::fromHeap;
71using hardware::HidlMemory;
Brian Lindahld7967a92023-08-10 10:12:49 -060072using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070073
Pawin Vongmasa36653902018-11-15 00:10:25 -080074using namespace hardware::cas::V1_0;
75using namespace hardware::cas::native::V1_0;
76
77using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070078using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080079
Pawin Vongmasa36653902018-11-15 00:10:25 -080080namespace {
81
Wonsik Kim469c8342019-04-11 16:46:09 -070082constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080083
Sungtak Leeab6f2f32019-02-15 14:43:51 -080084// This is for keeping IGBP's buffer dropping logic in legacy mode other
85// than making it non-blocking. Do not change this value.
86const static size_t kDequeueTimeoutNs = 0;
87
Brian Lindahld7967a92023-08-10 10:12:49 -060088static bool areRenderMetricsEnabled() {
89 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
90 return v == "true";
91}
92
Arun Johnsonf4a81f72023-11-09 21:22:48 +000093// Flags can come with individual BufferInfos
94// when used with large frame audio
95constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList = {
96 {BUFFER_FLAG_CODEC_CONFIG, C2FrameData::FLAG_CODEC_CONFIG},
97 {BUFFER_FLAG_END_OF_STREAM, C2FrameData::FLAG_END_OF_STREAM},
98 {BUFFER_FLAG_DECODE_ONLY, C2FrameData::FLAG_DROP_FRAME}
99};
100
101static uint32_t convertFlags(uint32_t flags, bool toC2) {
102 return std::transform_reduce(
103 flagList.begin(), flagList.end(),
104 0u,
105 std::bit_or{},
106 [flags, toC2](const std::pair<uint32_t, uint32_t> &entry) {
107 if (toC2) {
108 return (flags & entry.first) ? entry.second : 0;
109 } else {
110 return (flags & entry.second) ? entry.first : 0;
111 }
112 });
113}
114
Pawin Vongmasa36653902018-11-15 00:10:25 -0800115} // namespace
116
117CCodecBufferChannel::QueueGuard::QueueGuard(
118 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
119 Mutex::Autolock l(mSync.mGuardLock);
120 // At this point it's guaranteed that mSync is not under state transition,
121 // as we are holding its mutex.
122
123 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
124 if (count->value == -1) {
125 mRunning = false;
126 } else {
127 ++count->value;
128 mRunning = true;
129 }
130}
131
132CCodecBufferChannel::QueueGuard::~QueueGuard() {
133 if (mRunning) {
134 // We are not holding mGuardLock at this point so that QueueSync::stop() can
135 // keep holding the lock until mCount reaches zero.
136 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
137 --count->value;
138 count->cond.broadcast();
139 }
140}
141
142void CCodecBufferChannel::QueueSync::start() {
143 Mutex::Autolock l(mGuardLock);
144 // If stopped, it goes to running state; otherwise no-op.
145 Mutexed<Counter>::Locked count(mCount);
146 if (count->value == -1) {
147 count->value = 0;
148 }
149}
150
151void CCodecBufferChannel::QueueSync::stop() {
152 Mutex::Autolock l(mGuardLock);
153 Mutexed<Counter>::Locked count(mCount);
154 if (count->value == -1) {
155 // no-op
156 return;
157 }
158 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
159 // mCount can only decrement. In other words, threads that acquired the lock
160 // are allowed to finish execution but additional threads trying to acquire
161 // the lock at this point will block, and then get QueueGuard at STOPPED
162 // state.
163 while (count->value != 0) {
164 count.waitForCondition(count->cond);
165 }
166 count->value = -1;
167}
168
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700169// Input
170
171CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
172
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173// CCodecBufferChannel
174
175CCodecBufferChannel::CCodecBufferChannel(
176 const std::shared_ptr<CCodecCallback> &callback)
177 : mHeapSeqNum(-1),
178 mCCodecCallback(callback),
179 mFrameIndex(0u),
180 mFirstValidFrameIndex(0u),
Brian Lindahld7967a92023-08-10 10:12:49 -0600181 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600182 mIsSurfaceToDisplay(false),
183 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700184 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800185 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700186 mInputMetEos(false),
187 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700188 {
189 Mutexed<Input>::Locked input(mInput);
190 input->buffers.reset(new DummyInputBuffers(""));
191 input->extraBuffers.flush();
192 input->inputDelay = 0u;
193 input->pipelineDelay = 0u;
194 input->numSlots = kSmoothnessFactor;
195 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700196 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700197 }
198 {
199 Mutexed<Output>::Locked output(mOutput);
200 output->outputDelay = 0u;
201 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700202 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700203 }
David Stevensc3fbb282021-01-18 18:11:20 +0900204 {
205 Mutexed<BlockPools>::Locked pools(mBlockPools);
206 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
207 }
Brian Lindahld7967a92023-08-10 10:12:49 -0600208 std::string value = GetServerConfigurableFlag("media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700209 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700210 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800211}
212
213CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800214 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800215 mCrypto->unsetHeap(mHeapSeqNum);
216 }
217}
218
219void CCodecBufferChannel::setComponent(
220 const std::shared_ptr<Codec2Client::Component> &component) {
221 mComponent = component;
222 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
223 mName = mComponentName.c_str();
224}
225
226status_t CCodecBufferChannel::setInputSurface(
227 const std::shared_ptr<InputSurfaceWrapper> &surface) {
228 ALOGV("[%s] setInputSurface", mName);
229 mInputSurface = surface;
230 return mInputSurface->connect(mComponent);
231}
232
233status_t CCodecBufferChannel::signalEndOfInputStream() {
234 if (mInputSurface == nullptr) {
235 return INVALID_OPERATION;
236 }
237 return mInputSurface->signalEndOfInputStream();
238}
239
Sungtak Lee04b30352020-07-27 13:57:25 -0700240status_t CCodecBufferChannel::queueInputBufferInternal(
241 sp<MediaCodecBuffer> buffer,
242 std::shared_ptr<C2LinearBlock> encryptedBlock,
243 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800244 int64_t timeUs;
245 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
246
247 if (mInputMetEos) {
248 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
249 return OK;
250 }
251
252 int32_t flags = 0;
253 int32_t tmp = 0;
254 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200255 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800256 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
257 eos = true;
258 mInputMetEos = true;
259 ALOGV("[%s] input EOS", mName);
260 }
261 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
262 flags |= C2FrameData::FLAG_CODEC_CONFIG;
263 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200264 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
265 tunnelFirstFrame = true;
266 }
Marc Kassis96343b42022-12-09 11:49:44 +0100267 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
268 flags |= C2FrameData::FLAG_DROP_FRAME;
269 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000270 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu time: %lld",
271 mName, buffer->size(), (long long)timeUs);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800272 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800273 std::unique_ptr<C2Work> work(new C2Work);
274 work->input.ordinal.timestamp = timeUs;
275 work->input.ordinal.frameIndex = mFrameIndex++;
276 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
277 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
278 // Keep client timestamp in customOrdinal
279 work->input.ordinal.customOrdinal = timeUs;
280 work->input.buffers.clear();
281
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700282 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800283 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800284
Pawin Vongmasa36653902018-11-15 00:10:25 -0800285 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700286 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800287 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700288 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800289 return -ENOENT;
290 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700291 // TODO: we want to delay copying buffers.
292 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
293 copy = input->buffers->cloneAndReleaseBuffer(buffer);
294 if (copy != nullptr) {
295 (void)input->extraBuffers.assignSlot(copy);
296 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
297 return UNKNOWN_ERROR;
298 }
299 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
300 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
301 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700302 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700303 } else {
304 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
305 "buffer starvation on component.", mName);
306 }
307 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800308 if (input->frameReassembler) {
309 usesFrameReassembler = true;
310 input->frameReassembler.process(buffer, &items);
311 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900312 int32_t cvo = 0;
313 if (buffer->meta()->findInt32("cvo", &cvo)) {
314 int32_t rotation = cvo % 360;
315 // change rotation to counter-clock wise.
316 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
317
318 Mutexed<OutputSurface>::Locked output(mOutputSurface);
319 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
320 output->rotation[frameIndex] = rotation;
321 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000322 sp<RefBase> obj;
323 if (buffer->meta()->findObject("accessUnitInfo", &obj)) {
324 ALOGV("Filling C2Info from multiple access units");
325 sp<WrapperObject<std::vector<AccessUnitInfo>>> infos{
326 (decltype(infos.get()))obj.get()};
327 std::vector<AccessUnitInfo> &accessUnitInfoVec = infos->value;
328 std::vector<C2AccessUnitInfosStruct> multipleAccessUnitInfos;
329 uint32_t outFlags = 0;
330 for (int i = 0; i < accessUnitInfoVec.size(); i++) {
331 outFlags = 0;
332 outFlags = convertFlags(accessUnitInfoVec[i].mFlags, true);
333 if (eos && (outFlags & C2FrameData::FLAG_END_OF_STREAM)) {
334 outFlags &= (~C2FrameData::FLAG_END_OF_STREAM);
335 }
336 multipleAccessUnitInfos.emplace_back(
337 outFlags,
338 accessUnitInfoVec[i].mSize,
339 accessUnitInfoVec[i].mTimestamp);
340 ALOGV("%d) flags: %d, size: %d, time: %llu",
341 i, outFlags, accessUnitInfoVec[i].mSize,
342 (long long)accessUnitInfoVec[i].mTimestamp);
343
344 }
345 const std::shared_ptr<C2AccessUnitInfos::input> c2AccessUnitInfos =
346 C2AccessUnitInfos::input::AllocShared(
347 multipleAccessUnitInfos.size(), 0u, multipleAccessUnitInfos);
348 c2buffer->setInfo(c2AccessUnitInfos);
349 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800350 work->input.buffers.push_back(c2buffer);
351 if (encryptedBlock) {
352 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
353 kParamIndexEncryptedBuffer,
354 encryptedBlock->share(0, blockSize, C2Fence())));
355 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700356 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800357 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700358 Mutexed<Input>::Locked input(mInput);
359 if (input->frameReassembler) {
360 usesFrameReassembler = true;
361 // drain any pending items with eos
362 input->frameReassembler.process(buffer, &items);
363 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800364 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800365 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800366 if (usesFrameReassembler) {
367 if (!items.empty()) {
368 items.front()->input.configUpdate = std::move(mParamsToBeSet);
369 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
370 }
371 } else {
372 work->input.flags = (C2FrameData::flags_t)flags;
373 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800374
Wonsik Kime1104ca2020-11-24 15:01:33 -0800375 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200376 if (tunnelFirstFrame) {
377 C2StreamTunnelHoldRender::input tunnelHoldRender{
378 0u /* stream */,
379 C2_TRUE /* value */
380 };
381 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
382 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800383 work->worklets.clear();
384 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800385
Wonsik Kime1104ca2020-11-24 15:01:33 -0800386 items.push_back(std::move(work));
387
388 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800389 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800390 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800391 work.reset(new C2Work);
392 work->input.ordinal.timestamp = timeUs;
393 work->input.ordinal.frameIndex = mFrameIndex++;
394 // WORKAROUND: keep client timestamp in customOrdinal
395 work->input.ordinal.customOrdinal = timeUs;
396 work->input.buffers.clear();
397 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800398 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800399 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800400 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800401 c2_status_t err = C2_OK;
402 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700403 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
404 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800405 {
406 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
407 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
408 for (const std::unique_ptr<C2Work> &work : items) {
409 watcher->onWorkQueued(
410 work->input.ordinal.frameIndex.peeku(),
411 std::vector(work->input.buffers),
412 now);
413 }
414 }
415 err = mComponent->queue(&items);
416 }
417 if (err != C2_OK) {
418 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
419 for (const std::unique_ptr<C2Work> &work : items) {
420 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
421 }
422 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700423 Mutexed<Input>::Locked input(mInput);
424 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700425 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700426 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700427 } else if (buffer) {
428 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700429 }
430 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
431 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800432 }
433
434 feedInputBufferIfAvailableInternal();
435 return err;
436}
437
438status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
439 QueueGuard guard(mSync);
440 if (!guard.isRunning()) {
441 ALOGD("[%s] setParameters is only supported in the running state.", mName);
442 return -ENOSYS;
443 }
444 mParamsToBeSet.insert(mParamsToBeSet.end(),
445 std::make_move_iterator(params.begin()),
446 std::make_move_iterator(params.end()));
447 params.clear();
448 return OK;
449}
450
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800451status_t CCodecBufferChannel::attachBuffer(
452 const std::shared_ptr<C2Buffer> &c2Buffer,
453 const sp<MediaCodecBuffer> &buffer) {
454 if (!buffer->copy(c2Buffer)) {
455 return -ENOSYS;
456 }
457 return OK;
458}
459
460void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
461 if (!mDecryptDestination || mDecryptDestination->size() < size) {
462 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
463 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
464 mCrypto->unsetHeap(mHeapSeqNum);
465 }
466 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
467 if (mCrypto) {
468 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
469 }
470 }
471}
472
473int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
474 CHECK(mCrypto);
475 auto it = mHeapSeqNumMap.find(memory);
476 int32_t heapSeqNum = -1;
477 if (it == mHeapSeqNumMap.end()) {
478 heapSeqNum = mCrypto->setHeap(memory);
479 mHeapSeqNumMap.emplace(memory, heapSeqNum);
480 } else {
481 heapSeqNum = it->second;
482 }
483 return heapSeqNum;
484}
485
Arun Johnson564f3a92024-02-01 19:09:45 +0000486typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
487typedef WrapperObject<std::vector<std::unique_ptr<CodecCryptoInfo>>> CryptoInfosWrapper;
488status_t CCodecBufferChannel::attachEncryptedBuffers(
489 const sp<hardware::HidlMemory> &memory,
490 size_t offset,
491 const sp<MediaCodecBuffer> &buffer,
492 bool secure,
493 AString* errorDetailMsg) {
494 static const C2MemoryUsage kDefaultReadWriteUsage{
495 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
496 if (!hasCryptoOrDescrambler()) {
497 ALOGE("attachEncryptedBuffers requires Crypto/descrambler object");
498 return -ENOSYS;
499 }
500 size_t size = 0;
501 CHECK(buffer->meta()->findSize("ssize", &size));
502 if (size == 0) {
503 buffer->setRange(0, 0);
504 return OK;
505 }
506 sp<RefBase> obj;
507 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
508 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
509 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
510 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
511 if (secure || (mCrypto == nullptr)) {
512 if (cryptoInfos->value.size() != 1) {
513 ALOGE("Cannot decrypt multiple access units");
514 return -ENOSYS;
515 }
516 // we are dealing with just one cryptoInfo or descrambler.
517 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
518 if (info == nullptr) {
519 ALOGE("Cannot decrypt, CryptoInfos are null.");
520 return -ENOSYS;
521 }
522 return attachEncryptedBuffer(
523 memory,
524 secure,
525 info->mKey,
526 info->mIv,
527 info->mMode,
528 info->mPattern,
529 offset,
530 info->mSubSamples,
531 info->mNumSubSamples,
532 buffer,
533 errorDetailMsg);
534 }
535 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
536 std::shared_ptr<C2LinearBlock> block;
537 c2_status_t err = pool->fetchLinearBlock(
538 size,
539 kDefaultReadWriteUsage,
540 &block);
541 if (err != C2_OK) {
542 ALOGI("[%s] attachEncryptedBuffers: fetchLinearBlock failed: size = %zu (%s) err = %d",
543 mName, size, secure ? "secure" : "non-secure", err);
544 return NO_MEMORY;
545 }
546 ensureDecryptDestination(size);
547 C2WriteView wView = block->map().get();
548 if (wView.error() != C2_OK) {
549 ALOGI("[%s] attachEncryptedBuffers: block map error: %d (non-secure)",
550 mName, wView.error());
551 return UNKNOWN_ERROR;
552 }
553
554 ssize_t result = -1;
555 ssize_t codecDataOffset = 0;
556 size_t inBufferOffset = 0;
557 size_t outBufferSize = 0;
558 uint32_t cryptoInfoIdx = 0;
559 int32_t heapSeqNum = getHeapSeqNum(memory);
560 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
561 hardware::drm::V1_0::DestinationBuffer dst;
562 dst.type = DrmBufferType::SHARED_MEMORY;
563 IMemoryToSharedBuffer(
564 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
565 for (int i = 0; i < bufferInfos->value.size(); i++) {
566 if (bufferInfos->value[i].mSize > 0) {
567 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[cryptoInfoIdx++]);
568 result = mCrypto->decrypt(
569 (uint8_t*)info->mKey,
570 (uint8_t*)info->mIv,
571 info->mMode,
572 info->mPattern,
573 src,
574 inBufferOffset,
575 info->mSubSamples,
576 info->mNumSubSamples,
577 dst,
578 errorDetailMsg);
579 inBufferOffset += bufferInfos->value[i].mSize;
580 if (result < 0) {
581 ALOGI("[%s] attachEncryptedBuffers: decrypt failed: result = %zd",
582 mName, result);
583 return result;
584 }
585 if (wView.error() == C2_OK) {
586 if (wView.size() < result) {
587 ALOGI("[%s] attachEncryptedBuffers: block size too small:"
588 "size=%u result=%zd (non-secure)", mName, wView.size(), result);
589 return UNKNOWN_ERROR;
590 }
591 memcpy(wView.data(), mDecryptDestination->unsecurePointer(), result);
592 bufferInfos->value[i].mSize = result;
593 wView.setOffset(wView.offset() + result);
594 }
595 outBufferSize += result;
596 }
597 }
598 if (wView.error() == C2_OK) {
599 wView.setOffset(0);
600 }
601 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
602 block->share(codecDataOffset, outBufferSize - codecDataOffset, C2Fence{}))};
603 if (!buffer->copy(c2Buffer)) {
604 ALOGI("[%s] attachEncryptedBuffers: buffer copy failed", mName);
605 return -ENOSYS;
606 }
607 return OK;
608}
609
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800610status_t CCodecBufferChannel::attachEncryptedBuffer(
611 const sp<hardware::HidlMemory> &memory,
612 bool secure,
613 const uint8_t *key,
614 const uint8_t *iv,
615 CryptoPlugin::Mode mode,
616 CryptoPlugin::Pattern pattern,
617 size_t offset,
618 const CryptoPlugin::SubSample *subSamples,
619 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000620 const sp<MediaCodecBuffer> &buffer,
621 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800622 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
623 static const C2MemoryUsage kDefaultReadWriteUsage{
624 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
625
626 size_t size = 0;
627 for (size_t i = 0; i < numSubSamples; ++i) {
628 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
629 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700630 if (size == 0) {
631 buffer->setRange(0, 0);
632 return OK;
633 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800634 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
635 std::shared_ptr<C2LinearBlock> block;
636 c2_status_t err = pool->fetchLinearBlock(
637 size,
638 secure ? kSecureUsage : kDefaultReadWriteUsage,
639 &block);
640 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700641 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
642 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800643 return NO_MEMORY;
644 }
645 if (!secure) {
646 ensureDecryptDestination(size);
647 }
648 ssize_t result = -1;
649 ssize_t codecDataOffset = 0;
650 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800651 int32_t heapSeqNum = getHeapSeqNum(memory);
652 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
653 hardware::drm::V1_0::DestinationBuffer dst;
654 if (secure) {
655 dst.type = DrmBufferType::NATIVE_HANDLE;
656 dst.secureMemory = hardware::hidl_handle(block->handle());
657 } else {
658 dst.type = DrmBufferType::SHARED_MEMORY;
659 IMemoryToSharedBuffer(
660 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
661 }
662 result = mCrypto->decrypt(
663 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000664 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800665 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700666 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800667 return result;
668 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800669 } else {
670 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
671 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
672 hidl_vec<SubSample> hidlSubSamples;
673 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
674
675 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
676 hardware::cas::native::V1_0::DestinationBuffer dst;
677 if (secure) {
678 dst.type = BufferType::NATIVE_HANDLE;
679 dst.secureMemory = hardware::hidl_handle(block->handle());
680 } else {
681 dst.type = BufferType::SHARED_MEMORY;
682 dst.nonsecureMemory = src;
683 }
684
685 CasStatus status = CasStatus::OK;
686 hidl_string detailedError;
687 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
688
689 if (key != nullptr) {
690 sctrl = (ScramblingControl)key[0];
691 // Adjust for the PES offset
692 codecDataOffset = key[2] | (key[3] << 8);
693 }
694
695 auto returnVoid = mDescrambler->descramble(
696 sctrl,
697 hidlSubSamples,
698 src,
699 0,
700 dst,
701 0,
702 [&status, &result, &detailedError] (
703 CasStatus _status, uint32_t _bytesWritten,
704 const hidl_string& _detailedError) {
705 status = _status;
706 result = (ssize_t)_bytesWritten;
707 detailedError = _detailedError;
708 });
Arun Johnson634d0802023-02-14 22:07:51 +0000709 if (errorDetailMsg) {
710 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
711 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800712 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
713 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
714 mName, returnVoid.description().c_str(), status, result);
715 return UNKNOWN_ERROR;
716 }
717
718 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700719 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
720 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800721 return BAD_VALUE;
722 }
723 }
724 if (!secure) {
725 C2WriteView view = block->map().get();
726 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700727 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
728 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800729 return UNKNOWN_ERROR;
730 }
731 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700732 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
733 "(non-secure)",
734 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800735 return UNKNOWN_ERROR;
736 }
737 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
738 }
739 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
740 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
741 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700742 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800743 return -ENOSYS;
744 }
745 return OK;
746}
747
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
749 QueueGuard guard(mSync);
750 if (!guard.isRunning()) {
751 ALOGD("[%s] No more buffers should be queued at current state.", mName);
752 return -ENOSYS;
753 }
754 return queueInputBufferInternal(buffer);
755}
756
757status_t CCodecBufferChannel::queueSecureInputBuffer(
758 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
759 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
760 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
761 AString *errorDetailMsg) {
762 QueueGuard guard(mSync);
763 if (!guard.isRunning()) {
764 ALOGD("[%s] No more buffers should be queued at current state.", mName);
765 return -ENOSYS;
766 }
767
768 if (!hasCryptoOrDescrambler()) {
769 return -ENOSYS;
770 }
771 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
772
Sungtak Lee04b30352020-07-27 13:57:25 -0700773 std::shared_ptr<C2LinearBlock> block;
774 size_t allocSize = buffer->size();
775 size_t bufferSize = 0;
776 c2_status_t blockRes = C2_OK;
777 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000778 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
779 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700780 if (mSendEncryptedInfoBuffer) {
781 static const C2MemoryUsage kDefaultReadWriteUsage{
782 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
783 constexpr int kAllocGranule0 = 1024 * 64;
784 constexpr int kAllocGranule1 = 1024 * 1024;
785 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
786 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
787 if (allocSize <= kAllocGranule1) {
788 bufferSize = align(allocSize, kAllocGranule0);
789 } else {
790 bufferSize = align(allocSize, kAllocGranule1);
791 }
792 blockRes = pool->fetchLinearBlock(
793 bufferSize, kDefaultReadWriteUsage, &block);
794
795 if (blockRes == C2_OK) {
796 C2WriteView view = block->map().get();
797 if (view.error() == C2_OK && view.size() == bufferSize) {
798 copied = true;
799 // TODO: only copy clear sections
800 memcpy(view.data(), buffer->data(), allocSize);
801 }
802 }
803 }
804
805 if (!copied) {
806 block.reset();
807 }
808
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809 ssize_t result = -1;
810 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700811 if (numSubSamples == 1
812 && subSamples[0].mNumBytesOfClearData == 0
813 && subSamples[0].mNumBytesOfEncryptedData == 0) {
814 // We don't need to go through crypto or descrambler if the input is empty.
815 result = 0;
816 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700817 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800818 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700819 destination.type = DrmBufferType::NATIVE_HANDLE;
820 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800821 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700822 destination.type = DrmBufferType::SHARED_MEMORY;
823 IMemoryToSharedBuffer(
824 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800825 }
Robert Shih895fba92019-07-16 16:29:44 -0700826 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800827 encryptedBuffer->fillSourceBuffer(&source);
828 result = mCrypto->decrypt(
829 key, iv, mode, pattern, source, buffer->offset(),
830 subSamples, numSubSamples, destination, errorDetailMsg);
831 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700832 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800833 return result;
834 }
Robert Shih895fba92019-07-16 16:29:44 -0700835 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800836 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
837 }
838 } else {
839 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
840 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
841 hidl_vec<SubSample> hidlSubSamples;
842 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
843
844 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
845 encryptedBuffer->fillSourceBuffer(&srcBuffer);
846
847 DestinationBuffer dstBuffer;
848 if (secure) {
849 dstBuffer.type = BufferType::NATIVE_HANDLE;
850 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
851 } else {
852 dstBuffer.type = BufferType::SHARED_MEMORY;
853 dstBuffer.nonsecureMemory = srcBuffer;
854 }
855
856 CasStatus status = CasStatus::OK;
857 hidl_string detailedError;
858 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
859
860 if (key != nullptr) {
861 sctrl = (ScramblingControl)key[0];
862 // Adjust for the PES offset
863 codecDataOffset = key[2] | (key[3] << 8);
864 }
865
866 auto returnVoid = mDescrambler->descramble(
867 sctrl,
868 hidlSubSamples,
869 srcBuffer,
870 0,
871 dstBuffer,
872 0,
873 [&status, &result, &detailedError] (
874 CasStatus _status, uint32_t _bytesWritten,
875 const hidl_string& _detailedError) {
876 status = _status;
877 result = (ssize_t)_bytesWritten;
878 detailedError = _detailedError;
879 });
880
881 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
882 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
883 mName, returnVoid.description().c_str(), status, result);
884 return UNKNOWN_ERROR;
885 }
886
887 if (result < codecDataOffset) {
888 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
889 return BAD_VALUE;
890 }
891
892 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
893
894 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
895 encryptedBuffer->copyDecryptedContentFromMemory(result);
896 }
897 }
898
899 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700900
901 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902}
903
Arun Johnson564f3a92024-02-01 19:09:45 +0000904status_t CCodecBufferChannel::queueSecureInputBuffers(
905 const sp<MediaCodecBuffer> &buffer,
906 bool secure,
907 AString *errorDetailMsg) {
908 QueueGuard guard(mSync);
909 if (!guard.isRunning()) {
910 ALOGD("[%s] No more buffers should be queued at current state.", mName);
911 return -ENOSYS;
912 }
913
914 if (!hasCryptoOrDescrambler()) {
915 ALOGE("queueSecureInputBuffers requires a Crypto/descrambler Object");
916 return -ENOSYS;
917 }
918 sp<RefBase> obj;
919 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
920 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
921 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
922 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
923 if (secure || mCrypto == nullptr) {
924 if (cryptoInfos->value.size() != 1) {
925 ALOGE("Cannot decrypt multiple access units on native handles");
926 return -ENOSYS;
927 }
928 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
929 if (info == nullptr) {
930 ALOGE("Cannot decrypt, CryptoInfos are null");
931 return -ENOSYS;
932 }
933 return queueSecureInputBuffer(
934 buffer,
935 secure,
936 info->mKey,
937 info->mIv,
938 info->mMode,
939 info->mPattern,
940 info->mSubSamples,
941 info->mNumSubSamples,
942 errorDetailMsg);
943 }
944 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
945
946 std::shared_ptr<C2LinearBlock> block;
947 size_t allocSize = buffer->size();
948 size_t bufferSize = 0;
949 c2_status_t blockRes = C2_OK;
950 bool copied = false;
951 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
952 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
953 if (mSendEncryptedInfoBuffer) {
954 static const C2MemoryUsage kDefaultReadWriteUsage{
955 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
956 constexpr int kAllocGranule0 = 1024 * 64;
957 constexpr int kAllocGranule1 = 1024 * 1024;
958 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
959 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
960 if (allocSize <= kAllocGranule1) {
961 bufferSize = align(allocSize, kAllocGranule0);
962 } else {
963 bufferSize = align(allocSize, kAllocGranule1);
964 }
965 blockRes = pool->fetchLinearBlock(
966 bufferSize, kDefaultReadWriteUsage, &block);
967
968 if (blockRes == C2_OK) {
969 C2WriteView view = block->map().get();
970 if (view.error() == C2_OK && view.size() == bufferSize) {
971 copied = true;
972 // TODO: only copy clear sections
973 memcpy(view.data(), buffer->data(), allocSize);
974 }
975 }
976 }
977
978 if (!copied) {
979 block.reset();
980 }
981 // size of cryptoInfo and accessUnitInfo should be the same?
982 ssize_t result = -1;
983 ssize_t codecDataOffset = 0;
984 size_t inBufferOffset = 0;
985 size_t outBufferSize = 0;
986 uint32_t cryptoInfoIdx = 0;
987 {
988 // scoped this block to enable destruction of mappedBlock
989 std::unique_ptr<EncryptedLinearBlockBuffer::MappedBlock> mappedBlock = nullptr;
990 hardware::drm::V1_0::DestinationBuffer destination;
991 destination.type = DrmBufferType::SHARED_MEMORY;
992 IMemoryToSharedBuffer(
993 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
994 encryptedBuffer->getMappedBlock(&mappedBlock);
995 hardware::drm::V1_0::SharedBuffer source;
996 encryptedBuffer->fillSourceBuffer(&source);
997 for (int i = 0 ; i < bufferInfos->value.size(); i++) {
998 if (bufferInfos->value[i].mSize > 0) {
999 std::unique_ptr<CodecCryptoInfo> info =
1000 std::move(cryptoInfos->value[cryptoInfoIdx++]);
1001 if (info->mNumSubSamples == 1
1002 && info->mSubSamples[0].mNumBytesOfClearData == 0
1003 && info->mSubSamples[0].mNumBytesOfEncryptedData == 0) {
1004 // no data so we only populate the bufferInfo
1005 result = 0;
1006 } else {
1007 result = mCrypto->decrypt(
1008 (uint8_t*)info->mKey,
1009 (uint8_t*)info->mIv,
1010 info->mMode,
1011 info->mPattern,
1012 source,
1013 inBufferOffset,
1014 info->mSubSamples,
1015 info->mNumSubSamples,
1016 destination,
1017 errorDetailMsg);
1018 inBufferOffset += bufferInfos->value[i].mSize;
1019 if (result < 0) {
1020 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
1021 return result;
1022 }
1023 if (destination.type == DrmBufferType::SHARED_MEMORY && mappedBlock) {
1024 mappedBlock->copyDecryptedContent(mDecryptDestination, result);
1025 }
1026 bufferInfos->value[i].mSize = result;
1027 outBufferSize += result;
1028 }
1029 }
1030 }
1031 buffer->setRange(codecDataOffset, outBufferSize - codecDataOffset);
1032 }
1033 return queueInputBufferInternal(buffer, block, bufferSize);
1034}
1035
Pawin Vongmasa36653902018-11-15 00:10:25 -08001036void CCodecBufferChannel::feedInputBufferIfAvailable() {
1037 QueueGuard guard(mSync);
1038 if (!guard.isRunning()) {
1039 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1040 return;
1041 }
1042 feedInputBufferIfAvailableInternal();
1043}
1044
1045void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +09001046 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001047 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001048 }
1049 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001050 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001051 if (!output->buffers ||
1052 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -07001053 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001054 return;
1055 }
1056 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001057 size_t numActiveSlots = 0;
1058 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 sp<MediaCodecBuffer> inBuffer;
1060 size_t index;
1061 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001062 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001063 numActiveSlots = input->buffers->numActiveSlots();
1064 if (numActiveSlots >= input->numSlots) {
1065 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001066 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001067 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001069 break;
1070 }
1071 }
1072 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1073 mCallback->onInputBufferAvailable(index, inBuffer);
1074 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001075 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001076}
1077
1078status_t CCodecBufferChannel::renderOutputBuffer(
1079 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001080 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001082 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001084 Mutexed<Output>::Locked output(mOutput);
1085 if (output->buffers) {
1086 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 }
1088 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001089 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1090 // set to true.
1091 sendOutputBuffers();
1092 // input buffer feeding may have been gated by pending output buffers
1093 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001094 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001095 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001096 std::call_once(mRenderWarningFlag, [this] {
1097 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1098 "timestamp or render=true with non-video buffers. Apps should "
1099 "call releaseOutputBuffer() with render=false for those.",
1100 mName);
1101 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001102 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001103 return INVALID_OPERATION;
1104 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001105
1106#if 0
1107 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1108 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1109 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1110 AString res;
1111 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1112 if (ix) res.append(", ");
1113 res.append(*((int32_t*)info.get() + (ix / 4)));
1114 }
1115 ALOGV(" [%s]", res.c_str());
1116 }
1117#endif
1118 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1119 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1120 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1121 bool flip = rotation && (rotation->flip & 1);
1122 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001123
1124 {
1125 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1126 if (output->surface == nullptr) {
1127 ALOGI("[%s] cannot render buffer without surface", mName);
1128 return OK;
1129 }
1130 int64_t frameIndex;
1131 buffer->meta()->findInt64("frameIndex", &frameIndex);
1132 if (output->rotation.count(frameIndex) != 0) {
1133 auto it = output->rotation.find(frameIndex);
1134 quarters = (it->second / 90) & 3;
1135 output->rotation.erase(it);
1136 }
1137 }
1138
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 uint32_t transform = 0;
1140 switch (quarters) {
1141 case 0: // no rotation
1142 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1143 break;
1144 case 1: // 90 degrees counter-clockwise
1145 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1146 : HAL_TRANSFORM_ROT_270;
1147 break;
1148 case 2: // 180 degrees
1149 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1150 break;
1151 case 3: // 90 degrees clockwise
1152 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1153 : HAL_TRANSFORM_ROT_90;
1154 break;
1155 }
1156
1157 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1158 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1159 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1160 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1161 if (surfaceScaling) {
1162 videoScalingMode = surfaceScaling->value;
1163 }
1164
1165 // Use dataspace from format as it has the default aspects already applied
1166 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1167 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1168
1169 // HDR static info
1170 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1171 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1172 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1173
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001174 // HDR10 plus info
1175 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1176 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1177 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001178 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1179 hdr10PlusInfo.reset();
1180 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001181
Wonsik Kima79c5522022-01-18 16:29:24 -08001182 // HDR dynamic info
1183 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1184 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1185 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1186 // TODO: make this sticky & enable unset
1187 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1188 hdrDynamicInfo.reset();
1189 }
1190
1191 if (hdr10PlusInfo) {
1192 // C2StreamHdr10PlusInfo is deprecated; components should use
1193 // C2StreamHdrDynamicMetadataInfo
1194 // TODO: #metric
1195 if (hdrDynamicInfo) {
1196 // It is unexpected that C2StreamHdr10PlusInfo and
1197 // C2StreamHdrDynamicMetadataInfo is both present.
1198 // C2StreamHdrDynamicMetadataInfo takes priority.
1199 // TODO: #metric
1200 } else {
1201 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1202 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1203 hdr10PlusInfo->flexCount(),
1204 0u,
1205 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1206 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1207 hdrDynamicInfo = info;
1208 }
1209 }
1210
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1212 if (blocks.size() != 1u) {
1213 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1214 return UNKNOWN_ERROR;
1215 }
1216 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001217 C2Fence c2fence = block.fence();
1218 sp<Fence> fence = Fence::NO_FENCE;
1219 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1220 // Once C2Fence::type() is added, check the exact C2Fence type
1221 if (c2fence.isHW()) {
1222 int fenceFd = c2fence.fd();
1223 fence = sp<Fence>::make(fenceFd);
1224 if (!fence) {
1225 ALOGE("[%s] Failed to allocate a fence", mName);
1226 close(fenceFd);
1227 return NO_MEMORY;
1228 }
1229 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230
1231 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001232 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233 timestampNs,
1234 false, // droppable
1235 dataSpace,
1236 Rect(blocks.front().crop().left,
1237 blocks.front().crop().top,
1238 blocks.front().crop().right(),
1239 blocks.front().crop().bottom()),
1240 videoScalingMode,
1241 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001242 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001243 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001245 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001246 // If mastering max and min luminance fields are 0, do not use them.
1247 // It indicates the value may not be present in the stream.
1248 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1249 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1250 struct android_smpte2086_metadata smpte2086_meta = {
1251 .displayPrimaryRed = {
1252 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1253 },
1254 .displayPrimaryGreen = {
1255 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1256 },
1257 .displayPrimaryBlue = {
1258 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1259 },
1260 .whitePoint = {
1261 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1262 },
1263 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1264 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1265 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001266 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001267 hdr.smpte2086 = smpte2086_meta;
1268 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001269 // If the content light level fields are 0, do not use them, it
1270 // indicates the value may not be present in the stream.
1271 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1272 struct android_cta861_3_metadata cta861_meta = {
1273 .maxContentLightLevel = hdrStaticInfo->maxCll,
1274 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1275 };
1276 hdr.validTypes |= HdrMetadata::CTA861_3;
1277 hdr.cta8613 = cta861_meta;
1278 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001279
1280 // does not have valid info
1281 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1282 hdrStaticInfo.reset();
1283 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001284 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001285 if (hdrDynamicInfo
1286 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001287 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1288 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001289 hdrDynamicInfo->m.data,
1290 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001291 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001292 qbi.setHdrMetadata(hdr);
1293 }
Hongguangfc1478a2022-07-20 22:56:06 -07001294 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1295
Brian Lindahl932bf602023-03-09 11:59:48 -07001296 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1297 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1298 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001299 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1300 if (result != OK) {
1301 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001302 if (result == NO_INIT) {
1303 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1304 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001305 return result;
1306 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001307
1308 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1309 ALOGD("[%s] queue buffer successful", mName);
1310 } else {
1311 ALOGV("[%s] queue buffer successful", mName);
1312 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001313
1314 int64_t mediaTimeUs = 0;
1315 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001316 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001317 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1318 processRenderedFrames(qbo.frameTimestamps);
1319 } else {
1320 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1321 // when the frame is queued to the non-display surface
1322 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1323 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001324
1325 return OK;
1326}
1327
Brian Lindahl932bf602023-03-09 11:59:48 -07001328void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001329 mTrackedFrames.clear();
1330
1331 int isSurfaceToDisplay = 0;
1332 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1333 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1334 // No frame tracking is needed if we're not sending frames to the display
1335 if (!mIsSurfaceToDisplay) {
1336 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1337 return;
1338 }
1339
Brian Lindahl932bf602023-03-09 11:59:48 -07001340 int hasPresentFenceTimes = 0;
1341 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1342 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001343 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001344 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1345 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001346}
1347
1348void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1349 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1350 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1351 // so track the frame as if the desired render time is now.
1352 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1353 if (desiredRenderTimeNs < nowNs) {
1354 desiredRenderTimeNs = nowNs;
1355 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001356
1357 // If the render time is more than a second from now, then pretend the frame is supposed to be
1358 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1359 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1360 // processRenderedFrames.
1361 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1362 desiredRenderTimeNs = nowNs;
1363 }
1364
Brian Lindahl932bf602023-03-09 11:59:48 -07001365 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1366 // actually rendered.
1367 TrackedFrame frame;
1368 frame.number = qbo.nextFrameNumber - 1;
1369 frame.mediaTimeUs = mediaTimeUs;
1370 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1371 frame.latchTime = -1;
1372 frame.presentFence = nullptr;
1373 mTrackedFrames.push_back(frame);
1374}
1375
1376void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1377 // Grab the latch times and present fences from the frame event deltas
1378 for (const auto& delta : deltas) {
1379 for (auto& frame : mTrackedFrames) {
1380 if (delta.getFrameNumber() == frame.number) {
1381 delta.getLatchTime(&frame.latchTime);
1382 delta.getDisplayPresentFence(&frame.presentFence);
1383 }
1384 }
1385 }
1386
1387 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1388 // in fact, been rendered.
1389 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1390 while (!mTrackedFrames.empty()) {
1391 TrackedFrame & frame = mTrackedFrames.front();
1392 // Frames that should have been rendered at least 100ms in the past are checked
1393 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1394 break;
1395 }
1396
1397 // If we don't have a render time by now, then consider the frame as dropped
1398 int64_t renderTimeNs = getRenderTimeNs(frame);
1399 if (renderTimeNs != -1) {
1400 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1401 }
1402 mTrackedFrames.pop_front();
1403 }
1404}
1405
1406int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1407 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1408 if (!mHasPresentFenceTimes) {
1409 if (frame.latchTime == -1) {
1410 ALOGD("no latch time for frame %d", (int) frame.number);
1411 return -1;
1412 }
1413 return frame.latchTime;
1414 }
1415
1416 if (frame.presentFence == nullptr) {
1417 ALOGW("no present fence for frame %d", (int) frame.number);
1418 return -1;
1419 }
1420
1421 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1422
1423 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1424 ALOGW("invalid signal time for frame %d", (int) frame.number);
1425 return -1;
1426 }
1427
1428 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1429 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1430 return -1;
1431 }
1432
1433 return actualRenderTimeNs;
1434}
1435
1436void CCodecBufferChannel::pollForRenderedBuffers() {
1437 FrameEventHistoryDelta delta;
1438 mComponent->pollForRenderedFrames(&delta);
1439 processRenderedFrames(delta);
1440}
1441
Sungtak Lee214ce612023-11-01 10:01:13 +00001442void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001443 // Note: Since this is called asynchronously from IProducerListener not
1444 // knowing the internal state of CCodec/CCodecBufferChannel,
1445 // prevent mComponent from being destroyed by holding the shared reference
1446 // during this interface being executed.
1447 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1448 if (comp) {
1449 comp->onBufferReleasedFromOutputSurface(generation);
1450 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001451}
1452
Pawin Vongmasa36653902018-11-15 00:10:25 -08001453status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1454 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1455 bool released = false;
1456 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001457 Mutexed<Input>::Locked input(mInput);
1458 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001459 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460 }
1461 }
1462 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001463 Mutexed<Output>::Locked output(mOutput);
1464 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001465 released = true;
1466 }
1467 }
1468 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001469 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001470 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001471 } else {
1472 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1473 }
1474 return OK;
1475}
1476
1477void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1478 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001479 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001480
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001481 if (!input->buffers) {
1482 ALOGE("getInputBufferArray: No Input Buffers allocated");
1483 return;
1484 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001485 if (!input->buffers->isArrayMode()) {
1486 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 }
1488
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001489 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490}
1491
1492void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1493 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001494 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001495 if (!output->buffers) {
1496 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1497 return;
1498 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001499 if (!output->buffers->isArrayMode()) {
1500 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 }
1502
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001503 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001504}
1505
1506status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001507 const sp<AMessage> &inputFormat,
1508 const sp<AMessage> &outputFormat,
1509 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1511 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001512 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001513 C2PortReorderBufferDepthTuning::output reorderDepth;
1514 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001515 C2PortActualDelayTuning::input inputDelay(0);
1516 C2PortActualDelayTuning::output outputDelay(0);
1517 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001518 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001519
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 c2_status_t err = mComponent->query(
1521 {
1522 &iStreamFormat,
1523 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001524 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 &reorderDepth,
1526 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001527 &inputDelay,
1528 &pipelineDelay,
1529 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001530 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001531 },
1532 {},
1533 C2_DONT_BLOCK,
1534 nullptr);
1535 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001536 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 return UNKNOWN_ERROR;
1538 }
1539 } else if (err != C2_OK) {
1540 return UNKNOWN_ERROR;
1541 }
1542
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001543 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1544 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1545 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1546
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001547 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1548 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001549
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 // TODO: get this from input format
1551 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1552
Sungtak Lee04b30352020-07-27 13:57:25 -07001553 // secure mode is a static parameter (shall not change in the executing state)
1554 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1555
Pawin Vongmasa36653902018-11-15 00:10:25 -08001556 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001557 int poolMask = GetCodec2PoolMask();
1558 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559
1560 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001561 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001562 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001563 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1564 API_REFLECTION |
1565 API_VALUES |
1566 API_CURRENT_VALUES |
1567 API_DEPENDENCY |
1568 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001569 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1570 C2StreamSampleRateInfo::input sampleRate(0u);
1571 C2StreamChannelCountInfo::input channelCount(0u);
1572 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001573 std::shared_ptr<C2BlockPool> pool;
1574 {
1575 Mutexed<BlockPools>::Locked pools(mBlockPools);
1576
1577 // set default allocator ID.
1578 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001579 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580
1581 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1582 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1583 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001584 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001585 std::vector<C2Param *> stackParams({&featuresSetting});
1586 if (audioEncoder) {
1587 stackParams.push_back(&encoderFrameSize);
1588 stackParams.push_back(&sampleRate);
1589 stackParams.push_back(&channelCount);
1590 stackParams.push_back(&pcmEncoding);
1591 } else {
1592 encoderFrameSize.invalidate();
1593 sampleRate.invalidate();
1594 channelCount.invalidate();
1595 pcmEncoding.invalidate();
1596 }
1597 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001598 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1599 C2_DONT_BLOCK,
1600 &params);
1601 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1602 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1603 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001604 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 C2PortAllocatorsTuning::input *inputAllocators =
1606 C2PortAllocatorsTuning::input::From(params[0].get());
1607 if (inputAllocators && inputAllocators->flexCount() > 0) {
1608 std::shared_ptr<C2Allocator> allocator;
1609 // verify allocator IDs and resolve default allocator
1610 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1611 if (allocator) {
1612 pools->inputAllocatorId = allocator->getId();
1613 } else {
1614 ALOGD("[%s] component requested invalid input allocator ID %u",
1615 mName, inputAllocators->m.values[0]);
1616 }
1617 }
1618 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001619 if (featuresSetting) {
1620 apiFeatures = featuresSetting.value;
1621 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622
1623 // TODO: use C2Component wrapper to associate this pool with ourselves
1624 if ((poolMask >> pools->inputAllocatorId) & 1) {
1625 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1626 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1627 mName, pools->inputAllocatorId,
1628 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1629 asString(err), err);
1630 } else {
1631 err = C2_NOT_FOUND;
1632 }
1633 if (err != C2_OK) {
1634 C2BlockPool::local_id_t inputPoolId =
1635 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1636 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1637 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1638 mName, (unsigned long long)inputPoolId,
1639 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1640 asString(err), err);
1641 if (err != C2_OK) {
1642 return NO_MEMORY;
1643 }
1644 }
1645 pools->inputPool = pool;
1646 }
1647
Wonsik Kim51051262018-11-28 13:59:05 -08001648 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001649 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001650 input->inputDelay = inputDelayValue;
1651 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001652 input->numSlots = numInputSlots;
1653 input->extraBuffers.flush();
1654 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001655 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001656 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1657 input->frameReassembler.init(
1658 pool,
1659 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1660 encoderFrameSize.value,
1661 sampleRate.value,
1662 channelCount.value,
1663 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1664 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001665 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1666 // For encrypted content, framework decrypts source buffer (ashmem) into
1667 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001668 if (!buffersBoundToCodec
1669 && !input->frameReassembler
1670 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001671 input->buffers.reset(new SlotInputBuffers(mName));
1672 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001673 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001674 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001676 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001677 // This is to ensure buffers do not get released prematurely.
1678 // TODO: handle this without going into array mode
1679 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001681 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001682 }
1683 } else {
1684 if (hasCryptoOrDescrambler()) {
1685 int32_t capacity = kLinearBufferSize;
1686 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1687 if ((size_t)capacity > kMaxLinearBufferSize) {
1688 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1689 capacity = kMaxLinearBufferSize;
1690 }
1691 if (mDealer == nullptr) {
1692 mDealer = new MemoryDealer(
1693 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001694 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 "EncryptedLinearInputBuffers");
1696 mDecryptDestination = mDealer->allocate((size_t)capacity);
1697 }
1698 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001699 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1700 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 } else {
1702 mHeapSeqNum = -1;
1703 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001704 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001705 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001706 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001707 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001708 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001709 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 }
1711 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001712 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001713
1714 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001715 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716 } else {
1717 // TODO: error
1718 }
Wonsik Kim51051262018-11-28 13:59:05 -08001719
1720 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001721 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001722 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 }
1724
1725 if (outputFormat != nullptr) {
1726 sp<IGraphicBufferProducer> outputSurface;
1727 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001728 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729 {
1730 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001731 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001732 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 outputSurface = output->surface ?
1734 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001735 if (outputSurface) {
1736 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1737 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 outputGeneration = output->generation;
1739 }
1740
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001741 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001743 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001744
1745 {
1746 Mutexed<BlockPools>::Locked pools(mBlockPools);
1747
David Stevensc3fbb282021-01-18 18:11:20 +09001748 prevOutputPoolId = pools->outputPoolId;
1749
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 // set default allocator ID.
1751 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001752 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753
1754 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1755 // unsuccessful.
1756 std::vector<std::unique_ptr<C2Param>> params;
1757 err = mComponent->query({ },
1758 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1759 C2_DONT_BLOCK,
1760 &params);
1761 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1762 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1763 mName, params.size(), asString(err), err);
1764 } else if (err == C2_OK && params.size() == 1) {
1765 C2PortAllocatorsTuning::output *outputAllocators =
1766 C2PortAllocatorsTuning::output::From(params[0].get());
1767 if (outputAllocators && outputAllocators->flexCount() > 0) {
1768 std::shared_ptr<C2Allocator> allocator;
1769 // verify allocator IDs and resolve default allocator
1770 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1771 if (allocator) {
1772 pools->outputAllocatorId = allocator->getId();
1773 } else {
1774 ALOGD("[%s] component requested invalid output allocator ID %u",
1775 mName, outputAllocators->m.values[0]);
1776 }
1777 }
1778 }
1779
1780 // use bufferqueue if outputting to a surface.
1781 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1782 // if unsuccessful.
1783 if (outputSurface) {
1784 params.clear();
1785 err = mComponent->query({ },
1786 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1787 C2_DONT_BLOCK,
1788 &params);
1789 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1790 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1791 mName, params.size(), asString(err), err);
1792 } else if (err == C2_OK && params.size() == 1) {
1793 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1794 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1795 if (surfaceAllocator) {
1796 std::shared_ptr<C2Allocator> allocator;
1797 // verify allocator IDs and resolve default allocator
1798 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1799 if (allocator) {
1800 pools->outputAllocatorId = allocator->getId();
1801 } else {
1802 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1803 mName, surfaceAllocator->value);
1804 err = C2_BAD_VALUE;
1805 }
1806 }
1807 }
1808 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1809 && err != C2_OK
1810 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1811 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1812 }
1813 }
1814
1815 if ((poolMask >> pools->outputAllocatorId) & 1) {
1816 err = mComponent->createBlockPool(
1817 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1818 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1819 mName, pools->outputAllocatorId,
1820 (unsigned long long)pools->outputPoolId,
1821 asString(err));
1822 } else {
1823 err = C2_NOT_FOUND;
1824 }
1825 if (err != C2_OK) {
1826 // use basic pool instead
1827 pools->outputPoolId =
1828 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1829 }
1830
1831 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1832 // component.
1833 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1834 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1835
1836 std::vector<std::unique_ptr<C2SettingResult>> failures;
1837 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1838 ALOGD("[%s] Configured output block pool ids %llu => %s",
1839 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1840 outputPoolId_ = pools->outputPoolId;
1841 }
1842
David Stevensc3fbb282021-01-18 18:11:20 +09001843 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1844 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1845 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1846 if (err != C2_OK) {
1847 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1848 (unsigned long long) prevOutputPoolId, asString(err), err);
1849 }
1850 }
1851
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001852 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001853 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001854 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001855 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001857 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001858 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001859 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001860 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001861 }
1862 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001863 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001865 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001866
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001867 output->buffers->clearStash();
1868 if (reorderDepth) {
1869 output->buffers->setReorderDepth(reorderDepth.value);
1870 }
1871 if (reorderKey) {
1872 output->buffers->setReorderKey(reorderKey.value);
1873 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001874
1875 // Try to set output surface to created block pool if given.
1876 if (outputSurface) {
1877 mComponent->setOutputSurface(
1878 outputPoolId_,
1879 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001880 outputGeneration,
1881 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001882 } else {
1883 // configure CPU read consumer usage
1884 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1885 std::vector<std::unique_ptr<C2SettingResult>> failures;
1886 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1887 // do not print error message for now as most components may not yet
1888 // support this setting
1889 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1890 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001891 }
1892
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001893 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001894 if (buffersBoundToCodec) {
1895 // WORKAROUND: if we're using early CSD workaround we convert to
1896 // array mode, to appease apps assuming the output
1897 // buffers to be of the same size.
1898 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1899 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900
1901 int32_t channelCount;
1902 int32_t sampleRate;
1903 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1904 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1905 int32_t delay = 0;
1906 int32_t padding = 0;;
1907 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1908 delay = 0;
1909 }
1910 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1911 padding = 0;
1912 }
1913 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001914 // We need write access to the buffers, so turn them into array mode.
1915 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1916 // component, runs it through SkipCutBuffer and allocate local buffer to be
1917 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1918 // toArrayMode().
1919 if (!output->buffers->isArrayMode()) {
1920 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1921 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001922 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001923 }
1924 }
1925 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001926
1927 int32_t tunneled = 0;
1928 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1929 tunneled = 0;
1930 }
1931 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 }
1933
1934 // Set up pipeline control. This has to be done after mInputBuffers and
1935 // mOutputBuffers are initialized to make sure that lingering callbacks
1936 // about buffers from the previous generation do not interfere with the
1937 // newly initialized pipeline capacity.
1938
Wonsik Kim62545252021-01-20 11:25:41 -08001939 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001940 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001941 watcher->inputDelay(inputDelayValue)
1942 .pipelineDelay(pipelineDelayValue)
1943 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001944 .smoothnessFactor(kSmoothnessFactor)
1945 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001946 watcher->flush();
1947 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948
1949 mInputMetEos = false;
1950 mSync.start();
1951 return OK;
1952}
1953
Wonsik Kim34b28b42022-05-20 15:49:32 -07001954status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00001955 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001956 if (mInputSurface) {
1957 return OK;
1958 }
1959
Wonsik Kim34b28b42022-05-20 15:49:32 -07001960 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00001961 int retryCount = 1;
1962 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
1963 {
1964 Mutexed<Input>::Locked input(mInput);
1965 while (clientInputBuffers->size() < numInputSlots) {
1966 size_t index;
1967 sp<MediaCodecBuffer> buffer;
1968 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1969 break;
1970 }
1971 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07001972 }
Arun Johnson326166e2023-07-28 19:11:52 +00001973 }
1974 if (!retry || (retryCount <= 0)) {
1975 break;
1976 }
1977 if (clientInputBuffers->empty()) {
1978 // wait: buffer may be in transit from component.
1979 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07001980 }
1981 }
1982 if (clientInputBuffers->empty()) {
1983 ALOGW("[%s] start: cannot allocate memory at all", mName);
1984 return NO_MEMORY;
1985 } else if (clientInputBuffers->size() < numInputSlots) {
1986 ALOGD("[%s] start: cannot allocate memory for all slots, "
1987 "only %zu buffers allocated",
1988 mName, clientInputBuffers->size());
1989 } else {
1990 ALOGV("[%s] %zu initial input buffers available",
1991 mName, clientInputBuffers->size());
1992 }
1993 return OK;
1994}
1995
1996status_t CCodecBufferChannel::requestInitialInputBuffers(
1997 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001998 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001999 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
2000 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
2001 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002002 return UNKNOWN_ERROR;
2003 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002004
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002005 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2006 mFlushedConfigs.lock()->swap(flushedConfigs);
2007 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002008 {
2009 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2010 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2011 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2012 watcher->onWorkQueued(
2013 work->input.ordinal.frameIndex.peeku(),
2014 std::vector(work->input.buffers),
2015 now);
2016 }
2017 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002018 err = mComponent->queue(&flushedConfigs);
2019 if (err != C2_OK) {
2020 ALOGW("[%s] Error while queueing a flushed config", mName);
2021 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002022 }
2023 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002024 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002025 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2026 !clientInputBuffers.empty()) {
2027 size_t minIndex = clientInputBuffers.begin()->first;
2028 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2029 for (const auto &[index, buffer] : clientInputBuffers) {
2030 if (minBuffer->capacity() > buffer->capacity()) {
2031 minIndex = index;
2032 minBuffer = buffer;
2033 }
2034 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002035 // WORKAROUND: Some apps expect CSD available without queueing
2036 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002037 minBuffer->setRange(0, 0);
2038 minBuffer->meta()->clear();
2039 minBuffer->meta()->setInt64("timeUs", 0);
2040 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002041 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2042 mName);
2043 return UNKNOWN_ERROR;
2044 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002045 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002046 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002047
Wonsik Kim34b28b42022-05-20 15:49:32 -07002048 for (const auto &[index, buffer] : clientInputBuffers) {
2049 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002050 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002051
Pawin Vongmasa36653902018-11-15 00:10:25 -08002052 return OK;
2053}
2054
2055void CCodecBufferChannel::stop() {
2056 mSync.stop();
2057 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002058}
2059
Sungtak Lee99144332023-01-26 11:03:14 +00002060void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2061 sp<Surface> surface = mOutputSurface.lock()->surface;
2062 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002063 C2BlockPool::local_id_t outputPoolId;
2064 {
2065 Mutexed<BlockPools>::Locked pools(mBlockPools);
2066 outputPoolId = pools->outputPoolId;
2067 }
2068 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002069
2070 if (pushBlankBuffer) {
2071 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2072 if (anw) {
2073 pushBlankBuffersToNativeWindow(anw.get());
2074 }
2075 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002076 }
2077}
2078
Wonsik Kim936a89c2020-05-08 16:07:50 -07002079void CCodecBufferChannel::reset() {
2080 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002081 if (mInputSurface != nullptr) {
2082 mInputSurface.reset();
2083 }
2084 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002085 {
2086 Mutexed<Input>::Locked input(mInput);
2087 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002088 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002089 }
2090 {
2091 Mutexed<Output>::Locked output(mOutput);
2092 output->buffers.reset();
2093 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002094 // reset the frames that are being tracked for onFrameRendered callbacks
2095 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002096}
2097
2098void CCodecBufferChannel::release() {
2099 mComponent.reset();
2100 mInputAllocator.reset();
2101 mOutputSurface.lock()->surface.clear();
2102 {
2103 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2104 blockPools->inputPool.reset();
2105 blockPools->outputPoolIntf.reset();
2106 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002107 setCrypto(nullptr);
2108 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002109}
2110
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2112 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002113 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002114 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002115 {
2116 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2117 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2118 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2119 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2120 watcher->onWorkDone(frameIndex);
2121 continue;
2122 }
2123 if (work->input.buffers.empty()
2124 || work->input.buffers.front() == nullptr
2125 || work->input.buffers.front()->data().linearBlocks().empty()) {
2126 ALOGD("[%s] no linear codec config data found", mName);
2127 watcher->onWorkDone(frameIndex);
2128 continue;
2129 }
2130 std::unique_ptr<C2Work> copy(new C2Work);
2131 copy->input.flags = C2FrameData::flags_t(
2132 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2133 copy->input.ordinal = work->input.ordinal;
2134 copy->input.ordinal.frameIndex = mFrameIndex++;
2135 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2136 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2137 }
2138 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2139 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2140 }
2141 copy->input.infoBuffers.insert(
2142 copy->input.infoBuffers.begin(),
2143 work->input.infoBuffers.begin(),
2144 work->input.infoBuffers.end());
2145 copy->worklets.emplace_back(new C2Worklet);
2146 configs.push_back(std::move(copy));
2147 watcher->onWorkDone(frameIndex);
2148 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002149 }
2150 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002151 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002152 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002153 Mutexed<Input>::Locked input(mInput);
2154 input->buffers->flush();
2155 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002156 }
2157 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002158 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002159 if (output->buffers) {
2160 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002161 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002162 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002163 }
2164}
2165
2166void CCodecBufferChannel::onWorkDone(
2167 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002168 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002169 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002170 feedInputBufferIfAvailable();
2171 }
2172}
2173
2174void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002175 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07002176 if (mInputSurface) {
2177 return;
2178 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002179 std::shared_ptr<C2Buffer> buffer =
2180 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002181 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002182 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002183 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002184 if (input->lastFlushIndex >= frameIndex) {
2185 ALOGD("[%s] Ignoring stale input buffer done callback: "
2186 "last flush index = %lld, frameIndex = %lld",
2187 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2188 } else {
2189 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2190 if (!newInputSlotAvailable) {
2191 (void)input->extraBuffers.expireComponentBuffer(buffer);
2192 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002193 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002194 }
2195 if (newInputSlotAvailable) {
2196 feedInputBufferIfAvailable();
2197 }
2198}
2199
2200bool CCodecBufferChannel::handleWork(
2201 std::unique_ptr<C2Work> work,
2202 const sp<AMessage> &outputFormat,
2203 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002204 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002205 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002206 if (!output->buffers) {
2207 return false;
2208 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002209 }
2210
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002211 // Whether the output buffer should be reported to the client or not.
2212 bool notifyClient = false;
2213
2214 if (work->result == C2_OK){
2215 notifyClient = true;
2216 } else if (work->result == C2_NOT_FOUND) {
2217 ALOGD("[%s] flushed work; ignored.", mName);
2218 } else {
2219 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2220 // the config update.
2221 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2222 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2223 return false;
2224 }
2225
2226 if ((work->input.ordinal.frameIndex -
2227 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002228 // Discard frames from previous generation.
2229 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002230 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231 }
2232
Wonsik Kim524b0582019-03-12 11:28:57 -07002233 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002234 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002235 || !(work->worklets.front()->output.flags &
2236 C2FrameData::FLAG_INCOMPLETE))) {
2237 mPipelineWatcher.lock()->onWorkDone(
2238 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002239 }
2240
2241 // NOTE: MediaCodec usage supposedly have only one worklet
2242 if (work->worklets.size() != 1u) {
2243 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2244 mName, work->worklets.size());
2245 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2246 return false;
2247 }
2248
2249 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2250
2251 std::shared_ptr<C2Buffer> buffer;
2252 // NOTE: MediaCodec usage supposedly have only one output stream.
2253 if (worklet->output.buffers.size() > 1u) {
2254 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2255 mName, worklet->output.buffers.size());
2256 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2257 return false;
2258 } else if (worklet->output.buffers.size() == 1u) {
2259 buffer = worklet->output.buffers[0];
2260 if (!buffer) {
2261 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2262 }
2263 }
2264
Wonsik Kim3dedf682021-05-03 10:57:09 -07002265 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2266 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002267 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002268 while (!worklet->output.configUpdate.empty()) {
2269 std::unique_ptr<C2Param> param;
2270 worklet->output.configUpdate.back().swap(param);
2271 worklet->output.configUpdate.pop_back();
2272 switch (param->coreIndex().coreIndex()) {
2273 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2274 C2PortReorderBufferDepthTuning::output reorderDepth;
2275 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2277 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002278 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002279 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002280 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002281 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2282 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002283 }
2284 break;
2285 }
2286 case C2PortReorderKeySetting::CORE_INDEX: {
2287 C2PortReorderKeySetting::output reorderKey;
2288 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002289 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002290 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2291 mName, reorderKey.value);
2292 } else {
2293 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2294 }
2295 break;
2296 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002297 case C2PortActualDelayTuning::CORE_INDEX: {
2298 if (param->isGlobal()) {
2299 C2ActualPipelineDelayTuning pipelineDelay;
2300 if (pipelineDelay.updateFrom(*param)) {
2301 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2302 mName, pipelineDelay.value);
2303 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002304 (void)mPipelineWatcher.lock()->pipelineDelay(
2305 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002306 }
2307 }
2308 if (param->forInput()) {
2309 C2PortActualDelayTuning::input inputDelay;
2310 if (inputDelay.updateFrom(*param)) {
2311 ALOGV("[%s] onWorkDone: updating input delay %u",
2312 mName, inputDelay.value);
2313 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002314 (void)mPipelineWatcher.lock()->inputDelay(
2315 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002316 }
2317 }
2318 if (param->forOutput()) {
2319 C2PortActualDelayTuning::output outputDelay;
2320 if (outputDelay.updateFrom(*param)) {
2321 ALOGV("[%s] onWorkDone: updating output delay %u",
2322 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002323 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002324 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002325 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002326
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002327 }
2328 }
2329 break;
2330 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002331 case C2PortTunnelSystemTime::CORE_INDEX: {
2332 C2PortTunnelSystemTime::output frameRenderTime;
2333 if (frameRenderTime.updateFrom(*param)) {
2334 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2335 mName, (long long)frameRenderTime.value,
2336 (long long)worklet->output.ordinal.timestamp.peekll());
2337 mCCodecCallback->onOutputFramesRendered(
2338 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2339 }
2340 break;
2341 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002342 case C2StreamTunnelHoldRender::CORE_INDEX: {
2343 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2344 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2345 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2346 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2347 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2348 mCCodecCallback->onFirstTunnelFrameReady();
2349 break;
2350 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002351 default:
2352 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2353 mName, param->index());
2354 break;
2355 }
2356 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002357 if (newInputDelay || newPipelineDelay) {
2358 Mutexed<Input>::Locked input(mInput);
2359 size_t newNumSlots =
2360 newInputDelay.value_or(input->inputDelay) +
2361 newPipelineDelay.value_or(input->pipelineDelay) +
2362 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002363 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002364 if (input->buffers->isArrayMode()) {
2365 if (input->numSlots >= newNumSlots) {
2366 input->numExtraSlots = 0;
2367 } else {
2368 input->numExtraSlots = newNumSlots - input->numSlots;
2369 }
2370 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2371 mName, input->numExtraSlots);
2372 } else {
2373 input->numSlots = newNumSlots;
2374 }
2375 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002376 size_t numOutputSlots = 0;
2377 uint32_t reorderDepth = 0;
2378 bool outputBuffersChanged = false;
2379 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2380 Mutexed<Output>::Locked output(mOutput);
2381 if (!output->buffers) {
2382 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002383 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002384 numOutputSlots = output->numSlots;
2385 if (newReorderKey) {
2386 output->buffers->setReorderKey(newReorderKey.value());
2387 }
2388 if (newReorderDepth) {
2389 output->buffers->setReorderDepth(newReorderDepth.value());
2390 }
2391 reorderDepth = output->buffers->getReorderDepth();
2392 if (newOutputDelay) {
2393 output->outputDelay = newOutputDelay.value();
2394 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2395 if (output->numSlots < numOutputSlots) {
2396 output->numSlots = numOutputSlots;
2397 if (output->buffers->isArrayMode()) {
2398 OutputBuffersArray *array =
2399 (OutputBuffersArray *)output->buffers.get();
2400 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2401 mName, numOutputSlots);
2402 array->grow(numOutputSlots);
2403 outputBuffersChanged = true;
2404 }
2405 }
2406 }
2407 numOutputSlots = output->numSlots;
2408 }
2409 if (outputBuffersChanged) {
2410 mCCodecCallback->onOutputBuffersChanged();
2411 }
2412 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002413 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002414 {
2415 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2416 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002417 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002418 if (output->surface) {
2419 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2420 }
2421 }
2422 if (maxDequeueCount > 0) {
2423 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002424 }
2425 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002426
Pawin Vongmasa36653902018-11-15 00:10:25 -08002427 int32_t flags = 0;
2428 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002429 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002430 ALOGV("[%s] onWorkDone: output EOS", mName);
2431 }
2432
Pawin Vongmasa36653902018-11-15 00:10:25 -08002433 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2434 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2435 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2436 // shall correspond to the client input timesamp (in customOrdinal). By using the
2437 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2438 // produces multiple output.
2439 c2_cntr64_t timestamp =
2440 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2441 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002442 if (mInputSurface != nullptr) {
2443 // When using input surface we need to restore the original input timestamp.
2444 timestamp = work->input.ordinal.customOrdinal;
2445 }
My Name6bd9a7d2022-03-25 12:37:58 -07002446 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2447 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002448 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2449 mName,
2450 work->input.ordinal.customOrdinal.peekll(),
2451 work->input.ordinal.timestamp.peekll(),
2452 worklet->output.ordinal.timestamp.peekll(),
2453 timestamp.peekll());
2454
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002455 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002456 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002457 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002458 if (!output->buffers) {
2459 return false;
2460 }
2461 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002462 output->buffers->updateSkipCutBuffer(outputFormat);
2463 output->buffers->setFormat(outputFormat);
2464 }
2465 if (!notifyClient) {
2466 return false;
2467 }
2468 size_t index;
2469 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002470 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002471 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002472 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002473 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2474
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002475 // TRICKY: we want popped buffers reported in order, so sending
2476 // the callback while holding the lock here. This assumes that
2477 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2478 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002479 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002480 } else {
2481 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002482 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002483 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002484 return false;
2485 }
2486 }
2487
Wonsik Kimec585c32021-10-01 01:11:00 -07002488 bool drop = false;
2489 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2490 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2491 drop = true;
2492 }
2493
Marc Kassisec910342022-11-25 11:43:05 +01002494 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2495 // HAL, the flag is then removed in the corresponding output buffer.
2496 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2497 flags |= BUFFER_FLAG_DECODE_ONLY;
2498 }
2499
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002500 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002501 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002502 if (mOutputFormat != outputFormat) {
2503 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2504 mName, work->input.ordinal.frameIndex.peekull());
2505 mOutputFormat = outputFormat;
2506 } else {
2507 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2508 mName, work->input.ordinal.frameIndex.peekull());
2509 notifyClient = false;
2510 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002511 } else {
2512 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2513 mName, work->input.ordinal.frameIndex.peekull());
2514 notifyClient = false;
2515 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002516 }
2517
2518 if (buffer) {
2519 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2520 // TODO: properly translate these to metadata
2521 switch (info->coreIndex().coreIndex()) {
2522 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002523 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002524 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002525 }
2526 break;
2527 default:
2528 break;
2529 }
2530 }
2531 }
2532
2533 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002534 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002535 if (!output->buffers) {
2536 return false;
2537 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002538 output->buffers->pushToStash(
2539 buffer,
2540 notifyClient,
2541 timestamp.peek(),
2542 flags,
2543 outputFormat,
2544 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002545 }
2546 sendOutputBuffers();
2547 return true;
2548}
2549
2550void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002551 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002552 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002553 sp<MediaCodecBuffer> outBuffer;
2554 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002555
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002556 constexpr int kMaxReallocTry = 5;
2557 int reallocTryNum = 0;
2558
Pawin Vongmasa36653902018-11-15 00:10:25 -08002559 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002560 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002561 if (!output->buffers) {
2562 return;
2563 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002564 action = output->buffers->popFromStashAndRegister(
2565 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002566 if (action != OutputBuffers::REALLOCATE) {
2567 reallocTryNum = 0;
2568 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002569 switch (action) {
2570 case OutputBuffers::SKIP:
2571 return;
2572 case OutputBuffers::DISCARD:
2573 break;
2574 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002575 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002576 // TRICKY: we want popped buffers reported in order, so sending
2577 // the callback while holding the lock here. This assumes that
2578 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2579 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002580 if (c2Buffer) {
2581 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2582 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2583 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2584 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2585 uint32_t flag = 0;
2586 std::vector<AccessUnitInfo> accessUnitInfos;
2587 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2588 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2589 bufferMetadata->m.values[nMeta];
2590 flag = convertFlags(bufferMetadataStruct.flags, false);
2591 accessUnitInfos.emplace_back(flag,
2592 static_cast<size_t>(bufferMetadataStruct.size),
2593 static_cast<size_t>(bufferMetadataStruct.timestamp));
2594 }
2595 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2596 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2597 outBuffer->meta()->setObject("accessUnitInfo", obj);
2598 }
2599 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002600 mCallback->onOutputBufferAvailable(index, outBuffer);
2601 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002602 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002603 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002604 if (++reallocTryNum > kMaxReallocTry) {
2605 output.unlock();
2606 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2607 mName, kMaxReallocTry);
2608 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2609 return;
2610 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002611 if (!output->buffers->isArrayMode()) {
2612 output->buffers =
2613 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002614 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002615 static_cast<OutputBuffersArray*>(output->buffers.get())->
2616 realloc(c2Buffer);
2617 output.unlock();
2618 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002619 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002620 case OutputBuffers::RETRY:
2621 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2622 mName);
2623 return;
2624 default:
2625 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2626 "corrupted BufferAction value (%d) "
2627 "returned from popFromStashAndRegister.",
2628 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002629 return;
2630 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002631 }
2632}
2633
Sungtak Lee214ce612023-11-01 10:01:13 +00002634status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2635 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002636 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002637 int maxDequeueCount;
2638 sp<Surface> oldSurface;
2639 {
2640 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2641 maxDequeueCount = outputSurface->maxDequeueBuffers;
2642 oldSurface = outputSurface->surface;
2643 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002644 if (newSurface) {
2645 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002646 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002647 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002648 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002649 } else {
2650 ALOGE("[%s] setting output surface to null", mName);
2651 return INVALID_OPERATION;
2652 }
2653
2654 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2655 C2BlockPool::local_id_t outputPoolId;
2656 {
2657 Mutexed<BlockPools>::Locked pools(mBlockPools);
2658 outputPoolId = pools->outputPoolId;
2659 outputPoolIntf = pools->outputPoolIntf;
2660 }
2661
2662 if (outputPoolIntf) {
2663 if (mComponent->setOutputSurface(
2664 outputPoolId,
2665 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002666 generation,
2667 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002668 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2669 return INVALID_OPERATION;
2670 }
2671 }
2672
2673 {
2674 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2675 output->surface = newSurface;
2676 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002677 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002678 }
2679
Sungtak Lee99144332023-01-26 11:03:14 +00002680 if (oldSurface && pushBlankBuffer) {
2681 // When ReleaseSurface was set from MediaCodec,
2682 // pushing a blank buffer at the end might be necessary.
2683 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2684 if (anw) {
2685 pushBlankBuffersToNativeWindow(anw.get());
2686 }
2687 }
2688
Pawin Vongmasa36653902018-11-15 00:10:25 -08002689 return OK;
2690}
2691
Wonsik Kimab34ed62019-01-31 15:28:46 -08002692PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002693 // Otherwise, component may have stalled work due to input starvation up to
2694 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002695 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2696 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002697 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002698 size_t outputDelay = mOutput.lock()->outputDelay;
2699 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002700 Mutexed<Input>::Locked input(mInput);
2701 n = input->inputDelay + input->pipelineDelay + outputDelay;
2702 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002703 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002704}
2705
Pawin Vongmasa36653902018-11-15 00:10:25 -08002706void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2707 mMetaMode = mode;
2708}
2709
Wonsik Kim596187e2019-10-25 12:44:10 -07002710void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002711 if (mCrypto != nullptr) {
2712 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2713 mCrypto->unsetHeap(entry.second);
2714 }
2715 mHeapSeqNumMap.clear();
2716 if (mHeapSeqNum >= 0) {
2717 mCrypto->unsetHeap(mHeapSeqNum);
2718 mHeapSeqNum = -1;
2719 }
2720 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002721 mCrypto = crypto;
2722}
2723
2724void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2725 mDescrambler = descrambler;
2726}
2727
Songyue Han1e6769b2023-08-30 18:09:27 +00002728uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2729 if (isEncoder) {
2730 return getInputBuffersPixelFormat();
2731 } else {
2732 return getOutputBuffersPixelFormat();
2733 }
2734}
2735
2736uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2737 Mutexed<Input>::Locked input(mInput);
2738 if (input->buffers == nullptr) {
2739 return PIXEL_FORMAT_UNKNOWN;
2740 }
2741 return input->buffers->getPixelFormatIfApplicable();
2742}
2743
2744uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2745 Mutexed<Output>::Locked output(mOutput);
2746 if (output->buffers == nullptr) {
2747 return PIXEL_FORMAT_UNKNOWN;
2748 }
2749 return output->buffers->getPixelFormatIfApplicable();
2750}
2751
2752void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2753 if (isEncoder) {
2754 Mutexed<Input>::Locked input(mInput);
2755 if (input->buffers == nullptr) {
2756 return;
2757 }
2758 input->buffers->resetPixelFormatIfApplicable();
2759 } else {
2760 Mutexed<Output>::Locked output(mOutput);
2761 if (output->buffers == nullptr) {
2762 return;
2763 }
2764 output->buffers->resetPixelFormatIfApplicable();
2765 }
2766}
2767
Pawin Vongmasa36653902018-11-15 00:10:25 -08002768status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2769 // C2_OK is always translated to OK.
2770 if (c2s == C2_OK) {
2771 return OK;
2772 }
2773
2774 // Operation-dependent translation
2775 // TODO: Add as necessary
2776 switch (c2op) {
2777 case C2_OPERATION_Component_start:
2778 switch (c2s) {
2779 case C2_NO_MEMORY:
2780 return NO_MEMORY;
2781 default:
2782 return UNKNOWN_ERROR;
2783 }
2784 default:
2785 break;
2786 }
2787
2788 // Backup operation-agnostic translation
2789 switch (c2s) {
2790 case C2_BAD_INDEX:
2791 return BAD_INDEX;
2792 case C2_BAD_VALUE:
2793 return BAD_VALUE;
2794 case C2_BLOCKING:
2795 return WOULD_BLOCK;
2796 case C2_DUPLICATE:
2797 return ALREADY_EXISTS;
2798 case C2_NO_INIT:
2799 return NO_INIT;
2800 case C2_NO_MEMORY:
2801 return NO_MEMORY;
2802 case C2_NOT_FOUND:
2803 return NAME_NOT_FOUND;
2804 case C2_TIMED_OUT:
2805 return TIMED_OUT;
2806 case C2_BAD_STATE:
2807 case C2_CANCELED:
2808 case C2_CANNOT_DO:
2809 case C2_CORRUPTED:
2810 case C2_OMITTED:
2811 case C2_REFUSED:
2812 return UNKNOWN_ERROR;
2813 default:
2814 return -static_cast<status_t>(c2s);
2815 }
2816}
2817
Pawin Vongmasa36653902018-11-15 00:10:25 -08002818} // namespace android