blob: f58dc650d5deaa4177498283be6bf5979d225962 [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;
Arun Johnson82174a12024-02-27 04:53:59 +0000555 size_t srcOffset = offset;
Arun Johnson564f3a92024-02-01 19:09:45 +0000556 size_t outBufferSize = 0;
557 uint32_t cryptoInfoIdx = 0;
558 int32_t heapSeqNum = getHeapSeqNum(memory);
559 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
560 hardware::drm::V1_0::DestinationBuffer dst;
561 dst.type = DrmBufferType::SHARED_MEMORY;
562 IMemoryToSharedBuffer(
563 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
564 for (int i = 0; i < bufferInfos->value.size(); i++) {
565 if (bufferInfos->value[i].mSize > 0) {
566 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[cryptoInfoIdx++]);
Arun Johnson82174a12024-02-27 04:53:59 +0000567 src.offset = srcOffset;
568 src.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000569 result = mCrypto->decrypt(
570 (uint8_t*)info->mKey,
571 (uint8_t*)info->mIv,
572 info->mMode,
573 info->mPattern,
574 src,
Arun Johnson82174a12024-02-27 04:53:59 +0000575 0,
Arun Johnson564f3a92024-02-01 19:09:45 +0000576 info->mSubSamples,
577 info->mNumSubSamples,
578 dst,
579 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +0000580 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000581 if (result < 0) {
582 ALOGI("[%s] attachEncryptedBuffers: decrypt failed: result = %zd",
583 mName, result);
584 return result;
585 }
586 if (wView.error() == C2_OK) {
587 if (wView.size() < result) {
588 ALOGI("[%s] attachEncryptedBuffers: block size too small:"
589 "size=%u result=%zd (non-secure)", mName, wView.size(), result);
590 return UNKNOWN_ERROR;
591 }
592 memcpy(wView.data(), mDecryptDestination->unsecurePointer(), result);
593 bufferInfos->value[i].mSize = result;
594 wView.setOffset(wView.offset() + result);
595 }
596 outBufferSize += result;
597 }
598 }
599 if (wView.error() == C2_OK) {
600 wView.setOffset(0);
601 }
602 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
Arun Johnson82174a12024-02-27 04:53:59 +0000603 block->share(0, outBufferSize, C2Fence{}))};
Arun Johnson564f3a92024-02-01 19:09:45 +0000604 if (!buffer->copy(c2Buffer)) {
605 ALOGI("[%s] attachEncryptedBuffers: buffer copy failed", mName);
606 return -ENOSYS;
607 }
608 return OK;
609}
610
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800611status_t CCodecBufferChannel::attachEncryptedBuffer(
612 const sp<hardware::HidlMemory> &memory,
613 bool secure,
614 const uint8_t *key,
615 const uint8_t *iv,
616 CryptoPlugin::Mode mode,
617 CryptoPlugin::Pattern pattern,
618 size_t offset,
619 const CryptoPlugin::SubSample *subSamples,
620 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000621 const sp<MediaCodecBuffer> &buffer,
622 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800623 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
624 static const C2MemoryUsage kDefaultReadWriteUsage{
625 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
626
627 size_t size = 0;
628 for (size_t i = 0; i < numSubSamples; ++i) {
629 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
630 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700631 if (size == 0) {
632 buffer->setRange(0, 0);
633 return OK;
634 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800635 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
636 std::shared_ptr<C2LinearBlock> block;
637 c2_status_t err = pool->fetchLinearBlock(
638 size,
639 secure ? kSecureUsage : kDefaultReadWriteUsage,
640 &block);
641 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700642 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
643 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800644 return NO_MEMORY;
645 }
646 if (!secure) {
647 ensureDecryptDestination(size);
648 }
649 ssize_t result = -1;
650 ssize_t codecDataOffset = 0;
651 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800652 int32_t heapSeqNum = getHeapSeqNum(memory);
653 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
654 hardware::drm::V1_0::DestinationBuffer dst;
655 if (secure) {
656 dst.type = DrmBufferType::NATIVE_HANDLE;
657 dst.secureMemory = hardware::hidl_handle(block->handle());
658 } else {
659 dst.type = DrmBufferType::SHARED_MEMORY;
660 IMemoryToSharedBuffer(
661 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
662 }
663 result = mCrypto->decrypt(
664 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000665 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800666 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700667 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800668 return result;
669 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800670 } else {
671 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
672 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
673 hidl_vec<SubSample> hidlSubSamples;
674 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
675
676 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
677 hardware::cas::native::V1_0::DestinationBuffer dst;
678 if (secure) {
679 dst.type = BufferType::NATIVE_HANDLE;
680 dst.secureMemory = hardware::hidl_handle(block->handle());
681 } else {
682 dst.type = BufferType::SHARED_MEMORY;
683 dst.nonsecureMemory = src;
684 }
685
686 CasStatus status = CasStatus::OK;
687 hidl_string detailedError;
688 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
689
690 if (key != nullptr) {
691 sctrl = (ScramblingControl)key[0];
692 // Adjust for the PES offset
693 codecDataOffset = key[2] | (key[3] << 8);
694 }
695
696 auto returnVoid = mDescrambler->descramble(
697 sctrl,
698 hidlSubSamples,
699 src,
700 0,
701 dst,
702 0,
703 [&status, &result, &detailedError] (
704 CasStatus _status, uint32_t _bytesWritten,
705 const hidl_string& _detailedError) {
706 status = _status;
707 result = (ssize_t)_bytesWritten;
708 detailedError = _detailedError;
709 });
Arun Johnson634d0802023-02-14 22:07:51 +0000710 if (errorDetailMsg) {
711 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
712 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800713 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
714 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
715 mName, returnVoid.description().c_str(), status, result);
716 return UNKNOWN_ERROR;
717 }
718
719 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700720 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
721 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800722 return BAD_VALUE;
723 }
724 }
725 if (!secure) {
726 C2WriteView view = block->map().get();
727 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700728 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
729 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800730 return UNKNOWN_ERROR;
731 }
732 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700733 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
734 "(non-secure)",
735 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800736 return UNKNOWN_ERROR;
737 }
738 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
739 }
740 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
741 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
742 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700743 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800744 return -ENOSYS;
745 }
746 return OK;
747}
748
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
750 QueueGuard guard(mSync);
751 if (!guard.isRunning()) {
752 ALOGD("[%s] No more buffers should be queued at current state.", mName);
753 return -ENOSYS;
754 }
755 return queueInputBufferInternal(buffer);
756}
757
758status_t CCodecBufferChannel::queueSecureInputBuffer(
759 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
760 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
761 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
762 AString *errorDetailMsg) {
763 QueueGuard guard(mSync);
764 if (!guard.isRunning()) {
765 ALOGD("[%s] No more buffers should be queued at current state.", mName);
766 return -ENOSYS;
767 }
768
769 if (!hasCryptoOrDescrambler()) {
770 return -ENOSYS;
771 }
772 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
773
Sungtak Lee04b30352020-07-27 13:57:25 -0700774 std::shared_ptr<C2LinearBlock> block;
775 size_t allocSize = buffer->size();
776 size_t bufferSize = 0;
777 c2_status_t blockRes = C2_OK;
778 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000779 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
780 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700781 if (mSendEncryptedInfoBuffer) {
782 static const C2MemoryUsage kDefaultReadWriteUsage{
783 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
784 constexpr int kAllocGranule0 = 1024 * 64;
785 constexpr int kAllocGranule1 = 1024 * 1024;
786 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
787 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
788 if (allocSize <= kAllocGranule1) {
789 bufferSize = align(allocSize, kAllocGranule0);
790 } else {
791 bufferSize = align(allocSize, kAllocGranule1);
792 }
793 blockRes = pool->fetchLinearBlock(
794 bufferSize, kDefaultReadWriteUsage, &block);
795
796 if (blockRes == C2_OK) {
797 C2WriteView view = block->map().get();
798 if (view.error() == C2_OK && view.size() == bufferSize) {
799 copied = true;
800 // TODO: only copy clear sections
801 memcpy(view.data(), buffer->data(), allocSize);
802 }
803 }
804 }
805
806 if (!copied) {
807 block.reset();
808 }
809
Pawin Vongmasa36653902018-11-15 00:10:25 -0800810 ssize_t result = -1;
811 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700812 if (numSubSamples == 1
813 && subSamples[0].mNumBytesOfClearData == 0
814 && subSamples[0].mNumBytesOfEncryptedData == 0) {
815 // We don't need to go through crypto or descrambler if the input is empty.
816 result = 0;
817 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700818 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800819 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700820 destination.type = DrmBufferType::NATIVE_HANDLE;
821 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700823 destination.type = DrmBufferType::SHARED_MEMORY;
824 IMemoryToSharedBuffer(
825 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800826 }
Robert Shih895fba92019-07-16 16:29:44 -0700827 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 encryptedBuffer->fillSourceBuffer(&source);
829 result = mCrypto->decrypt(
830 key, iv, mode, pattern, source, buffer->offset(),
831 subSamples, numSubSamples, destination, errorDetailMsg);
832 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700833 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834 return result;
835 }
Robert Shih895fba92019-07-16 16:29:44 -0700836 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800837 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
838 }
839 } else {
840 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
841 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
842 hidl_vec<SubSample> hidlSubSamples;
843 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
844
845 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
846 encryptedBuffer->fillSourceBuffer(&srcBuffer);
847
848 DestinationBuffer dstBuffer;
849 if (secure) {
850 dstBuffer.type = BufferType::NATIVE_HANDLE;
851 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
852 } else {
853 dstBuffer.type = BufferType::SHARED_MEMORY;
854 dstBuffer.nonsecureMemory = srcBuffer;
855 }
856
857 CasStatus status = CasStatus::OK;
858 hidl_string detailedError;
859 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
860
861 if (key != nullptr) {
862 sctrl = (ScramblingControl)key[0];
863 // Adjust for the PES offset
864 codecDataOffset = key[2] | (key[3] << 8);
865 }
866
867 auto returnVoid = mDescrambler->descramble(
868 sctrl,
869 hidlSubSamples,
870 srcBuffer,
871 0,
872 dstBuffer,
873 0,
874 [&status, &result, &detailedError] (
875 CasStatus _status, uint32_t _bytesWritten,
876 const hidl_string& _detailedError) {
877 status = _status;
878 result = (ssize_t)_bytesWritten;
879 detailedError = _detailedError;
880 });
881
882 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
883 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
884 mName, returnVoid.description().c_str(), status, result);
885 return UNKNOWN_ERROR;
886 }
887
888 if (result < codecDataOffset) {
889 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
890 return BAD_VALUE;
891 }
892
893 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
894
895 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
896 encryptedBuffer->copyDecryptedContentFromMemory(result);
897 }
898 }
899
900 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700901
902 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903}
904
Arun Johnson564f3a92024-02-01 19:09:45 +0000905status_t CCodecBufferChannel::queueSecureInputBuffers(
906 const sp<MediaCodecBuffer> &buffer,
907 bool secure,
908 AString *errorDetailMsg) {
909 QueueGuard guard(mSync);
910 if (!guard.isRunning()) {
911 ALOGD("[%s] No more buffers should be queued at current state.", mName);
912 return -ENOSYS;
913 }
914
915 if (!hasCryptoOrDescrambler()) {
916 ALOGE("queueSecureInputBuffers requires a Crypto/descrambler Object");
917 return -ENOSYS;
918 }
919 sp<RefBase> obj;
920 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
921 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
922 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
923 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
924 if (secure || mCrypto == nullptr) {
925 if (cryptoInfos->value.size() != 1) {
926 ALOGE("Cannot decrypt multiple access units on native handles");
927 return -ENOSYS;
928 }
929 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
930 if (info == nullptr) {
931 ALOGE("Cannot decrypt, CryptoInfos are null");
932 return -ENOSYS;
933 }
934 return queueSecureInputBuffer(
935 buffer,
936 secure,
937 info->mKey,
938 info->mIv,
939 info->mMode,
940 info->mPattern,
941 info->mSubSamples,
942 info->mNumSubSamples,
943 errorDetailMsg);
944 }
945 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
946
947 std::shared_ptr<C2LinearBlock> block;
948 size_t allocSize = buffer->size();
949 size_t bufferSize = 0;
950 c2_status_t blockRes = C2_OK;
951 bool copied = false;
952 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
953 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
954 if (mSendEncryptedInfoBuffer) {
955 static const C2MemoryUsage kDefaultReadWriteUsage{
956 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
957 constexpr int kAllocGranule0 = 1024 * 64;
958 constexpr int kAllocGranule1 = 1024 * 1024;
959 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
960 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
961 if (allocSize <= kAllocGranule1) {
962 bufferSize = align(allocSize, kAllocGranule0);
963 } else {
964 bufferSize = align(allocSize, kAllocGranule1);
965 }
966 blockRes = pool->fetchLinearBlock(
967 bufferSize, kDefaultReadWriteUsage, &block);
968
969 if (blockRes == C2_OK) {
970 C2WriteView view = block->map().get();
971 if (view.error() == C2_OK && view.size() == bufferSize) {
972 copied = true;
973 // TODO: only copy clear sections
974 memcpy(view.data(), buffer->data(), allocSize);
975 }
976 }
977 }
978
979 if (!copied) {
980 block.reset();
981 }
982 // size of cryptoInfo and accessUnitInfo should be the same?
983 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +0000984 size_t srcOffset = 0;
Arun Johnson564f3a92024-02-01 19:09:45 +0000985 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);
Arun Johnson82174a12024-02-27 04:53:59 +0000997 srcOffset = source.offset;
Arun Johnson564f3a92024-02-01 19:09:45 +0000998 for (int i = 0 ; i < bufferInfos->value.size(); i++) {
999 if (bufferInfos->value[i].mSize > 0) {
1000 std::unique_ptr<CodecCryptoInfo> info =
1001 std::move(cryptoInfos->value[cryptoInfoIdx++]);
1002 if (info->mNumSubSamples == 1
1003 && info->mSubSamples[0].mNumBytesOfClearData == 0
1004 && info->mSubSamples[0].mNumBytesOfEncryptedData == 0) {
1005 // no data so we only populate the bufferInfo
1006 result = 0;
1007 } else {
Arun Johnson82174a12024-02-27 04:53:59 +00001008 source.offset = srcOffset;
1009 source.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001010 result = mCrypto->decrypt(
1011 (uint8_t*)info->mKey,
1012 (uint8_t*)info->mIv,
1013 info->mMode,
1014 info->mPattern,
1015 source,
Arun Johnson82174a12024-02-27 04:53:59 +00001016 buffer->offset(),
Arun Johnson564f3a92024-02-01 19:09:45 +00001017 info->mSubSamples,
1018 info->mNumSubSamples,
1019 destination,
1020 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +00001021 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001022 if (result < 0) {
1023 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
1024 return result;
1025 }
1026 if (destination.type == DrmBufferType::SHARED_MEMORY && mappedBlock) {
1027 mappedBlock->copyDecryptedContent(mDecryptDestination, result);
1028 }
1029 bufferInfos->value[i].mSize = result;
1030 outBufferSize += result;
1031 }
1032 }
1033 }
Arun Johnson82174a12024-02-27 04:53:59 +00001034 buffer->setRange(0, outBufferSize);
Arun Johnson564f3a92024-02-01 19:09:45 +00001035 }
1036 return queueInputBufferInternal(buffer, block, bufferSize);
1037}
1038
Pawin Vongmasa36653902018-11-15 00:10:25 -08001039void CCodecBufferChannel::feedInputBufferIfAvailable() {
1040 QueueGuard guard(mSync);
1041 if (!guard.isRunning()) {
1042 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1043 return;
1044 }
1045 feedInputBufferIfAvailableInternal();
1046}
1047
1048void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +09001049 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001050 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001051 }
1052 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001053 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001054 if (!output->buffers ||
1055 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -07001056 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001057 return;
1058 }
1059 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001060 size_t numActiveSlots = 0;
1061 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001062 sp<MediaCodecBuffer> inBuffer;
1063 size_t index;
1064 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001065 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001066 numActiveSlots = input->buffers->numActiveSlots();
1067 if (numActiveSlots >= input->numSlots) {
1068 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001069 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001070 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001071 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001072 break;
1073 }
1074 }
1075 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1076 mCallback->onInputBufferAvailable(index, inBuffer);
1077 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001078 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001079}
1080
1081status_t CCodecBufferChannel::renderOutputBuffer(
1082 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001083 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001084 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001085 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001086 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001087 Mutexed<Output>::Locked output(mOutput);
1088 if (output->buffers) {
1089 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090 }
1091 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001092 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1093 // set to true.
1094 sendOutputBuffers();
1095 // input buffer feeding may have been gated by pending output buffers
1096 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001097 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001098 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001099 std::call_once(mRenderWarningFlag, [this] {
1100 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1101 "timestamp or render=true with non-video buffers. Apps should "
1102 "call releaseOutputBuffer() with render=false for those.",
1103 mName);
1104 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001105 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 return INVALID_OPERATION;
1107 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001108
1109#if 0
1110 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1111 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1112 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1113 AString res;
1114 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1115 if (ix) res.append(", ");
1116 res.append(*((int32_t*)info.get() + (ix / 4)));
1117 }
1118 ALOGV(" [%s]", res.c_str());
1119 }
1120#endif
1121 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1122 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1123 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1124 bool flip = rotation && (rotation->flip & 1);
1125 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001126
1127 {
1128 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1129 if (output->surface == nullptr) {
1130 ALOGI("[%s] cannot render buffer without surface", mName);
1131 return OK;
1132 }
1133 int64_t frameIndex;
1134 buffer->meta()->findInt64("frameIndex", &frameIndex);
1135 if (output->rotation.count(frameIndex) != 0) {
1136 auto it = output->rotation.find(frameIndex);
1137 quarters = (it->second / 90) & 3;
1138 output->rotation.erase(it);
1139 }
1140 }
1141
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 uint32_t transform = 0;
1143 switch (quarters) {
1144 case 0: // no rotation
1145 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1146 break;
1147 case 1: // 90 degrees counter-clockwise
1148 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1149 : HAL_TRANSFORM_ROT_270;
1150 break;
1151 case 2: // 180 degrees
1152 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1153 break;
1154 case 3: // 90 degrees clockwise
1155 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1156 : HAL_TRANSFORM_ROT_90;
1157 break;
1158 }
1159
1160 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1161 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1162 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1163 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1164 if (surfaceScaling) {
1165 videoScalingMode = surfaceScaling->value;
1166 }
1167
1168 // Use dataspace from format as it has the default aspects already applied
1169 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1170 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1171
1172 // HDR static info
1173 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1174 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1175 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1176
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001177 // HDR10 plus info
1178 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1179 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1180 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001181 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1182 hdr10PlusInfo.reset();
1183 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001184
Wonsik Kima79c5522022-01-18 16:29:24 -08001185 // HDR dynamic info
1186 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1187 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1188 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1189 // TODO: make this sticky & enable unset
1190 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1191 hdrDynamicInfo.reset();
1192 }
1193
1194 if (hdr10PlusInfo) {
1195 // C2StreamHdr10PlusInfo is deprecated; components should use
1196 // C2StreamHdrDynamicMetadataInfo
1197 // TODO: #metric
1198 if (hdrDynamicInfo) {
1199 // It is unexpected that C2StreamHdr10PlusInfo and
1200 // C2StreamHdrDynamicMetadataInfo is both present.
1201 // C2StreamHdrDynamicMetadataInfo takes priority.
1202 // TODO: #metric
1203 } else {
1204 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1205 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1206 hdr10PlusInfo->flexCount(),
1207 0u,
1208 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1209 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1210 hdrDynamicInfo = info;
1211 }
1212 }
1213
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1215 if (blocks.size() != 1u) {
1216 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1217 return UNKNOWN_ERROR;
1218 }
1219 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001220 C2Fence c2fence = block.fence();
1221 sp<Fence> fence = Fence::NO_FENCE;
1222 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1223 // Once C2Fence::type() is added, check the exact C2Fence type
1224 if (c2fence.isHW()) {
1225 int fenceFd = c2fence.fd();
1226 fence = sp<Fence>::make(fenceFd);
1227 if (!fence) {
1228 ALOGE("[%s] Failed to allocate a fence", mName);
1229 close(fenceFd);
1230 return NO_MEMORY;
1231 }
1232 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233
1234 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001235 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 timestampNs,
1237 false, // droppable
1238 dataSpace,
1239 Rect(blocks.front().crop().left,
1240 blocks.front().crop().top,
1241 blocks.front().crop().right(),
1242 blocks.front().crop().bottom()),
1243 videoScalingMode,
1244 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001245 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001246 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001248 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001249 // If mastering max and min luminance fields are 0, do not use them.
1250 // It indicates the value may not be present in the stream.
1251 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1252 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1253 struct android_smpte2086_metadata smpte2086_meta = {
1254 .displayPrimaryRed = {
1255 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1256 },
1257 .displayPrimaryGreen = {
1258 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1259 },
1260 .displayPrimaryBlue = {
1261 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1262 },
1263 .whitePoint = {
1264 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1265 },
1266 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1267 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1268 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001269 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001270 hdr.smpte2086 = smpte2086_meta;
1271 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001272 // If the content light level fields are 0, do not use them, it
1273 // indicates the value may not be present in the stream.
1274 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1275 struct android_cta861_3_metadata cta861_meta = {
1276 .maxContentLightLevel = hdrStaticInfo->maxCll,
1277 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1278 };
1279 hdr.validTypes |= HdrMetadata::CTA861_3;
1280 hdr.cta8613 = cta861_meta;
1281 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001282
1283 // does not have valid info
1284 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1285 hdrStaticInfo.reset();
1286 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001287 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001288 if (hdrDynamicInfo
1289 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001290 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1291 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001292 hdrDynamicInfo->m.data,
1293 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001294 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001295 qbi.setHdrMetadata(hdr);
1296 }
Hongguangfc1478a2022-07-20 22:56:06 -07001297 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1298
Brian Lindahl932bf602023-03-09 11:59:48 -07001299 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1300 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1301 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001302 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1303 if (result != OK) {
1304 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001305 if (result == NO_INIT) {
1306 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1307 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001308 return result;
1309 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001310
1311 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1312 ALOGD("[%s] queue buffer successful", mName);
1313 } else {
1314 ALOGV("[%s] queue buffer successful", mName);
1315 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316
1317 int64_t mediaTimeUs = 0;
1318 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001319 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001320 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1321 processRenderedFrames(qbo.frameTimestamps);
1322 } else {
1323 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1324 // when the frame is queued to the non-display surface
1325 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1326 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327
1328 return OK;
1329}
1330
Brian Lindahl932bf602023-03-09 11:59:48 -07001331void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001332 mTrackedFrames.clear();
1333
1334 int isSurfaceToDisplay = 0;
1335 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1336 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1337 // No frame tracking is needed if we're not sending frames to the display
1338 if (!mIsSurfaceToDisplay) {
1339 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1340 return;
1341 }
1342
Brian Lindahl932bf602023-03-09 11:59:48 -07001343 int hasPresentFenceTimes = 0;
1344 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1345 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001346 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001347 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1348 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001349}
1350
1351void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1352 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1353 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1354 // so track the frame as if the desired render time is now.
1355 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1356 if (desiredRenderTimeNs < nowNs) {
1357 desiredRenderTimeNs = nowNs;
1358 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001359
1360 // If the render time is more than a second from now, then pretend the frame is supposed to be
1361 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1362 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1363 // processRenderedFrames.
1364 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1365 desiredRenderTimeNs = nowNs;
1366 }
1367
Brian Lindahl932bf602023-03-09 11:59:48 -07001368 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1369 // actually rendered.
1370 TrackedFrame frame;
1371 frame.number = qbo.nextFrameNumber - 1;
1372 frame.mediaTimeUs = mediaTimeUs;
1373 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1374 frame.latchTime = -1;
1375 frame.presentFence = nullptr;
1376 mTrackedFrames.push_back(frame);
1377}
1378
1379void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1380 // Grab the latch times and present fences from the frame event deltas
1381 for (const auto& delta : deltas) {
1382 for (auto& frame : mTrackedFrames) {
1383 if (delta.getFrameNumber() == frame.number) {
1384 delta.getLatchTime(&frame.latchTime);
1385 delta.getDisplayPresentFence(&frame.presentFence);
1386 }
1387 }
1388 }
1389
1390 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1391 // in fact, been rendered.
1392 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1393 while (!mTrackedFrames.empty()) {
1394 TrackedFrame & frame = mTrackedFrames.front();
1395 // Frames that should have been rendered at least 100ms in the past are checked
1396 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1397 break;
1398 }
1399
1400 // If we don't have a render time by now, then consider the frame as dropped
1401 int64_t renderTimeNs = getRenderTimeNs(frame);
1402 if (renderTimeNs != -1) {
1403 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1404 }
1405 mTrackedFrames.pop_front();
1406 }
1407}
1408
1409int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1410 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1411 if (!mHasPresentFenceTimes) {
1412 if (frame.latchTime == -1) {
1413 ALOGD("no latch time for frame %d", (int) frame.number);
1414 return -1;
1415 }
1416 return frame.latchTime;
1417 }
1418
1419 if (frame.presentFence == nullptr) {
1420 ALOGW("no present fence for frame %d", (int) frame.number);
1421 return -1;
1422 }
1423
1424 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1425
1426 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1427 ALOGW("invalid signal time for frame %d", (int) frame.number);
1428 return -1;
1429 }
1430
1431 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1432 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1433 return -1;
1434 }
1435
1436 return actualRenderTimeNs;
1437}
1438
1439void CCodecBufferChannel::pollForRenderedBuffers() {
1440 FrameEventHistoryDelta delta;
1441 mComponent->pollForRenderedFrames(&delta);
1442 processRenderedFrames(delta);
1443}
1444
Sungtak Lee214ce612023-11-01 10:01:13 +00001445void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001446 // Note: Since this is called asynchronously from IProducerListener not
1447 // knowing the internal state of CCodec/CCodecBufferChannel,
1448 // prevent mComponent from being destroyed by holding the shared reference
1449 // during this interface being executed.
1450 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1451 if (comp) {
1452 comp->onBufferReleasedFromOutputSurface(generation);
1453 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001454}
1455
Pawin Vongmasa36653902018-11-15 00:10:25 -08001456status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1457 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1458 bool released = false;
1459 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001460 Mutexed<Input>::Locked input(mInput);
1461 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001462 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001463 }
1464 }
1465 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001466 Mutexed<Output>::Locked output(mOutput);
1467 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468 released = true;
1469 }
1470 }
1471 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001472 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001473 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001474 } else {
1475 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1476 }
1477 return OK;
1478}
1479
1480void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1481 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001482 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001483
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001484 if (!input->buffers) {
1485 ALOGE("getInputBufferArray: No Input Buffers allocated");
1486 return;
1487 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001488 if (!input->buffers->isArrayMode()) {
1489 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490 }
1491
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001492 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001493}
1494
1495void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1496 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001497 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001498 if (!output->buffers) {
1499 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1500 return;
1501 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001502 if (!output->buffers->isArrayMode()) {
1503 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001504 }
1505
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001506 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507}
1508
1509status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001510 const sp<AMessage> &inputFormat,
1511 const sp<AMessage> &outputFormat,
1512 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001513 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1514 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001515 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516 C2PortReorderBufferDepthTuning::output reorderDepth;
1517 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001518 C2PortActualDelayTuning::input inputDelay(0);
1519 C2PortActualDelayTuning::output outputDelay(0);
1520 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001521 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001522
Pawin Vongmasa36653902018-11-15 00:10:25 -08001523 c2_status_t err = mComponent->query(
1524 {
1525 &iStreamFormat,
1526 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001527 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 &reorderDepth,
1529 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001530 &inputDelay,
1531 &pipelineDelay,
1532 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001533 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534 },
1535 {},
1536 C2_DONT_BLOCK,
1537 nullptr);
1538 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001539 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 return UNKNOWN_ERROR;
1541 }
1542 } else if (err != C2_OK) {
1543 return UNKNOWN_ERROR;
1544 }
1545
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001546 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1547 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1548 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1549
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001550 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1551 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001552
Pawin Vongmasa36653902018-11-15 00:10:25 -08001553 // TODO: get this from input format
1554 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1555
Sungtak Lee04b30352020-07-27 13:57:25 -07001556 // secure mode is a static parameter (shall not change in the executing state)
1557 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1558
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001560 int poolMask = GetCodec2PoolMask();
1561 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562
1563 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001564 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001565 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001566 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1567 API_REFLECTION |
1568 API_VALUES |
1569 API_CURRENT_VALUES |
1570 API_DEPENDENCY |
1571 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001572 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1573 C2StreamSampleRateInfo::input sampleRate(0u);
1574 C2StreamChannelCountInfo::input channelCount(0u);
1575 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001576 std::shared_ptr<C2BlockPool> pool;
1577 {
1578 Mutexed<BlockPools>::Locked pools(mBlockPools);
1579
1580 // set default allocator ID.
1581 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001582 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583
1584 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1585 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1586 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001587 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001588 std::vector<C2Param *> stackParams({&featuresSetting});
1589 if (audioEncoder) {
1590 stackParams.push_back(&encoderFrameSize);
1591 stackParams.push_back(&sampleRate);
1592 stackParams.push_back(&channelCount);
1593 stackParams.push_back(&pcmEncoding);
1594 } else {
1595 encoderFrameSize.invalidate();
1596 sampleRate.invalidate();
1597 channelCount.invalidate();
1598 pcmEncoding.invalidate();
1599 }
1600 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1602 C2_DONT_BLOCK,
1603 &params);
1604 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1605 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1606 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001607 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608 C2PortAllocatorsTuning::input *inputAllocators =
1609 C2PortAllocatorsTuning::input::From(params[0].get());
1610 if (inputAllocators && inputAllocators->flexCount() > 0) {
1611 std::shared_ptr<C2Allocator> allocator;
1612 // verify allocator IDs and resolve default allocator
1613 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1614 if (allocator) {
1615 pools->inputAllocatorId = allocator->getId();
1616 } else {
1617 ALOGD("[%s] component requested invalid input allocator ID %u",
1618 mName, inputAllocators->m.values[0]);
1619 }
1620 }
1621 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001622 if (featuresSetting) {
1623 apiFeatures = featuresSetting.value;
1624 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625
1626 // TODO: use C2Component wrapper to associate this pool with ourselves
1627 if ((poolMask >> pools->inputAllocatorId) & 1) {
1628 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1629 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1630 mName, pools->inputAllocatorId,
1631 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1632 asString(err), err);
1633 } else {
1634 err = C2_NOT_FOUND;
1635 }
1636 if (err != C2_OK) {
1637 C2BlockPool::local_id_t inputPoolId =
1638 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1639 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1640 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1641 mName, (unsigned long long)inputPoolId,
1642 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1643 asString(err), err);
1644 if (err != C2_OK) {
1645 return NO_MEMORY;
1646 }
1647 }
1648 pools->inputPool = pool;
1649 }
1650
Wonsik Kim51051262018-11-28 13:59:05 -08001651 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001652 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001653 input->inputDelay = inputDelayValue;
1654 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001655 input->numSlots = numInputSlots;
1656 input->extraBuffers.flush();
1657 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001658 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001659 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1660 input->frameReassembler.init(
1661 pool,
1662 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1663 encoderFrameSize.value,
1664 sampleRate.value,
1665 channelCount.value,
1666 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1667 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001668 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1669 // For encrypted content, framework decrypts source buffer (ashmem) into
1670 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001671 if (!buffersBoundToCodec
1672 && !input->frameReassembler
1673 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001674 input->buffers.reset(new SlotInputBuffers(mName));
1675 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001676 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001677 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001679 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001680 // This is to ensure buffers do not get released prematurely.
1681 // TODO: handle this without going into array mode
1682 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001684 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001685 }
1686 } else {
1687 if (hasCryptoOrDescrambler()) {
1688 int32_t capacity = kLinearBufferSize;
1689 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1690 if ((size_t)capacity > kMaxLinearBufferSize) {
1691 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1692 capacity = kMaxLinearBufferSize;
1693 }
1694 if (mDealer == nullptr) {
1695 mDealer = new MemoryDealer(
1696 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001697 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 "EncryptedLinearInputBuffers");
1699 mDecryptDestination = mDealer->allocate((size_t)capacity);
1700 }
1701 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001702 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1703 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704 } else {
1705 mHeapSeqNum = -1;
1706 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001707 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001708 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001709 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001710 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001712 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001713 }
1714 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001715 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716
1717 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001718 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001719 } else {
1720 // TODO: error
1721 }
Wonsik Kim51051262018-11-28 13:59:05 -08001722
1723 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001724 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001725 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 }
1727
1728 if (outputFormat != nullptr) {
1729 sp<IGraphicBufferProducer> outputSurface;
1730 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001731 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 {
1733 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001734 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001735 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001736 outputSurface = output->surface ?
1737 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001738 if (outputSurface) {
1739 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1740 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001741 outputGeneration = output->generation;
1742 }
1743
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001744 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001746 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747
1748 {
1749 Mutexed<BlockPools>::Locked pools(mBlockPools);
1750
David Stevensc3fbb282021-01-18 18:11:20 +09001751 prevOutputPoolId = pools->outputPoolId;
1752
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753 // set default allocator ID.
1754 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001755 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001756
1757 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1758 // unsuccessful.
1759 std::vector<std::unique_ptr<C2Param>> params;
1760 err = mComponent->query({ },
1761 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1762 C2_DONT_BLOCK,
1763 &params);
1764 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1765 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1766 mName, params.size(), asString(err), err);
1767 } else if (err == C2_OK && params.size() == 1) {
1768 C2PortAllocatorsTuning::output *outputAllocators =
1769 C2PortAllocatorsTuning::output::From(params[0].get());
1770 if (outputAllocators && outputAllocators->flexCount() > 0) {
1771 std::shared_ptr<C2Allocator> allocator;
1772 // verify allocator IDs and resolve default allocator
1773 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1774 if (allocator) {
1775 pools->outputAllocatorId = allocator->getId();
1776 } else {
1777 ALOGD("[%s] component requested invalid output allocator ID %u",
1778 mName, outputAllocators->m.values[0]);
1779 }
1780 }
1781 }
1782
1783 // use bufferqueue if outputting to a surface.
1784 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1785 // if unsuccessful.
1786 if (outputSurface) {
1787 params.clear();
1788 err = mComponent->query({ },
1789 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1790 C2_DONT_BLOCK,
1791 &params);
1792 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1793 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1794 mName, params.size(), asString(err), err);
1795 } else if (err == C2_OK && params.size() == 1) {
1796 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1797 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1798 if (surfaceAllocator) {
1799 std::shared_ptr<C2Allocator> allocator;
1800 // verify allocator IDs and resolve default allocator
1801 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1802 if (allocator) {
1803 pools->outputAllocatorId = allocator->getId();
1804 } else {
1805 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1806 mName, surfaceAllocator->value);
1807 err = C2_BAD_VALUE;
1808 }
1809 }
1810 }
1811 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1812 && err != C2_OK
1813 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1814 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1815 }
1816 }
1817
1818 if ((poolMask >> pools->outputAllocatorId) & 1) {
1819 err = mComponent->createBlockPool(
1820 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1821 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1822 mName, pools->outputAllocatorId,
1823 (unsigned long long)pools->outputPoolId,
1824 asString(err));
1825 } else {
1826 err = C2_NOT_FOUND;
1827 }
1828 if (err != C2_OK) {
1829 // use basic pool instead
1830 pools->outputPoolId =
1831 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1832 }
1833
1834 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1835 // component.
1836 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1837 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1838
1839 std::vector<std::unique_ptr<C2SettingResult>> failures;
1840 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1841 ALOGD("[%s] Configured output block pool ids %llu => %s",
1842 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1843 outputPoolId_ = pools->outputPoolId;
1844 }
1845
David Stevensc3fbb282021-01-18 18:11:20 +09001846 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1847 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1848 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1849 if (err != C2_OK) {
1850 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1851 (unsigned long long) prevOutputPoolId, asString(err), err);
1852 }
1853 }
1854
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001855 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001856 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001857 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001858 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001859 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001860 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001861 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001862 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001863 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 }
1865 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001866 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001868 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001870 output->buffers->clearStash();
1871 if (reorderDepth) {
1872 output->buffers->setReorderDepth(reorderDepth.value);
1873 }
1874 if (reorderKey) {
1875 output->buffers->setReorderKey(reorderKey.value);
1876 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001877
1878 // Try to set output surface to created block pool if given.
1879 if (outputSurface) {
1880 mComponent->setOutputSurface(
1881 outputPoolId_,
1882 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001883 outputGeneration,
1884 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001885 } else {
1886 // configure CPU read consumer usage
1887 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1888 std::vector<std::unique_ptr<C2SettingResult>> failures;
1889 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1890 // do not print error message for now as most components may not yet
1891 // support this setting
1892 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1893 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001894 }
1895
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001896 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001897 if (buffersBoundToCodec) {
1898 // WORKAROUND: if we're using early CSD workaround we convert to
1899 // array mode, to appease apps assuming the output
1900 // buffers to be of the same size.
1901 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1902 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903
1904 int32_t channelCount;
1905 int32_t sampleRate;
1906 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1907 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1908 int32_t delay = 0;
1909 int32_t padding = 0;;
1910 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1911 delay = 0;
1912 }
1913 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1914 padding = 0;
1915 }
1916 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001917 // We need write access to the buffers, so turn them into array mode.
1918 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1919 // component, runs it through SkipCutBuffer and allocate local buffer to be
1920 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1921 // toArrayMode().
1922 if (!output->buffers->isArrayMode()) {
1923 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1924 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001925 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001926 }
1927 }
1928 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001929
1930 int32_t tunneled = 0;
1931 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1932 tunneled = 0;
1933 }
1934 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001935 }
1936
1937 // Set up pipeline control. This has to be done after mInputBuffers and
1938 // mOutputBuffers are initialized to make sure that lingering callbacks
1939 // about buffers from the previous generation do not interfere with the
1940 // newly initialized pipeline capacity.
1941
Wonsik Kim62545252021-01-20 11:25:41 -08001942 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001943 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001944 watcher->inputDelay(inputDelayValue)
1945 .pipelineDelay(pipelineDelayValue)
1946 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001947 .smoothnessFactor(kSmoothnessFactor)
1948 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001949 watcher->flush();
1950 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001951
1952 mInputMetEos = false;
1953 mSync.start();
1954 return OK;
1955}
1956
Wonsik Kim34b28b42022-05-20 15:49:32 -07001957status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00001958 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959 if (mInputSurface) {
1960 return OK;
1961 }
1962
Wonsik Kim34b28b42022-05-20 15:49:32 -07001963 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00001964 int retryCount = 1;
1965 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
1966 {
1967 Mutexed<Input>::Locked input(mInput);
1968 while (clientInputBuffers->size() < numInputSlots) {
1969 size_t index;
1970 sp<MediaCodecBuffer> buffer;
1971 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1972 break;
1973 }
1974 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07001975 }
Arun Johnson326166e2023-07-28 19:11:52 +00001976 }
1977 if (!retry || (retryCount <= 0)) {
1978 break;
1979 }
1980 if (clientInputBuffers->empty()) {
1981 // wait: buffer may be in transit from component.
1982 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07001983 }
1984 }
1985 if (clientInputBuffers->empty()) {
1986 ALOGW("[%s] start: cannot allocate memory at all", mName);
1987 return NO_MEMORY;
1988 } else if (clientInputBuffers->size() < numInputSlots) {
1989 ALOGD("[%s] start: cannot allocate memory for all slots, "
1990 "only %zu buffers allocated",
1991 mName, clientInputBuffers->size());
1992 } else {
1993 ALOGV("[%s] %zu initial input buffers available",
1994 mName, clientInputBuffers->size());
1995 }
1996 return OK;
1997}
1998
1999status_t CCodecBufferChannel::requestInitialInputBuffers(
2000 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002001 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002002 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
2003 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
2004 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005 return UNKNOWN_ERROR;
2006 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002007
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002008 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2009 mFlushedConfigs.lock()->swap(flushedConfigs);
2010 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002011 {
2012 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2013 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2014 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2015 watcher->onWorkQueued(
2016 work->input.ordinal.frameIndex.peeku(),
2017 std::vector(work->input.buffers),
2018 now);
2019 }
2020 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002021 err = mComponent->queue(&flushedConfigs);
2022 if (err != C2_OK) {
2023 ALOGW("[%s] Error while queueing a flushed config", mName);
2024 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002025 }
2026 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002027 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002028 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2029 !clientInputBuffers.empty()) {
2030 size_t minIndex = clientInputBuffers.begin()->first;
2031 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2032 for (const auto &[index, buffer] : clientInputBuffers) {
2033 if (minBuffer->capacity() > buffer->capacity()) {
2034 minIndex = index;
2035 minBuffer = buffer;
2036 }
2037 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002038 // WORKAROUND: Some apps expect CSD available without queueing
2039 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002040 minBuffer->setRange(0, 0);
2041 minBuffer->meta()->clear();
2042 minBuffer->meta()->setInt64("timeUs", 0);
2043 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002044 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2045 mName);
2046 return UNKNOWN_ERROR;
2047 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002048 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002049 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002050
Wonsik Kim34b28b42022-05-20 15:49:32 -07002051 for (const auto &[index, buffer] : clientInputBuffers) {
2052 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002054
Pawin Vongmasa36653902018-11-15 00:10:25 -08002055 return OK;
2056}
2057
2058void CCodecBufferChannel::stop() {
2059 mSync.stop();
2060 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002061}
2062
Sungtak Lee99144332023-01-26 11:03:14 +00002063void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2064 sp<Surface> surface = mOutputSurface.lock()->surface;
2065 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002066 C2BlockPool::local_id_t outputPoolId;
2067 {
2068 Mutexed<BlockPools>::Locked pools(mBlockPools);
2069 outputPoolId = pools->outputPoolId;
2070 }
2071 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002072
2073 if (pushBlankBuffer) {
2074 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2075 if (anw) {
2076 pushBlankBuffersToNativeWindow(anw.get());
2077 }
2078 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002079 }
2080}
2081
Wonsik Kim936a89c2020-05-08 16:07:50 -07002082void CCodecBufferChannel::reset() {
2083 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002084 if (mInputSurface != nullptr) {
2085 mInputSurface.reset();
2086 }
2087 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002088 {
2089 Mutexed<Input>::Locked input(mInput);
2090 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002091 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002092 }
2093 {
2094 Mutexed<Output>::Locked output(mOutput);
2095 output->buffers.reset();
2096 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002097 // reset the frames that are being tracked for onFrameRendered callbacks
2098 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002099}
2100
2101void CCodecBufferChannel::release() {
2102 mComponent.reset();
2103 mInputAllocator.reset();
2104 mOutputSurface.lock()->surface.clear();
2105 {
2106 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2107 blockPools->inputPool.reset();
2108 blockPools->outputPoolIntf.reset();
2109 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002110 setCrypto(nullptr);
2111 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002112}
2113
Pawin Vongmasa36653902018-11-15 00:10:25 -08002114void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2115 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002116 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002117 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002118 {
2119 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2120 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2121 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2122 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2123 watcher->onWorkDone(frameIndex);
2124 continue;
2125 }
2126 if (work->input.buffers.empty()
2127 || work->input.buffers.front() == nullptr
2128 || work->input.buffers.front()->data().linearBlocks().empty()) {
2129 ALOGD("[%s] no linear codec config data found", mName);
2130 watcher->onWorkDone(frameIndex);
2131 continue;
2132 }
2133 std::unique_ptr<C2Work> copy(new C2Work);
2134 copy->input.flags = C2FrameData::flags_t(
2135 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2136 copy->input.ordinal = work->input.ordinal;
2137 copy->input.ordinal.frameIndex = mFrameIndex++;
2138 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2139 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2140 }
2141 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2142 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2143 }
2144 copy->input.infoBuffers.insert(
2145 copy->input.infoBuffers.begin(),
2146 work->input.infoBuffers.begin(),
2147 work->input.infoBuffers.end());
2148 copy->worklets.emplace_back(new C2Worklet);
2149 configs.push_back(std::move(copy));
2150 watcher->onWorkDone(frameIndex);
2151 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002152 }
2153 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002154 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002155 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002156 Mutexed<Input>::Locked input(mInput);
2157 input->buffers->flush();
2158 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002159 }
2160 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002161 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002162 if (output->buffers) {
2163 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002164 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002165 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002166 }
2167}
2168
2169void CCodecBufferChannel::onWorkDone(
2170 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002171 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002172 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002173 feedInputBufferIfAvailable();
2174 }
2175}
2176
2177void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002178 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07002179 if (mInputSurface) {
2180 return;
2181 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002182 std::shared_ptr<C2Buffer> buffer =
2183 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002184 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002185 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002186 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002187 if (input->lastFlushIndex >= frameIndex) {
2188 ALOGD("[%s] Ignoring stale input buffer done callback: "
2189 "last flush index = %lld, frameIndex = %lld",
2190 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2191 } else {
2192 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2193 if (!newInputSlotAvailable) {
2194 (void)input->extraBuffers.expireComponentBuffer(buffer);
2195 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002196 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002197 }
2198 if (newInputSlotAvailable) {
2199 feedInputBufferIfAvailable();
2200 }
2201}
2202
2203bool CCodecBufferChannel::handleWork(
2204 std::unique_ptr<C2Work> work,
2205 const sp<AMessage> &outputFormat,
2206 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002207 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002208 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002209 if (!output->buffers) {
2210 return false;
2211 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002212 }
2213
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002214 // Whether the output buffer should be reported to the client or not.
2215 bool notifyClient = false;
2216
2217 if (work->result == C2_OK){
2218 notifyClient = true;
2219 } else if (work->result == C2_NOT_FOUND) {
2220 ALOGD("[%s] flushed work; ignored.", mName);
2221 } else {
2222 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2223 // the config update.
2224 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2225 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2226 return false;
2227 }
2228
2229 if ((work->input.ordinal.frameIndex -
2230 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231 // Discard frames from previous generation.
2232 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002233 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002234 }
2235
Wonsik Kim524b0582019-03-12 11:28:57 -07002236 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002237 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002238 || !(work->worklets.front()->output.flags &
2239 C2FrameData::FLAG_INCOMPLETE))) {
2240 mPipelineWatcher.lock()->onWorkDone(
2241 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002242 }
2243
2244 // NOTE: MediaCodec usage supposedly have only one worklet
2245 if (work->worklets.size() != 1u) {
2246 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2247 mName, work->worklets.size());
2248 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2249 return false;
2250 }
2251
2252 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2253
2254 std::shared_ptr<C2Buffer> buffer;
2255 // NOTE: MediaCodec usage supposedly have only one output stream.
2256 if (worklet->output.buffers.size() > 1u) {
2257 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2258 mName, worklet->output.buffers.size());
2259 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2260 return false;
2261 } else if (worklet->output.buffers.size() == 1u) {
2262 buffer = worklet->output.buffers[0];
2263 if (!buffer) {
2264 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2265 }
2266 }
2267
Wonsik Kim3dedf682021-05-03 10:57:09 -07002268 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2269 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002270 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002271 while (!worklet->output.configUpdate.empty()) {
2272 std::unique_ptr<C2Param> param;
2273 worklet->output.configUpdate.back().swap(param);
2274 worklet->output.configUpdate.pop_back();
2275 switch (param->coreIndex().coreIndex()) {
2276 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2277 C2PortReorderBufferDepthTuning::output reorderDepth;
2278 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002279 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2280 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002281 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002282 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002283 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002284 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2285 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002286 }
2287 break;
2288 }
2289 case C2PortReorderKeySetting::CORE_INDEX: {
2290 C2PortReorderKeySetting::output reorderKey;
2291 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002292 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002293 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2294 mName, reorderKey.value);
2295 } else {
2296 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2297 }
2298 break;
2299 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002300 case C2PortActualDelayTuning::CORE_INDEX: {
2301 if (param->isGlobal()) {
2302 C2ActualPipelineDelayTuning pipelineDelay;
2303 if (pipelineDelay.updateFrom(*param)) {
2304 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2305 mName, pipelineDelay.value);
2306 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002307 (void)mPipelineWatcher.lock()->pipelineDelay(
2308 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002309 }
2310 }
2311 if (param->forInput()) {
2312 C2PortActualDelayTuning::input inputDelay;
2313 if (inputDelay.updateFrom(*param)) {
2314 ALOGV("[%s] onWorkDone: updating input delay %u",
2315 mName, inputDelay.value);
2316 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002317 (void)mPipelineWatcher.lock()->inputDelay(
2318 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002319 }
2320 }
2321 if (param->forOutput()) {
2322 C2PortActualDelayTuning::output outputDelay;
2323 if (outputDelay.updateFrom(*param)) {
2324 ALOGV("[%s] onWorkDone: updating output delay %u",
2325 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002326 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002327 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002328 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002329
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002330 }
2331 }
2332 break;
2333 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002334 case C2PortTunnelSystemTime::CORE_INDEX: {
2335 C2PortTunnelSystemTime::output frameRenderTime;
2336 if (frameRenderTime.updateFrom(*param)) {
2337 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2338 mName, (long long)frameRenderTime.value,
2339 (long long)worklet->output.ordinal.timestamp.peekll());
2340 mCCodecCallback->onOutputFramesRendered(
2341 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2342 }
2343 break;
2344 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002345 case C2StreamTunnelHoldRender::CORE_INDEX: {
2346 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2347 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2348 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2349 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2350 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2351 mCCodecCallback->onFirstTunnelFrameReady();
2352 break;
2353 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002354 default:
2355 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2356 mName, param->index());
2357 break;
2358 }
2359 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002360 if (newInputDelay || newPipelineDelay) {
2361 Mutexed<Input>::Locked input(mInput);
2362 size_t newNumSlots =
2363 newInputDelay.value_or(input->inputDelay) +
2364 newPipelineDelay.value_or(input->pipelineDelay) +
2365 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002366 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002367 if (input->buffers->isArrayMode()) {
2368 if (input->numSlots >= newNumSlots) {
2369 input->numExtraSlots = 0;
2370 } else {
2371 input->numExtraSlots = newNumSlots - input->numSlots;
2372 }
2373 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2374 mName, input->numExtraSlots);
2375 } else {
2376 input->numSlots = newNumSlots;
2377 }
2378 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002379 size_t numOutputSlots = 0;
2380 uint32_t reorderDepth = 0;
2381 bool outputBuffersChanged = false;
2382 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2383 Mutexed<Output>::Locked output(mOutput);
2384 if (!output->buffers) {
2385 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002386 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002387 numOutputSlots = output->numSlots;
2388 if (newReorderKey) {
2389 output->buffers->setReorderKey(newReorderKey.value());
2390 }
2391 if (newReorderDepth) {
2392 output->buffers->setReorderDepth(newReorderDepth.value());
2393 }
2394 reorderDepth = output->buffers->getReorderDepth();
2395 if (newOutputDelay) {
2396 output->outputDelay = newOutputDelay.value();
2397 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2398 if (output->numSlots < numOutputSlots) {
2399 output->numSlots = numOutputSlots;
2400 if (output->buffers->isArrayMode()) {
2401 OutputBuffersArray *array =
2402 (OutputBuffersArray *)output->buffers.get();
2403 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2404 mName, numOutputSlots);
2405 array->grow(numOutputSlots);
2406 outputBuffersChanged = true;
2407 }
2408 }
2409 }
2410 numOutputSlots = output->numSlots;
2411 }
2412 if (outputBuffersChanged) {
2413 mCCodecCallback->onOutputBuffersChanged();
2414 }
2415 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002416 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002417 {
2418 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2419 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002420 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002421 if (output->surface) {
2422 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2423 }
2424 }
2425 if (maxDequeueCount > 0) {
2426 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002427 }
2428 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002429
Pawin Vongmasa36653902018-11-15 00:10:25 -08002430 int32_t flags = 0;
2431 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002432 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002433 ALOGV("[%s] onWorkDone: output EOS", mName);
2434 }
2435
Pawin Vongmasa36653902018-11-15 00:10:25 -08002436 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2437 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2438 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2439 // shall correspond to the client input timesamp (in customOrdinal). By using the
2440 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2441 // produces multiple output.
2442 c2_cntr64_t timestamp =
2443 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2444 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002445 if (mInputSurface != nullptr) {
2446 // When using input surface we need to restore the original input timestamp.
2447 timestamp = work->input.ordinal.customOrdinal;
2448 }
My Name6bd9a7d2022-03-25 12:37:58 -07002449 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2450 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002451 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2452 mName,
2453 work->input.ordinal.customOrdinal.peekll(),
2454 work->input.ordinal.timestamp.peekll(),
2455 worklet->output.ordinal.timestamp.peekll(),
2456 timestamp.peekll());
2457
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002458 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002459 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002460 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002461 if (!output->buffers) {
2462 return false;
2463 }
2464 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002465 output->buffers->updateSkipCutBuffer(outputFormat);
2466 output->buffers->setFormat(outputFormat);
2467 }
2468 if (!notifyClient) {
2469 return false;
2470 }
2471 size_t index;
2472 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002473 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002474 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002475 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002476 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2477
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002478 // TRICKY: we want popped buffers reported in order, so sending
2479 // the callback while holding the lock here. This assumes that
2480 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2481 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002482 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002483 } else {
2484 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002485 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002486 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002487 return false;
2488 }
2489 }
2490
Wonsik Kimec585c32021-10-01 01:11:00 -07002491 bool drop = false;
2492 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2493 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2494 drop = true;
2495 }
2496
Marc Kassisec910342022-11-25 11:43:05 +01002497 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2498 // HAL, the flag is then removed in the corresponding output buffer.
2499 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2500 flags |= BUFFER_FLAG_DECODE_ONLY;
2501 }
2502
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002503 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002504 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002505 if (mOutputFormat != outputFormat) {
2506 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2507 mName, work->input.ordinal.frameIndex.peekull());
2508 mOutputFormat = outputFormat;
2509 } else {
2510 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2511 mName, work->input.ordinal.frameIndex.peekull());
2512 notifyClient = false;
2513 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002514 } else {
2515 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2516 mName, work->input.ordinal.frameIndex.peekull());
2517 notifyClient = false;
2518 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002519 }
2520
2521 if (buffer) {
2522 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2523 // TODO: properly translate these to metadata
2524 switch (info->coreIndex().coreIndex()) {
2525 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002526 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002527 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002528 }
2529 break;
2530 default:
2531 break;
2532 }
2533 }
2534 }
2535
2536 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002537 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002538 if (!output->buffers) {
2539 return false;
2540 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002541 output->buffers->pushToStash(
2542 buffer,
2543 notifyClient,
2544 timestamp.peek(),
2545 flags,
2546 outputFormat,
2547 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002548 }
2549 sendOutputBuffers();
2550 return true;
2551}
2552
2553void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002554 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002555 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002556 sp<MediaCodecBuffer> outBuffer;
2557 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002558
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002559 constexpr int kMaxReallocTry = 5;
2560 int reallocTryNum = 0;
2561
Pawin Vongmasa36653902018-11-15 00:10:25 -08002562 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002563 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002564 if (!output->buffers) {
2565 return;
2566 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002567 action = output->buffers->popFromStashAndRegister(
2568 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002569 if (action != OutputBuffers::REALLOCATE) {
2570 reallocTryNum = 0;
2571 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002572 switch (action) {
2573 case OutputBuffers::SKIP:
2574 return;
2575 case OutputBuffers::DISCARD:
2576 break;
2577 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002578 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002579 // TRICKY: we want popped buffers reported in order, so sending
2580 // the callback while holding the lock here. This assumes that
2581 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2582 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002583 if (c2Buffer) {
2584 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2585 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2586 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2587 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2588 uint32_t flag = 0;
2589 std::vector<AccessUnitInfo> accessUnitInfos;
2590 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2591 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2592 bufferMetadata->m.values[nMeta];
2593 flag = convertFlags(bufferMetadataStruct.flags, false);
2594 accessUnitInfos.emplace_back(flag,
2595 static_cast<size_t>(bufferMetadataStruct.size),
2596 static_cast<size_t>(bufferMetadataStruct.timestamp));
2597 }
2598 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2599 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2600 outBuffer->meta()->setObject("accessUnitInfo", obj);
2601 }
2602 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002603 mCallback->onOutputBufferAvailable(index, outBuffer);
2604 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002605 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002606 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002607 if (++reallocTryNum > kMaxReallocTry) {
2608 output.unlock();
2609 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2610 mName, kMaxReallocTry);
2611 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2612 return;
2613 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002614 if (!output->buffers->isArrayMode()) {
2615 output->buffers =
2616 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002617 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002618 static_cast<OutputBuffersArray*>(output->buffers.get())->
2619 realloc(c2Buffer);
2620 output.unlock();
2621 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002622 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002623 case OutputBuffers::RETRY:
2624 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2625 mName);
2626 return;
2627 default:
2628 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2629 "corrupted BufferAction value (%d) "
2630 "returned from popFromStashAndRegister.",
2631 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002632 return;
2633 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002634 }
2635}
2636
Sungtak Lee214ce612023-11-01 10:01:13 +00002637status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2638 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002639 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002640 int maxDequeueCount;
2641 sp<Surface> oldSurface;
2642 {
2643 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2644 maxDequeueCount = outputSurface->maxDequeueBuffers;
2645 oldSurface = outputSurface->surface;
2646 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002647 if (newSurface) {
2648 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002649 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002650 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002651 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002652 } else {
2653 ALOGE("[%s] setting output surface to null", mName);
2654 return INVALID_OPERATION;
2655 }
2656
2657 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2658 C2BlockPool::local_id_t outputPoolId;
2659 {
2660 Mutexed<BlockPools>::Locked pools(mBlockPools);
2661 outputPoolId = pools->outputPoolId;
2662 outputPoolIntf = pools->outputPoolIntf;
2663 }
2664
2665 if (outputPoolIntf) {
2666 if (mComponent->setOutputSurface(
2667 outputPoolId,
2668 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002669 generation,
2670 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002671 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2672 return INVALID_OPERATION;
2673 }
2674 }
2675
2676 {
2677 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2678 output->surface = newSurface;
2679 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002680 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002681 }
2682
Sungtak Lee99144332023-01-26 11:03:14 +00002683 if (oldSurface && pushBlankBuffer) {
2684 // When ReleaseSurface was set from MediaCodec,
2685 // pushing a blank buffer at the end might be necessary.
2686 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2687 if (anw) {
2688 pushBlankBuffersToNativeWindow(anw.get());
2689 }
2690 }
2691
Pawin Vongmasa36653902018-11-15 00:10:25 -08002692 return OK;
2693}
2694
Wonsik Kimab34ed62019-01-31 15:28:46 -08002695PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002696 // Otherwise, component may have stalled work due to input starvation up to
2697 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002698 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2699 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002700 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002701 size_t outputDelay = mOutput.lock()->outputDelay;
2702 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002703 Mutexed<Input>::Locked input(mInput);
2704 n = input->inputDelay + input->pipelineDelay + outputDelay;
2705 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002706 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002707}
2708
Pawin Vongmasa36653902018-11-15 00:10:25 -08002709void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2710 mMetaMode = mode;
2711}
2712
Wonsik Kim596187e2019-10-25 12:44:10 -07002713void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002714 if (mCrypto != nullptr) {
2715 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2716 mCrypto->unsetHeap(entry.second);
2717 }
2718 mHeapSeqNumMap.clear();
2719 if (mHeapSeqNum >= 0) {
2720 mCrypto->unsetHeap(mHeapSeqNum);
2721 mHeapSeqNum = -1;
2722 }
2723 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002724 mCrypto = crypto;
2725}
2726
2727void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2728 mDescrambler = descrambler;
2729}
2730
Songyue Han1e6769b2023-08-30 18:09:27 +00002731uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2732 if (isEncoder) {
2733 return getInputBuffersPixelFormat();
2734 } else {
2735 return getOutputBuffersPixelFormat();
2736 }
2737}
2738
2739uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2740 Mutexed<Input>::Locked input(mInput);
2741 if (input->buffers == nullptr) {
2742 return PIXEL_FORMAT_UNKNOWN;
2743 }
2744 return input->buffers->getPixelFormatIfApplicable();
2745}
2746
2747uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2748 Mutexed<Output>::Locked output(mOutput);
2749 if (output->buffers == nullptr) {
2750 return PIXEL_FORMAT_UNKNOWN;
2751 }
2752 return output->buffers->getPixelFormatIfApplicable();
2753}
2754
2755void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2756 if (isEncoder) {
2757 Mutexed<Input>::Locked input(mInput);
2758 if (input->buffers == nullptr) {
2759 return;
2760 }
2761 input->buffers->resetPixelFormatIfApplicable();
2762 } else {
2763 Mutexed<Output>::Locked output(mOutput);
2764 if (output->buffers == nullptr) {
2765 return;
2766 }
2767 output->buffers->resetPixelFormatIfApplicable();
2768 }
2769}
2770
Pawin Vongmasa36653902018-11-15 00:10:25 -08002771status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2772 // C2_OK is always translated to OK.
2773 if (c2s == C2_OK) {
2774 return OK;
2775 }
2776
2777 // Operation-dependent translation
2778 // TODO: Add as necessary
2779 switch (c2op) {
2780 case C2_OPERATION_Component_start:
2781 switch (c2s) {
2782 case C2_NO_MEMORY:
2783 return NO_MEMORY;
2784 default:
2785 return UNKNOWN_ERROR;
2786 }
2787 default:
2788 break;
2789 }
2790
2791 // Backup operation-agnostic translation
2792 switch (c2s) {
2793 case C2_BAD_INDEX:
2794 return BAD_INDEX;
2795 case C2_BAD_VALUE:
2796 return BAD_VALUE;
2797 case C2_BLOCKING:
2798 return WOULD_BLOCK;
2799 case C2_DUPLICATE:
2800 return ALREADY_EXISTS;
2801 case C2_NO_INIT:
2802 return NO_INIT;
2803 case C2_NO_MEMORY:
2804 return NO_MEMORY;
2805 case C2_NOT_FOUND:
2806 return NAME_NOT_FOUND;
2807 case C2_TIMED_OUT:
2808 return TIMED_OUT;
2809 case C2_BAD_STATE:
2810 case C2_CANCELED:
2811 case C2_CANNOT_DO:
2812 case C2_CORRUPTED:
2813 case C2_OMITTED:
2814 case C2_REFUSED:
2815 return UNKNOWN_ERROR;
2816 default:
2817 return -static_cast<status_t>(c2s);
2818 }
2819}
2820
Pawin Vongmasa36653902018-11-15 00:10:25 -08002821} // namespace android