blob: 3ef2f848f7c19ccf0fcd5df64933c5fc5f7475b5 [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
Harish Mahendrakar38a99c22024-02-26 20:28:05 +053031#include <android_media_codec.h>
32
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <C2AllocatorGralloc.h>
34#include <C2PlatformSupport.h>
35#include <C2BlockInternal.h>
36#include <C2Config.h>
37#include <C2Debug.h>
38
39#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070040#include <android/hardware/drm/1.0/types.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070041#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080042#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080044#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070046#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070048#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include <media/openmax/OMX_Core.h>
50#include <media/stagefright/foundation/ABuffer.h>
51#include <media/stagefright/foundation/ALookup.h>
52#include <media/stagefright/foundation/AMessage.h>
53#include <media/stagefright/foundation/AUtils.h>
54#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070056#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010057#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080058#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070059#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070060#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080061#include <system/window.h>
62
63#include "CCodecBufferChannel.h"
64#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080065
66namespace android {
67
68using android::base::StringPrintf;
69using hardware::hidl_handle;
70using hardware::hidl_string;
71using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070072using hardware::fromHeap;
73using hardware::HidlMemory;
Brian Lindahld7967a92023-08-10 10:12:49 -060074using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070075
Pawin Vongmasa36653902018-11-15 00:10:25 -080076using namespace hardware::cas::V1_0;
77using namespace hardware::cas::native::V1_0;
78
79using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070080using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080081
Pawin Vongmasa36653902018-11-15 00:10:25 -080082namespace {
83
Wonsik Kim469c8342019-04-11 16:46:09 -070084constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080085
Sungtak Leeab6f2f32019-02-15 14:43:51 -080086// This is for keeping IGBP's buffer dropping logic in legacy mode other
87// than making it non-blocking. Do not change this value.
88const static size_t kDequeueTimeoutNs = 0;
89
Brian Lindahld7967a92023-08-10 10:12:49 -060090static bool areRenderMetricsEnabled() {
91 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
92 return v == "true";
93}
94
Arun Johnsonf4a81f72023-11-09 21:22:48 +000095// Flags can come with individual BufferInfos
96// when used with large frame audio
97constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList = {
98 {BUFFER_FLAG_CODEC_CONFIG, C2FrameData::FLAG_CODEC_CONFIG},
99 {BUFFER_FLAG_END_OF_STREAM, C2FrameData::FLAG_END_OF_STREAM},
100 {BUFFER_FLAG_DECODE_ONLY, C2FrameData::FLAG_DROP_FRAME}
101};
102
103static uint32_t convertFlags(uint32_t flags, bool toC2) {
104 return std::transform_reduce(
105 flagList.begin(), flagList.end(),
106 0u,
107 std::bit_or{},
108 [flags, toC2](const std::pair<uint32_t, uint32_t> &entry) {
109 if (toC2) {
110 return (flags & entry.first) ? entry.second : 0;
111 } else {
112 return (flags & entry.second) ? entry.first : 0;
113 }
114 });
115}
116
Pawin Vongmasa36653902018-11-15 00:10:25 -0800117} // namespace
118
119CCodecBufferChannel::QueueGuard::QueueGuard(
120 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
121 Mutex::Autolock l(mSync.mGuardLock);
122 // At this point it's guaranteed that mSync is not under state transition,
123 // as we are holding its mutex.
124
125 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
126 if (count->value == -1) {
127 mRunning = false;
128 } else {
129 ++count->value;
130 mRunning = true;
131 }
132}
133
134CCodecBufferChannel::QueueGuard::~QueueGuard() {
135 if (mRunning) {
136 // We are not holding mGuardLock at this point so that QueueSync::stop() can
137 // keep holding the lock until mCount reaches zero.
138 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
139 --count->value;
140 count->cond.broadcast();
141 }
142}
143
144void CCodecBufferChannel::QueueSync::start() {
145 Mutex::Autolock l(mGuardLock);
146 // If stopped, it goes to running state; otherwise no-op.
147 Mutexed<Counter>::Locked count(mCount);
148 if (count->value == -1) {
149 count->value = 0;
150 }
151}
152
153void CCodecBufferChannel::QueueSync::stop() {
154 Mutex::Autolock l(mGuardLock);
155 Mutexed<Counter>::Locked count(mCount);
156 if (count->value == -1) {
157 // no-op
158 return;
159 }
160 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
161 // mCount can only decrement. In other words, threads that acquired the lock
162 // are allowed to finish execution but additional threads trying to acquire
163 // the lock at this point will block, and then get QueueGuard at STOPPED
164 // state.
165 while (count->value != 0) {
166 count.waitForCondition(count->cond);
167 }
168 count->value = -1;
169}
170
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700171// Input
172
173CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
174
Pawin Vongmasa36653902018-11-15 00:10:25 -0800175// CCodecBufferChannel
176
177CCodecBufferChannel::CCodecBufferChannel(
178 const std::shared_ptr<CCodecCallback> &callback)
179 : mHeapSeqNum(-1),
180 mCCodecCallback(callback),
181 mFrameIndex(0u),
182 mFirstValidFrameIndex(0u),
Brian Lindahld7967a92023-08-10 10:12:49 -0600183 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600184 mIsSurfaceToDisplay(false),
185 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700186 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800187 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700188 mInputMetEos(false),
189 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700190 {
191 Mutexed<Input>::Locked input(mInput);
192 input->buffers.reset(new DummyInputBuffers(""));
193 input->extraBuffers.flush();
194 input->inputDelay = 0u;
195 input->pipelineDelay = 0u;
196 input->numSlots = kSmoothnessFactor;
197 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700198 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700199 }
200 {
201 Mutexed<Output>::Locked output(mOutput);
202 output->outputDelay = 0u;
203 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700204 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700205 }
David Stevensc3fbb282021-01-18 18:11:20 +0900206 {
207 Mutexed<BlockPools>::Locked pools(mBlockPools);
208 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
209 }
Brian Lindahld7967a92023-08-10 10:12:49 -0600210 std::string value = GetServerConfigurableFlag("media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700211 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700212 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213}
214
215CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800216 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 mCrypto->unsetHeap(mHeapSeqNum);
218 }
219}
220
221void CCodecBufferChannel::setComponent(
222 const std::shared_ptr<Codec2Client::Component> &component) {
223 mComponent = component;
224 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
225 mName = mComponentName.c_str();
226}
227
228status_t CCodecBufferChannel::setInputSurface(
229 const std::shared_ptr<InputSurfaceWrapper> &surface) {
230 ALOGV("[%s] setInputSurface", mName);
Wonsik Kimfca97a22024-08-30 20:20:42 +0000231 if (!surface) {
232 ALOGE("[%s] setInputSurface: surface must not be null", mName);
233 return BAD_VALUE;
234 }
235 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
236 inputSurface->numProcessingBuffersBalance = 0;
237 inputSurface->surface = surface;
238 mHasInputSurface = true;
239 return inputSurface->surface->connect(mComponent);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240}
241
242status_t CCodecBufferChannel::signalEndOfInputStream() {
Wonsik Kimfca97a22024-08-30 20:20:42 +0000243 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
244 if (inputSurface->surface == nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 return INVALID_OPERATION;
246 }
Wonsik Kimfca97a22024-08-30 20:20:42 +0000247 return inputSurface->surface->signalEndOfInputStream();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248}
249
Sungtak Lee04b30352020-07-27 13:57:25 -0700250status_t CCodecBufferChannel::queueInputBufferInternal(
251 sp<MediaCodecBuffer> buffer,
252 std::shared_ptr<C2LinearBlock> encryptedBlock,
253 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800254 int64_t timeUs;
255 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
256
257 if (mInputMetEos) {
258 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
259 return OK;
260 }
261
262 int32_t flags = 0;
263 int32_t tmp = 0;
264 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200265 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800266 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
267 eos = true;
268 mInputMetEos = true;
269 ALOGV("[%s] input EOS", mName);
270 }
271 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
272 flags |= C2FrameData::FLAG_CODEC_CONFIG;
273 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200274 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
275 tunnelFirstFrame = true;
276 }
Marc Kassis96343b42022-12-09 11:49:44 +0100277 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
278 flags |= C2FrameData::FLAG_DROP_FRAME;
279 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000280 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu time: %lld",
281 mName, buffer->size(), (long long)timeUs);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800282 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800283 std::unique_ptr<C2Work> work(new C2Work);
284 work->input.ordinal.timestamp = timeUs;
285 work->input.ordinal.frameIndex = mFrameIndex++;
286 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
287 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
288 // Keep client timestamp in customOrdinal
289 work->input.ordinal.customOrdinal = timeUs;
290 work->input.buffers.clear();
291
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700292 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800293 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800294
Pawin Vongmasa36653902018-11-15 00:10:25 -0800295 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700296 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700298 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800299 return -ENOENT;
300 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700301 // TODO: we want to delay copying buffers.
302 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
303 copy = input->buffers->cloneAndReleaseBuffer(buffer);
304 if (copy != nullptr) {
305 (void)input->extraBuffers.assignSlot(copy);
306 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
307 return UNKNOWN_ERROR;
308 }
309 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
310 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
311 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700312 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700313 } else {
314 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
315 "buffer starvation on component.", mName);
316 }
317 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800318 if (input->frameReassembler) {
319 usesFrameReassembler = true;
320 input->frameReassembler.process(buffer, &items);
321 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900322 int32_t cvo = 0;
323 if (buffer->meta()->findInt32("cvo", &cvo)) {
324 int32_t rotation = cvo % 360;
325 // change rotation to counter-clock wise.
326 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
327
328 Mutexed<OutputSurface>::Locked output(mOutputSurface);
329 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
330 output->rotation[frameIndex] = rotation;
331 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000332 sp<RefBase> obj;
333 if (buffer->meta()->findObject("accessUnitInfo", &obj)) {
334 ALOGV("Filling C2Info from multiple access units");
335 sp<WrapperObject<std::vector<AccessUnitInfo>>> infos{
336 (decltype(infos.get()))obj.get()};
337 std::vector<AccessUnitInfo> &accessUnitInfoVec = infos->value;
338 std::vector<C2AccessUnitInfosStruct> multipleAccessUnitInfos;
339 uint32_t outFlags = 0;
340 for (int i = 0; i < accessUnitInfoVec.size(); i++) {
341 outFlags = 0;
342 outFlags = convertFlags(accessUnitInfoVec[i].mFlags, true);
343 if (eos && (outFlags & C2FrameData::FLAG_END_OF_STREAM)) {
344 outFlags &= (~C2FrameData::FLAG_END_OF_STREAM);
345 }
346 multipleAccessUnitInfos.emplace_back(
347 outFlags,
348 accessUnitInfoVec[i].mSize,
349 accessUnitInfoVec[i].mTimestamp);
350 ALOGV("%d) flags: %d, size: %d, time: %llu",
351 i, outFlags, accessUnitInfoVec[i].mSize,
352 (long long)accessUnitInfoVec[i].mTimestamp);
353
354 }
355 const std::shared_ptr<C2AccessUnitInfos::input> c2AccessUnitInfos =
356 C2AccessUnitInfos::input::AllocShared(
357 multipleAccessUnitInfos.size(), 0u, multipleAccessUnitInfos);
358 c2buffer->setInfo(c2AccessUnitInfos);
359 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800360 work->input.buffers.push_back(c2buffer);
361 if (encryptedBlock) {
362 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
363 kParamIndexEncryptedBuffer,
364 encryptedBlock->share(0, blockSize, C2Fence())));
365 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700366 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800367 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700368 Mutexed<Input>::Locked input(mInput);
369 if (input->frameReassembler) {
370 usesFrameReassembler = true;
371 // drain any pending items with eos
372 input->frameReassembler.process(buffer, &items);
373 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800374 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800375 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800376 if (usesFrameReassembler) {
377 if (!items.empty()) {
378 items.front()->input.configUpdate = std::move(mParamsToBeSet);
379 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
380 }
381 } else {
382 work->input.flags = (C2FrameData::flags_t)flags;
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530383
Wonsik Kime1104ca2020-11-24 15:01:33 -0800384 // TODO: fill info's
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530385 if (android::media::codec::provider_->region_of_interest()
386 && android::media::codec::provider_->region_of_interest_support()) {
387 if (mInfoBuffers.size()) {
388 for (auto infoBuffer : mInfoBuffers) {
389 work->input.infoBuffers.emplace_back(*infoBuffer);
390 }
391 mInfoBuffers.clear();
392 }
393 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800394
Wonsik Kime1104ca2020-11-24 15:01:33 -0800395 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200396 if (tunnelFirstFrame) {
397 C2StreamTunnelHoldRender::input tunnelHoldRender{
398 0u /* stream */,
399 C2_TRUE /* value */
400 };
401 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
402 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800403 work->worklets.clear();
404 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800405
Wonsik Kime1104ca2020-11-24 15:01:33 -0800406 items.push_back(std::move(work));
407
408 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800409 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800410 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800411 work.reset(new C2Work);
412 work->input.ordinal.timestamp = timeUs;
413 work->input.ordinal.frameIndex = mFrameIndex++;
414 // WORKAROUND: keep client timestamp in customOrdinal
415 work->input.ordinal.customOrdinal = timeUs;
416 work->input.buffers.clear();
417 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800418 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800419 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800420 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800421 c2_status_t err = C2_OK;
422 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700423 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
424 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800425 {
426 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
427 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
428 for (const std::unique_ptr<C2Work> &work : items) {
429 watcher->onWorkQueued(
430 work->input.ordinal.frameIndex.peeku(),
431 std::vector(work->input.buffers),
432 now);
433 }
434 }
435 err = mComponent->queue(&items);
436 }
437 if (err != C2_OK) {
438 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
439 for (const std::unique_ptr<C2Work> &work : items) {
440 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
441 }
442 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700443 Mutexed<Input>::Locked input(mInput);
444 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700445 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700446 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700447 } else if (buffer) {
448 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700449 }
450 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
451 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800452 }
453
454 feedInputBufferIfAvailableInternal();
455 return err;
456}
457
458status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
459 QueueGuard guard(mSync);
460 if (!guard.isRunning()) {
461 ALOGD("[%s] setParameters is only supported in the running state.", mName);
462 return -ENOSYS;
463 }
464 mParamsToBeSet.insert(mParamsToBeSet.end(),
465 std::make_move_iterator(params.begin()),
466 std::make_move_iterator(params.end()));
467 params.clear();
468 return OK;
469}
470
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800471status_t CCodecBufferChannel::attachBuffer(
472 const std::shared_ptr<C2Buffer> &c2Buffer,
473 const sp<MediaCodecBuffer> &buffer) {
474 if (!buffer->copy(c2Buffer)) {
475 return -ENOSYS;
476 }
477 return OK;
478}
479
480void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
481 if (!mDecryptDestination || mDecryptDestination->size() < size) {
482 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
483 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
484 mCrypto->unsetHeap(mHeapSeqNum);
485 }
486 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
487 if (mCrypto) {
488 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
489 }
490 }
491}
492
493int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
494 CHECK(mCrypto);
495 auto it = mHeapSeqNumMap.find(memory);
496 int32_t heapSeqNum = -1;
497 if (it == mHeapSeqNumMap.end()) {
498 heapSeqNum = mCrypto->setHeap(memory);
499 mHeapSeqNumMap.emplace(memory, heapSeqNum);
500 } else {
501 heapSeqNum = it->second;
502 }
503 return heapSeqNum;
504}
505
Arun Johnson564f3a92024-02-01 19:09:45 +0000506typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
507typedef WrapperObject<std::vector<std::unique_ptr<CodecCryptoInfo>>> CryptoInfosWrapper;
508status_t CCodecBufferChannel::attachEncryptedBuffers(
509 const sp<hardware::HidlMemory> &memory,
510 size_t offset,
511 const sp<MediaCodecBuffer> &buffer,
512 bool secure,
513 AString* errorDetailMsg) {
514 static const C2MemoryUsage kDefaultReadWriteUsage{
515 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
516 if (!hasCryptoOrDescrambler()) {
517 ALOGE("attachEncryptedBuffers requires Crypto/descrambler object");
518 return -ENOSYS;
519 }
520 size_t size = 0;
521 CHECK(buffer->meta()->findSize("ssize", &size));
522 if (size == 0) {
523 buffer->setRange(0, 0);
524 return OK;
525 }
526 sp<RefBase> obj;
527 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
528 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
529 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
530 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
531 if (secure || (mCrypto == nullptr)) {
532 if (cryptoInfos->value.size() != 1) {
533 ALOGE("Cannot decrypt multiple access units");
534 return -ENOSYS;
535 }
536 // we are dealing with just one cryptoInfo or descrambler.
537 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
538 if (info == nullptr) {
539 ALOGE("Cannot decrypt, CryptoInfos are null.");
540 return -ENOSYS;
541 }
542 return attachEncryptedBuffer(
543 memory,
544 secure,
545 info->mKey,
546 info->mIv,
547 info->mMode,
548 info->mPattern,
549 offset,
550 info->mSubSamples,
551 info->mNumSubSamples,
552 buffer,
553 errorDetailMsg);
554 }
555 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
556 std::shared_ptr<C2LinearBlock> block;
557 c2_status_t err = pool->fetchLinearBlock(
558 size,
559 kDefaultReadWriteUsage,
560 &block);
561 if (err != C2_OK) {
562 ALOGI("[%s] attachEncryptedBuffers: fetchLinearBlock failed: size = %zu (%s) err = %d",
563 mName, size, secure ? "secure" : "non-secure", err);
564 return NO_MEMORY;
565 }
566 ensureDecryptDestination(size);
567 C2WriteView wView = block->map().get();
568 if (wView.error() != C2_OK) {
569 ALOGI("[%s] attachEncryptedBuffers: block map error: %d (non-secure)",
570 mName, wView.error());
571 return UNKNOWN_ERROR;
572 }
573
574 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +0000575 size_t srcOffset = offset;
Arun Johnson564f3a92024-02-01 19:09:45 +0000576 size_t outBufferSize = 0;
577 uint32_t cryptoInfoIdx = 0;
578 int32_t heapSeqNum = getHeapSeqNum(memory);
579 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
580 hardware::drm::V1_0::DestinationBuffer dst;
581 dst.type = DrmBufferType::SHARED_MEMORY;
582 IMemoryToSharedBuffer(
583 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
584 for (int i = 0; i < bufferInfos->value.size(); i++) {
585 if (bufferInfos->value[i].mSize > 0) {
586 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[cryptoInfoIdx++]);
Arun Johnson82174a12024-02-27 04:53:59 +0000587 src.offset = srcOffset;
588 src.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000589 result = mCrypto->decrypt(
590 (uint8_t*)info->mKey,
591 (uint8_t*)info->mIv,
592 info->mMode,
593 info->mPattern,
594 src,
Arun Johnson82174a12024-02-27 04:53:59 +0000595 0,
Arun Johnson564f3a92024-02-01 19:09:45 +0000596 info->mSubSamples,
597 info->mNumSubSamples,
598 dst,
599 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +0000600 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000601 if (result < 0) {
602 ALOGI("[%s] attachEncryptedBuffers: decrypt failed: result = %zd",
603 mName, result);
604 return result;
605 }
606 if (wView.error() == C2_OK) {
607 if (wView.size() < result) {
608 ALOGI("[%s] attachEncryptedBuffers: block size too small:"
609 "size=%u result=%zd (non-secure)", mName, wView.size(), result);
610 return UNKNOWN_ERROR;
611 }
612 memcpy(wView.data(), mDecryptDestination->unsecurePointer(), result);
613 bufferInfos->value[i].mSize = result;
614 wView.setOffset(wView.offset() + result);
615 }
616 outBufferSize += result;
617 }
618 }
619 if (wView.error() == C2_OK) {
620 wView.setOffset(0);
621 }
622 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
Arun Johnson82174a12024-02-27 04:53:59 +0000623 block->share(0, outBufferSize, C2Fence{}))};
Arun Johnson564f3a92024-02-01 19:09:45 +0000624 if (!buffer->copy(c2Buffer)) {
625 ALOGI("[%s] attachEncryptedBuffers: buffer copy failed", mName);
626 return -ENOSYS;
627 }
628 return OK;
629}
630
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800631status_t CCodecBufferChannel::attachEncryptedBuffer(
632 const sp<hardware::HidlMemory> &memory,
633 bool secure,
634 const uint8_t *key,
635 const uint8_t *iv,
636 CryptoPlugin::Mode mode,
637 CryptoPlugin::Pattern pattern,
638 size_t offset,
639 const CryptoPlugin::SubSample *subSamples,
640 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000641 const sp<MediaCodecBuffer> &buffer,
642 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800643 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
644 static const C2MemoryUsage kDefaultReadWriteUsage{
645 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
646
647 size_t size = 0;
648 for (size_t i = 0; i < numSubSamples; ++i) {
649 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
650 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700651 if (size == 0) {
652 buffer->setRange(0, 0);
653 return OK;
654 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800655 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
656 std::shared_ptr<C2LinearBlock> block;
657 c2_status_t err = pool->fetchLinearBlock(
658 size,
659 secure ? kSecureUsage : kDefaultReadWriteUsage,
660 &block);
661 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700662 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
663 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800664 return NO_MEMORY;
665 }
666 if (!secure) {
667 ensureDecryptDestination(size);
668 }
669 ssize_t result = -1;
670 ssize_t codecDataOffset = 0;
671 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800672 int32_t heapSeqNum = getHeapSeqNum(memory);
673 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
674 hardware::drm::V1_0::DestinationBuffer dst;
675 if (secure) {
676 dst.type = DrmBufferType::NATIVE_HANDLE;
677 dst.secureMemory = hardware::hidl_handle(block->handle());
678 } else {
679 dst.type = DrmBufferType::SHARED_MEMORY;
680 IMemoryToSharedBuffer(
681 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
682 }
683 result = mCrypto->decrypt(
684 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000685 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800686 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700687 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800688 return result;
689 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800690 } else {
691 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
692 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
693 hidl_vec<SubSample> hidlSubSamples;
694 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
695
696 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
697 hardware::cas::native::V1_0::DestinationBuffer dst;
698 if (secure) {
699 dst.type = BufferType::NATIVE_HANDLE;
700 dst.secureMemory = hardware::hidl_handle(block->handle());
701 } else {
702 dst.type = BufferType::SHARED_MEMORY;
703 dst.nonsecureMemory = src;
704 }
705
706 CasStatus status = CasStatus::OK;
707 hidl_string detailedError;
708 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
709
710 if (key != nullptr) {
711 sctrl = (ScramblingControl)key[0];
712 // Adjust for the PES offset
713 codecDataOffset = key[2] | (key[3] << 8);
714 }
715
716 auto returnVoid = mDescrambler->descramble(
717 sctrl,
718 hidlSubSamples,
719 src,
720 0,
721 dst,
722 0,
723 [&status, &result, &detailedError] (
724 CasStatus _status, uint32_t _bytesWritten,
725 const hidl_string& _detailedError) {
726 status = _status;
727 result = (ssize_t)_bytesWritten;
728 detailedError = _detailedError;
729 });
Arun Johnson634d0802023-02-14 22:07:51 +0000730 if (errorDetailMsg) {
731 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
732 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800733 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
734 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
735 mName, returnVoid.description().c_str(), status, result);
736 return UNKNOWN_ERROR;
737 }
738
739 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700740 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
741 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800742 return BAD_VALUE;
743 }
744 }
745 if (!secure) {
746 C2WriteView view = block->map().get();
747 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700748 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
749 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800750 return UNKNOWN_ERROR;
751 }
752 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700753 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
754 "(non-secure)",
755 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800756 return UNKNOWN_ERROR;
757 }
758 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
759 }
760 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
761 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
762 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700763 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800764 return -ENOSYS;
765 }
766 return OK;
767}
768
Pawin Vongmasa36653902018-11-15 00:10:25 -0800769status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
770 QueueGuard guard(mSync);
771 if (!guard.isRunning()) {
772 ALOGD("[%s] No more buffers should be queued at current state.", mName);
773 return -ENOSYS;
774 }
775 return queueInputBufferInternal(buffer);
776}
777
778status_t CCodecBufferChannel::queueSecureInputBuffer(
779 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
780 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
781 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
782 AString *errorDetailMsg) {
783 QueueGuard guard(mSync);
784 if (!guard.isRunning()) {
785 ALOGD("[%s] No more buffers should be queued at current state.", mName);
786 return -ENOSYS;
787 }
788
789 if (!hasCryptoOrDescrambler()) {
790 return -ENOSYS;
791 }
792 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
793
Sungtak Lee04b30352020-07-27 13:57:25 -0700794 std::shared_ptr<C2LinearBlock> block;
795 size_t allocSize = buffer->size();
796 size_t bufferSize = 0;
797 c2_status_t blockRes = C2_OK;
798 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000799 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
800 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700801 if (mSendEncryptedInfoBuffer) {
802 static const C2MemoryUsage kDefaultReadWriteUsage{
803 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
804 constexpr int kAllocGranule0 = 1024 * 64;
805 constexpr int kAllocGranule1 = 1024 * 1024;
806 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
807 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
808 if (allocSize <= kAllocGranule1) {
809 bufferSize = align(allocSize, kAllocGranule0);
810 } else {
811 bufferSize = align(allocSize, kAllocGranule1);
812 }
813 blockRes = pool->fetchLinearBlock(
814 bufferSize, kDefaultReadWriteUsage, &block);
815
816 if (blockRes == C2_OK) {
817 C2WriteView view = block->map().get();
818 if (view.error() == C2_OK && view.size() == bufferSize) {
819 copied = true;
820 // TODO: only copy clear sections
821 memcpy(view.data(), buffer->data(), allocSize);
822 }
823 }
824 }
825
826 if (!copied) {
827 block.reset();
828 }
829
Pawin Vongmasa36653902018-11-15 00:10:25 -0800830 ssize_t result = -1;
831 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700832 if (numSubSamples == 1
833 && subSamples[0].mNumBytesOfClearData == 0
834 && subSamples[0].mNumBytesOfEncryptedData == 0) {
835 // We don't need to go through crypto or descrambler if the input is empty.
836 result = 0;
837 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700838 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800839 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700840 destination.type = DrmBufferType::NATIVE_HANDLE;
841 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800842 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700843 destination.type = DrmBufferType::SHARED_MEMORY;
844 IMemoryToSharedBuffer(
845 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800846 }
Robert Shih895fba92019-07-16 16:29:44 -0700847 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800848 encryptedBuffer->fillSourceBuffer(&source);
849 result = mCrypto->decrypt(
850 key, iv, mode, pattern, source, buffer->offset(),
851 subSamples, numSubSamples, destination, errorDetailMsg);
852 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700853 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 return result;
855 }
Robert Shih895fba92019-07-16 16:29:44 -0700856 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800857 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
858 }
859 } else {
860 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
861 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
862 hidl_vec<SubSample> hidlSubSamples;
863 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
864
865 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
866 encryptedBuffer->fillSourceBuffer(&srcBuffer);
867
868 DestinationBuffer dstBuffer;
869 if (secure) {
870 dstBuffer.type = BufferType::NATIVE_HANDLE;
871 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
872 } else {
873 dstBuffer.type = BufferType::SHARED_MEMORY;
874 dstBuffer.nonsecureMemory = srcBuffer;
875 }
876
877 CasStatus status = CasStatus::OK;
878 hidl_string detailedError;
879 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
880
881 if (key != nullptr) {
882 sctrl = (ScramblingControl)key[0];
883 // Adjust for the PES offset
884 codecDataOffset = key[2] | (key[3] << 8);
885 }
886
887 auto returnVoid = mDescrambler->descramble(
888 sctrl,
889 hidlSubSamples,
890 srcBuffer,
891 0,
892 dstBuffer,
893 0,
894 [&status, &result, &detailedError] (
895 CasStatus _status, uint32_t _bytesWritten,
896 const hidl_string& _detailedError) {
897 status = _status;
898 result = (ssize_t)_bytesWritten;
899 detailedError = _detailedError;
900 });
901
902 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
903 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
904 mName, returnVoid.description().c_str(), status, result);
905 return UNKNOWN_ERROR;
906 }
907
908 if (result < codecDataOffset) {
909 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
910 return BAD_VALUE;
911 }
912
913 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
914
915 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
916 encryptedBuffer->copyDecryptedContentFromMemory(result);
917 }
918 }
919
920 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700921
922 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923}
924
Arun Johnson564f3a92024-02-01 19:09:45 +0000925status_t CCodecBufferChannel::queueSecureInputBuffers(
926 const sp<MediaCodecBuffer> &buffer,
927 bool secure,
928 AString *errorDetailMsg) {
929 QueueGuard guard(mSync);
930 if (!guard.isRunning()) {
931 ALOGD("[%s] No more buffers should be queued at current state.", mName);
932 return -ENOSYS;
933 }
934
935 if (!hasCryptoOrDescrambler()) {
936 ALOGE("queueSecureInputBuffers requires a Crypto/descrambler Object");
937 return -ENOSYS;
938 }
939 sp<RefBase> obj;
940 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
941 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
942 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
943 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
944 if (secure || mCrypto == nullptr) {
945 if (cryptoInfos->value.size() != 1) {
946 ALOGE("Cannot decrypt multiple access units on native handles");
947 return -ENOSYS;
948 }
949 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
950 if (info == nullptr) {
951 ALOGE("Cannot decrypt, CryptoInfos are null");
952 return -ENOSYS;
953 }
954 return queueSecureInputBuffer(
955 buffer,
956 secure,
957 info->mKey,
958 info->mIv,
959 info->mMode,
960 info->mPattern,
961 info->mSubSamples,
962 info->mNumSubSamples,
963 errorDetailMsg);
964 }
965 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
966
967 std::shared_ptr<C2LinearBlock> block;
968 size_t allocSize = buffer->size();
969 size_t bufferSize = 0;
970 c2_status_t blockRes = C2_OK;
971 bool copied = false;
972 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
973 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
974 if (mSendEncryptedInfoBuffer) {
975 static const C2MemoryUsage kDefaultReadWriteUsage{
976 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
977 constexpr int kAllocGranule0 = 1024 * 64;
978 constexpr int kAllocGranule1 = 1024 * 1024;
979 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
980 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
981 if (allocSize <= kAllocGranule1) {
982 bufferSize = align(allocSize, kAllocGranule0);
983 } else {
984 bufferSize = align(allocSize, kAllocGranule1);
985 }
986 blockRes = pool->fetchLinearBlock(
987 bufferSize, kDefaultReadWriteUsage, &block);
988
989 if (blockRes == C2_OK) {
990 C2WriteView view = block->map().get();
991 if (view.error() == C2_OK && view.size() == bufferSize) {
992 copied = true;
993 // TODO: only copy clear sections
994 memcpy(view.data(), buffer->data(), allocSize);
995 }
996 }
997 }
998
999 if (!copied) {
1000 block.reset();
1001 }
1002 // size of cryptoInfo and accessUnitInfo should be the same?
1003 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +00001004 size_t srcOffset = 0;
Arun Johnson564f3a92024-02-01 19:09:45 +00001005 size_t outBufferSize = 0;
1006 uint32_t cryptoInfoIdx = 0;
1007 {
1008 // scoped this block to enable destruction of mappedBlock
1009 std::unique_ptr<EncryptedLinearBlockBuffer::MappedBlock> mappedBlock = nullptr;
1010 hardware::drm::V1_0::DestinationBuffer destination;
1011 destination.type = DrmBufferType::SHARED_MEMORY;
1012 IMemoryToSharedBuffer(
1013 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
1014 encryptedBuffer->getMappedBlock(&mappedBlock);
1015 hardware::drm::V1_0::SharedBuffer source;
1016 encryptedBuffer->fillSourceBuffer(&source);
Arun Johnson82174a12024-02-27 04:53:59 +00001017 srcOffset = source.offset;
Arun Johnson564f3a92024-02-01 19:09:45 +00001018 for (int i = 0 ; i < bufferInfos->value.size(); i++) {
1019 if (bufferInfos->value[i].mSize > 0) {
1020 std::unique_ptr<CodecCryptoInfo> info =
1021 std::move(cryptoInfos->value[cryptoInfoIdx++]);
1022 if (info->mNumSubSamples == 1
1023 && info->mSubSamples[0].mNumBytesOfClearData == 0
1024 && info->mSubSamples[0].mNumBytesOfEncryptedData == 0) {
1025 // no data so we only populate the bufferInfo
1026 result = 0;
1027 } else {
Arun Johnson82174a12024-02-27 04:53:59 +00001028 source.offset = srcOffset;
1029 source.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001030 result = mCrypto->decrypt(
1031 (uint8_t*)info->mKey,
1032 (uint8_t*)info->mIv,
1033 info->mMode,
1034 info->mPattern,
1035 source,
Arun Johnson82174a12024-02-27 04:53:59 +00001036 buffer->offset(),
Arun Johnson564f3a92024-02-01 19:09:45 +00001037 info->mSubSamples,
1038 info->mNumSubSamples,
1039 destination,
1040 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +00001041 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001042 if (result < 0) {
1043 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
1044 return result;
1045 }
1046 if (destination.type == DrmBufferType::SHARED_MEMORY && mappedBlock) {
1047 mappedBlock->copyDecryptedContent(mDecryptDestination, result);
1048 }
1049 bufferInfos->value[i].mSize = result;
1050 outBufferSize += result;
1051 }
1052 }
1053 }
Arun Johnson82174a12024-02-27 04:53:59 +00001054 buffer->setRange(0, outBufferSize);
Arun Johnson564f3a92024-02-01 19:09:45 +00001055 }
1056 return queueInputBufferInternal(buffer, block, bufferSize);
1057}
1058
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059void CCodecBufferChannel::feedInputBufferIfAvailable() {
1060 QueueGuard guard(mSync);
1061 if (!guard.isRunning()) {
1062 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1063 return;
1064 }
1065 feedInputBufferIfAvailableInternal();
1066}
1067
1068void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +09001069 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001070 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001071 }
Wonsik Kimfca97a22024-08-30 20:20:42 +00001072 int64_t numOutputSlots = 0;
1073 bool outputFull = [this, &numOutputSlots]() {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001074 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimfca97a22024-08-30 20:20:42 +00001075 if (!output->buffers) {
1076 ALOGV("[%s] feedInputBufferIfAvailableInternal: "
1077 "return because output buffers are null", mName);
1078 return true;
1079 }
1080 numOutputSlots = int64_t(output->numSlots);
1081 if (output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -07001082 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00001083 ALOGV("[%s] feedInputBufferIfAvailableInternal: "
1084 "return because there are no room for more output buffers", mName);
1085 return true;
1086 }
1087 return false;
1088 }();
1089 if (android::media::codec::provider_->input_surface_throttle()) {
1090 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
1091 if (inputSurface->surface) {
1092 if (inputSurface->numProcessingBuffersBalance <= numOutputSlots) {
1093 ++inputSurface->numProcessingBuffersBalance;
1094 ALOGV("[%s] feedInputBufferIfAvailableInternal: numProcessingBuffersBalance = %lld",
1095 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
1096 inputSurface->surface->onInputBufferEmptied();
1097 }
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001098 }
1099 }
Wonsik Kimfca97a22024-08-30 20:20:42 +00001100 if (outputFull) {
1101 return;
Wonsik Kim1951d932024-05-23 22:59:00 +00001102 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001103 size_t numActiveSlots = 0;
1104 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001105 sp<MediaCodecBuffer> inBuffer;
1106 size_t index;
1107 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001108 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001109 numActiveSlots = input->buffers->numActiveSlots();
1110 if (numActiveSlots >= input->numSlots) {
1111 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001112 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001113 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001114 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001115 break;
1116 }
1117 }
1118 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1119 mCallback->onInputBufferAvailable(index, inBuffer);
1120 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001121 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122}
1123
1124status_t CCodecBufferChannel::renderOutputBuffer(
1125 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001126 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001127 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001128 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001130 Mutexed<Output>::Locked output(mOutput);
1131 if (output->buffers) {
1132 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001133 }
1134 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001135 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1136 // set to true.
1137 sendOutputBuffers();
1138 // input buffer feeding may have been gated by pending output buffers
1139 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001141 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001142 std::call_once(mRenderWarningFlag, [this] {
1143 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1144 "timestamp or render=true with non-video buffers. Apps should "
1145 "call releaseOutputBuffer() with render=false for those.",
1146 mName);
1147 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001148 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 return INVALID_OPERATION;
1150 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151
1152#if 0
1153 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1154 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1155 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1156 AString res;
1157 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1158 if (ix) res.append(", ");
1159 res.append(*((int32_t*)info.get() + (ix / 4)));
1160 }
1161 ALOGV(" [%s]", res.c_str());
1162 }
1163#endif
1164 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1165 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1166 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1167 bool flip = rotation && (rotation->flip & 1);
1168 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001169
1170 {
1171 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1172 if (output->surface == nullptr) {
1173 ALOGI("[%s] cannot render buffer without surface", mName);
1174 return OK;
1175 }
1176 int64_t frameIndex;
1177 buffer->meta()->findInt64("frameIndex", &frameIndex);
1178 if (output->rotation.count(frameIndex) != 0) {
1179 auto it = output->rotation.find(frameIndex);
1180 quarters = (it->second / 90) & 3;
1181 output->rotation.erase(it);
1182 }
1183 }
1184
Pawin Vongmasa36653902018-11-15 00:10:25 -08001185 uint32_t transform = 0;
1186 switch (quarters) {
1187 case 0: // no rotation
1188 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1189 break;
1190 case 1: // 90 degrees counter-clockwise
1191 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1192 : HAL_TRANSFORM_ROT_270;
1193 break;
1194 case 2: // 180 degrees
1195 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1196 break;
1197 case 3: // 90 degrees clockwise
1198 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1199 : HAL_TRANSFORM_ROT_90;
1200 break;
1201 }
1202
1203 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1204 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1205 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1206 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1207 if (surfaceScaling) {
1208 videoScalingMode = surfaceScaling->value;
1209 }
1210
1211 // Use dataspace from format as it has the default aspects already applied
1212 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1213 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1214
1215 // HDR static info
1216 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1217 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1218 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1219
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001220 // HDR10 plus info
1221 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1222 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1223 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001224 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1225 hdr10PlusInfo.reset();
1226 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001227
Wonsik Kima79c5522022-01-18 16:29:24 -08001228 // HDR dynamic info
1229 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1230 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1231 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1232 // TODO: make this sticky & enable unset
1233 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1234 hdrDynamicInfo.reset();
1235 }
1236
1237 if (hdr10PlusInfo) {
1238 // C2StreamHdr10PlusInfo is deprecated; components should use
1239 // C2StreamHdrDynamicMetadataInfo
1240 // TODO: #metric
1241 if (hdrDynamicInfo) {
1242 // It is unexpected that C2StreamHdr10PlusInfo and
1243 // C2StreamHdrDynamicMetadataInfo is both present.
1244 // C2StreamHdrDynamicMetadataInfo takes priority.
1245 // TODO: #metric
1246 } else {
1247 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1248 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1249 hdr10PlusInfo->flexCount(),
1250 0u,
1251 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1252 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1253 hdrDynamicInfo = info;
1254 }
1255 }
1256
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1258 if (blocks.size() != 1u) {
1259 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1260 return UNKNOWN_ERROR;
1261 }
1262 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001263 C2Fence c2fence = block.fence();
1264 sp<Fence> fence = Fence::NO_FENCE;
1265 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1266 // Once C2Fence::type() is added, check the exact C2Fence type
1267 if (c2fence.isHW()) {
1268 int fenceFd = c2fence.fd();
1269 fence = sp<Fence>::make(fenceFd);
1270 if (!fence) {
1271 ALOGE("[%s] Failed to allocate a fence", mName);
1272 close(fenceFd);
1273 return NO_MEMORY;
1274 }
1275 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276
1277 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001278 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001279 timestampNs,
1280 false, // droppable
1281 dataSpace,
1282 Rect(blocks.front().crop().left,
1283 blocks.front().crop().top,
1284 blocks.front().crop().right(),
1285 blocks.front().crop().bottom()),
1286 videoScalingMode,
1287 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001288 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001289 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001290 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001291 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001292 // If mastering max and min luminance fields are 0, do not use them.
1293 // It indicates the value may not be present in the stream.
1294 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1295 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1296 struct android_smpte2086_metadata smpte2086_meta = {
1297 .displayPrimaryRed = {
1298 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1299 },
1300 .displayPrimaryGreen = {
1301 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1302 },
1303 .displayPrimaryBlue = {
1304 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1305 },
1306 .whitePoint = {
1307 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1308 },
1309 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1310 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1311 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001312 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001313 hdr.smpte2086 = smpte2086_meta;
1314 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001315 // If the content light level fields are 0, do not use them, it
1316 // indicates the value may not be present in the stream.
1317 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1318 struct android_cta861_3_metadata cta861_meta = {
1319 .maxContentLightLevel = hdrStaticInfo->maxCll,
1320 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1321 };
1322 hdr.validTypes |= HdrMetadata::CTA861_3;
1323 hdr.cta8613 = cta861_meta;
1324 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001325
1326 // does not have valid info
1327 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1328 hdrStaticInfo.reset();
1329 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001330 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001331 if (hdrDynamicInfo
1332 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001333 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1334 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001335 hdrDynamicInfo->m.data,
1336 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001337 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 qbi.setHdrMetadata(hdr);
1339 }
Hongguangfc1478a2022-07-20 22:56:06 -07001340 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1341
Brian Lindahl932bf602023-03-09 11:59:48 -07001342 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1343 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1344 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1346 if (result != OK) {
1347 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001348 if (result == NO_INIT) {
1349 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1350 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 return result;
1352 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001353
1354 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1355 ALOGD("[%s] queue buffer successful", mName);
1356 } else {
1357 ALOGV("[%s] queue buffer successful", mName);
1358 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359
1360 int64_t mediaTimeUs = 0;
1361 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001362 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001363 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1364 processRenderedFrames(qbo.frameTimestamps);
1365 } else {
1366 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1367 // when the frame is queued to the non-display surface
1368 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1369 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370
1371 return OK;
1372}
1373
Brian Lindahl932bf602023-03-09 11:59:48 -07001374void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001375 mTrackedFrames.clear();
1376
1377 int isSurfaceToDisplay = 0;
1378 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1379 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1380 // No frame tracking is needed if we're not sending frames to the display
1381 if (!mIsSurfaceToDisplay) {
1382 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1383 return;
1384 }
1385
Brian Lindahl932bf602023-03-09 11:59:48 -07001386 int hasPresentFenceTimes = 0;
1387 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1388 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001389 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001390 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1391 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001392}
1393
1394void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1395 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1396 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1397 // so track the frame as if the desired render time is now.
1398 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1399 if (desiredRenderTimeNs < nowNs) {
1400 desiredRenderTimeNs = nowNs;
1401 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001402
1403 // If the render time is more than a second from now, then pretend the frame is supposed to be
1404 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1405 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1406 // processRenderedFrames.
1407 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1408 desiredRenderTimeNs = nowNs;
1409 }
1410
Brian Lindahl932bf602023-03-09 11:59:48 -07001411 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1412 // actually rendered.
1413 TrackedFrame frame;
1414 frame.number = qbo.nextFrameNumber - 1;
1415 frame.mediaTimeUs = mediaTimeUs;
1416 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1417 frame.latchTime = -1;
1418 frame.presentFence = nullptr;
1419 mTrackedFrames.push_back(frame);
1420}
1421
1422void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1423 // Grab the latch times and present fences from the frame event deltas
1424 for (const auto& delta : deltas) {
1425 for (auto& frame : mTrackedFrames) {
1426 if (delta.getFrameNumber() == frame.number) {
1427 delta.getLatchTime(&frame.latchTime);
1428 delta.getDisplayPresentFence(&frame.presentFence);
1429 }
1430 }
1431 }
1432
1433 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1434 // in fact, been rendered.
1435 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1436 while (!mTrackedFrames.empty()) {
1437 TrackedFrame & frame = mTrackedFrames.front();
1438 // Frames that should have been rendered at least 100ms in the past are checked
1439 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1440 break;
1441 }
1442
1443 // If we don't have a render time by now, then consider the frame as dropped
1444 int64_t renderTimeNs = getRenderTimeNs(frame);
1445 if (renderTimeNs != -1) {
1446 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1447 }
1448 mTrackedFrames.pop_front();
1449 }
1450}
1451
1452int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1453 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1454 if (!mHasPresentFenceTimes) {
1455 if (frame.latchTime == -1) {
1456 ALOGD("no latch time for frame %d", (int) frame.number);
1457 return -1;
1458 }
1459 return frame.latchTime;
1460 }
1461
1462 if (frame.presentFence == nullptr) {
1463 ALOGW("no present fence for frame %d", (int) frame.number);
1464 return -1;
1465 }
1466
1467 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1468
1469 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1470 ALOGW("invalid signal time for frame %d", (int) frame.number);
1471 return -1;
1472 }
1473
1474 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1475 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1476 return -1;
1477 }
1478
1479 return actualRenderTimeNs;
1480}
1481
1482void CCodecBufferChannel::pollForRenderedBuffers() {
1483 FrameEventHistoryDelta delta;
1484 mComponent->pollForRenderedFrames(&delta);
1485 processRenderedFrames(delta);
1486}
1487
Sungtak Lee214ce612023-11-01 10:01:13 +00001488void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001489 // Note: Since this is called asynchronously from IProducerListener not
1490 // knowing the internal state of CCodec/CCodecBufferChannel,
1491 // prevent mComponent from being destroyed by holding the shared reference
1492 // during this interface being executed.
1493 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1494 if (comp) {
1495 comp->onBufferReleasedFromOutputSurface(generation);
1496 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001497}
1498
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001499void CCodecBufferChannel::onBufferAttachedToOutputSurface(uint32_t generation) {
1500 // Note: Since this is called asynchronously from IProducerListener not
1501 // knowing the internal state of CCodec/CCodecBufferChannel,
1502 // prevent mComponent from being destroyed by holding the shared reference
1503 // during this interface being executed.
1504 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1505 if (comp) {
1506 comp->onBufferAttachedToOutputSurface(generation);
1507 }
1508}
1509
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1511 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1512 bool released = false;
1513 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001514 Mutexed<Input>::Locked input(mInput);
1515 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517 }
1518 }
1519 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001520 Mutexed<Output>::Locked output(mOutput);
1521 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 released = true;
1523 }
1524 }
1525 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001526 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001527 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 } else {
1529 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1530 }
1531 return OK;
1532}
1533
1534void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1535 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001536 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001538 if (!input->buffers) {
1539 ALOGE("getInputBufferArray: No Input Buffers allocated");
1540 return;
1541 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001542 if (!input->buffers->isArrayMode()) {
1543 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001544 }
1545
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001546 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001547}
1548
1549void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1550 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001551 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001552 if (!output->buffers) {
1553 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1554 return;
1555 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001556 if (!output->buffers->isArrayMode()) {
1557 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001558 }
1559
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001560 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001561}
1562
1563status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001564 const sp<AMessage> &inputFormat,
1565 const sp<AMessage> &outputFormat,
1566 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1568 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001569 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001570 C2PortReorderBufferDepthTuning::output reorderDepth;
1571 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001572 C2PortActualDelayTuning::input inputDelay(0);
1573 C2PortActualDelayTuning::output outputDelay(0);
1574 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001575 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001576
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577 c2_status_t err = mComponent->query(
1578 {
1579 &iStreamFormat,
1580 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001581 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 &reorderDepth,
1583 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001584 &inputDelay,
1585 &pipelineDelay,
1586 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001587 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001588 },
1589 {},
1590 C2_DONT_BLOCK,
1591 nullptr);
1592 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001593 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001594 return UNKNOWN_ERROR;
1595 }
1596 } else if (err != C2_OK) {
1597 return UNKNOWN_ERROR;
1598 }
1599
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001600 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1601 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1602 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1603
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001604 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1605 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001606
Pawin Vongmasa36653902018-11-15 00:10:25 -08001607 // TODO: get this from input format
1608 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1609
Sungtak Lee04b30352020-07-27 13:57:25 -07001610 // secure mode is a static parameter (shall not change in the executing state)
1611 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1612
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001614 int poolMask = GetCodec2PoolMask();
1615 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616
1617 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001618 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001619 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001620 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1621 API_REFLECTION |
1622 API_VALUES |
1623 API_CURRENT_VALUES |
1624 API_DEPENDENCY |
1625 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001626 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1627 C2StreamSampleRateInfo::input sampleRate(0u);
1628 C2StreamChannelCountInfo::input channelCount(0u);
1629 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 std::shared_ptr<C2BlockPool> pool;
1631 {
1632 Mutexed<BlockPools>::Locked pools(mBlockPools);
1633
1634 // set default allocator ID.
1635 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001636 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637
1638 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1639 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1640 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001641 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001642 std::vector<C2Param *> stackParams({&featuresSetting});
1643 if (audioEncoder) {
1644 stackParams.push_back(&encoderFrameSize);
1645 stackParams.push_back(&sampleRate);
1646 stackParams.push_back(&channelCount);
1647 stackParams.push_back(&pcmEncoding);
1648 } else {
1649 encoderFrameSize.invalidate();
1650 sampleRate.invalidate();
1651 channelCount.invalidate();
1652 pcmEncoding.invalidate();
1653 }
1654 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001655 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1656 C2_DONT_BLOCK,
1657 &params);
1658 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1659 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1660 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001661 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 C2PortAllocatorsTuning::input *inputAllocators =
1663 C2PortAllocatorsTuning::input::From(params[0].get());
1664 if (inputAllocators && inputAllocators->flexCount() > 0) {
1665 std::shared_ptr<C2Allocator> allocator;
1666 // verify allocator IDs and resolve default allocator
1667 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1668 if (allocator) {
1669 pools->inputAllocatorId = allocator->getId();
1670 } else {
1671 ALOGD("[%s] component requested invalid input allocator ID %u",
1672 mName, inputAllocators->m.values[0]);
1673 }
1674 }
1675 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001676 if (featuresSetting) {
1677 apiFeatures = featuresSetting.value;
1678 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001679
1680 // TODO: use C2Component wrapper to associate this pool with ourselves
1681 if ((poolMask >> pools->inputAllocatorId) & 1) {
1682 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1683 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1684 mName, pools->inputAllocatorId,
1685 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1686 asString(err), err);
1687 } else {
1688 err = C2_NOT_FOUND;
1689 }
1690 if (err != C2_OK) {
1691 C2BlockPool::local_id_t inputPoolId =
1692 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1693 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1694 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1695 mName, (unsigned long long)inputPoolId,
1696 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1697 asString(err), err);
1698 if (err != C2_OK) {
1699 return NO_MEMORY;
1700 }
1701 }
1702 pools->inputPool = pool;
1703 }
1704
Wonsik Kim51051262018-11-28 13:59:05 -08001705 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001706 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001707 input->inputDelay = inputDelayValue;
1708 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001709 input->numSlots = numInputSlots;
1710 input->extraBuffers.flush();
1711 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001712 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001713 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1714 input->frameReassembler.init(
1715 pool,
1716 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1717 encoderFrameSize.value,
1718 sampleRate.value,
1719 channelCount.value,
1720 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1721 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001722 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1723 // For encrypted content, framework decrypts source buffer (ashmem) into
1724 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001725 if (!buffersBoundToCodec
1726 && !input->frameReassembler
1727 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001728 input->buffers.reset(new SlotInputBuffers(mName));
1729 } else if (graphic) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00001730 if (mHasInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001731 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001733 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001734 // This is to ensure buffers do not get released prematurely.
1735 // TODO: handle this without going into array mode
1736 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001738 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 }
1740 } else {
1741 if (hasCryptoOrDescrambler()) {
1742 int32_t capacity = kLinearBufferSize;
1743 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1744 if ((size_t)capacity > kMaxLinearBufferSize) {
1745 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1746 capacity = kMaxLinearBufferSize;
1747 }
1748 if (mDealer == nullptr) {
1749 mDealer = new MemoryDealer(
1750 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001751 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 "EncryptedLinearInputBuffers");
1753 mDecryptDestination = mDealer->allocate((size_t)capacity);
1754 }
1755 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001756 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1757 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001758 } else {
1759 mHeapSeqNum = -1;
1760 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001761 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001762 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001763 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001764 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001766 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 }
1768 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001769 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001770
1771 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001772 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001773 } else {
1774 // TODO: error
1775 }
Wonsik Kim51051262018-11-28 13:59:05 -08001776
1777 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001778 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001779 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001780 }
1781
1782 if (outputFormat != nullptr) {
1783 sp<IGraphicBufferProducer> outputSurface;
1784 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001785 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001786 {
1787 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001788 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001789 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001790 outputSurface = output->surface ?
1791 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001792 if (outputSurface) {
1793 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1794 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001795 outputGeneration = output->generation;
1796 }
1797
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001798 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001799 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001800 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801
1802 {
1803 Mutexed<BlockPools>::Locked pools(mBlockPools);
1804
David Stevensc3fbb282021-01-18 18:11:20 +09001805 prevOutputPoolId = pools->outputPoolId;
1806
Pawin Vongmasa36653902018-11-15 00:10:25 -08001807 // set default allocator ID.
1808 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001809 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001810
1811 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1812 // unsuccessful.
1813 std::vector<std::unique_ptr<C2Param>> params;
1814 err = mComponent->query({ },
1815 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1816 C2_DONT_BLOCK,
1817 &params);
1818 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1819 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1820 mName, params.size(), asString(err), err);
1821 } else if (err == C2_OK && params.size() == 1) {
1822 C2PortAllocatorsTuning::output *outputAllocators =
1823 C2PortAllocatorsTuning::output::From(params[0].get());
1824 if (outputAllocators && outputAllocators->flexCount() > 0) {
1825 std::shared_ptr<C2Allocator> allocator;
1826 // verify allocator IDs and resolve default allocator
1827 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1828 if (allocator) {
1829 pools->outputAllocatorId = allocator->getId();
1830 } else {
1831 ALOGD("[%s] component requested invalid output allocator ID %u",
1832 mName, outputAllocators->m.values[0]);
1833 }
1834 }
1835 }
1836
1837 // use bufferqueue if outputting to a surface.
1838 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1839 // if unsuccessful.
1840 if (outputSurface) {
1841 params.clear();
1842 err = mComponent->query({ },
1843 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1844 C2_DONT_BLOCK,
1845 &params);
1846 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1847 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1848 mName, params.size(), asString(err), err);
1849 } else if (err == C2_OK && params.size() == 1) {
1850 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1851 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1852 if (surfaceAllocator) {
1853 std::shared_ptr<C2Allocator> allocator;
1854 // verify allocator IDs and resolve default allocator
1855 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1856 if (allocator) {
1857 pools->outputAllocatorId = allocator->getId();
1858 } else {
1859 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1860 mName, surfaceAllocator->value);
1861 err = C2_BAD_VALUE;
1862 }
1863 }
1864 }
1865 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1866 && err != C2_OK
1867 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1868 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1869 }
1870 }
1871
1872 if ((poolMask >> pools->outputAllocatorId) & 1) {
1873 err = mComponent->createBlockPool(
1874 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1875 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1876 mName, pools->outputAllocatorId,
1877 (unsigned long long)pools->outputPoolId,
1878 asString(err));
1879 } else {
1880 err = C2_NOT_FOUND;
1881 }
1882 if (err != C2_OK) {
1883 // use basic pool instead
1884 pools->outputPoolId =
1885 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1886 }
1887
1888 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1889 // component.
1890 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1891 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1892
1893 std::vector<std::unique_ptr<C2SettingResult>> failures;
1894 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1895 ALOGD("[%s] Configured output block pool ids %llu => %s",
1896 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1897 outputPoolId_ = pools->outputPoolId;
1898 }
1899
David Stevensc3fbb282021-01-18 18:11:20 +09001900 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1901 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1902 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1903 if (err != C2_OK) {
1904 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1905 (unsigned long long) prevOutputPoolId, asString(err), err);
1906 }
1907 }
1908
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001909 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001910 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001911 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001912 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001914 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001915 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001916 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001917 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001918 }
1919 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001920 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001922 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001923
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001924 output->buffers->clearStash();
1925 if (reorderDepth) {
1926 output->buffers->setReorderDepth(reorderDepth.value);
1927 }
1928 if (reorderKey) {
1929 output->buffers->setReorderKey(reorderKey.value);
1930 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001931
1932 // Try to set output surface to created block pool if given.
1933 if (outputSurface) {
1934 mComponent->setOutputSurface(
1935 outputPoolId_,
1936 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001937 outputGeneration,
1938 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001939 } else {
1940 // configure CPU read consumer usage
1941 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1942 std::vector<std::unique_ptr<C2SettingResult>> failures;
1943 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1944 // do not print error message for now as most components may not yet
1945 // support this setting
1946 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1947 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948 }
1949
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001950 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001951 if (buffersBoundToCodec) {
1952 // WORKAROUND: if we're using early CSD workaround we convert to
1953 // array mode, to appease apps assuming the output
1954 // buffers to be of the same size.
1955 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1956 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001957
1958 int32_t channelCount;
1959 int32_t sampleRate;
1960 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1961 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1962 int32_t delay = 0;
1963 int32_t padding = 0;;
1964 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1965 delay = 0;
1966 }
1967 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1968 padding = 0;
1969 }
1970 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001971 // We need write access to the buffers, so turn them into array mode.
1972 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1973 // component, runs it through SkipCutBuffer and allocate local buffer to be
1974 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1975 // toArrayMode().
1976 if (!output->buffers->isArrayMode()) {
1977 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1978 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001979 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001980 }
1981 }
1982 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001983
1984 int32_t tunneled = 0;
1985 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1986 tunneled = 0;
1987 }
1988 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001989 }
1990
1991 // Set up pipeline control. This has to be done after mInputBuffers and
1992 // mOutputBuffers are initialized to make sure that lingering callbacks
1993 // about buffers from the previous generation do not interfere with the
1994 // newly initialized pipeline capacity.
1995
Wonsik Kim62545252021-01-20 11:25:41 -08001996 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001997 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001998 watcher->inputDelay(inputDelayValue)
1999 .pipelineDelay(pipelineDelayValue)
2000 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08002001 .smoothnessFactor(kSmoothnessFactor)
2002 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002003 watcher->flush();
2004 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005
2006 mInputMetEos = false;
2007 mSync.start();
2008 return OK;
2009}
2010
Wonsik Kim34b28b42022-05-20 15:49:32 -07002011status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00002012 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002013 if (mHasInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002014 return OK;
2015 }
2016
Wonsik Kim34b28b42022-05-20 15:49:32 -07002017 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00002018 int retryCount = 1;
2019 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
2020 {
2021 Mutexed<Input>::Locked input(mInput);
2022 while (clientInputBuffers->size() < numInputSlots) {
2023 size_t index;
2024 sp<MediaCodecBuffer> buffer;
2025 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
2026 break;
2027 }
2028 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002029 }
Arun Johnson326166e2023-07-28 19:11:52 +00002030 }
2031 if (!retry || (retryCount <= 0)) {
2032 break;
2033 }
2034 if (clientInputBuffers->empty()) {
2035 // wait: buffer may be in transit from component.
2036 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07002037 }
2038 }
2039 if (clientInputBuffers->empty()) {
2040 ALOGW("[%s] start: cannot allocate memory at all", mName);
2041 return NO_MEMORY;
2042 } else if (clientInputBuffers->size() < numInputSlots) {
2043 ALOGD("[%s] start: cannot allocate memory for all slots, "
2044 "only %zu buffers allocated",
2045 mName, clientInputBuffers->size());
2046 } else {
2047 ALOGV("[%s] %zu initial input buffers available",
2048 mName, clientInputBuffers->size());
2049 }
2050 return OK;
2051}
2052
2053status_t CCodecBufferChannel::requestInitialInputBuffers(
2054 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002055 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002056 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
2057 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
2058 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002059 return UNKNOWN_ERROR;
2060 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002061
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002062 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2063 mFlushedConfigs.lock()->swap(flushedConfigs);
2064 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002065 {
2066 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2067 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2068 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2069 watcher->onWorkQueued(
2070 work->input.ordinal.frameIndex.peeku(),
2071 std::vector(work->input.buffers),
2072 now);
2073 }
2074 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002075 err = mComponent->queue(&flushedConfigs);
2076 if (err != C2_OK) {
2077 ALOGW("[%s] Error while queueing a flushed config", mName);
2078 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 }
2080 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002081 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002082 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2083 !clientInputBuffers.empty()) {
2084 size_t minIndex = clientInputBuffers.begin()->first;
2085 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2086 for (const auto &[index, buffer] : clientInputBuffers) {
2087 if (minBuffer->capacity() > buffer->capacity()) {
2088 minIndex = index;
2089 minBuffer = buffer;
2090 }
2091 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002092 // WORKAROUND: Some apps expect CSD available without queueing
2093 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002094 minBuffer->setRange(0, 0);
2095 minBuffer->meta()->clear();
2096 minBuffer->meta()->setInt64("timeUs", 0);
2097 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002098 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2099 mName);
2100 return UNKNOWN_ERROR;
2101 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002102 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002103 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002104
Wonsik Kim34b28b42022-05-20 15:49:32 -07002105 for (const auto &[index, buffer] : clientInputBuffers) {
2106 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002108
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 return OK;
2110}
2111
2112void CCodecBufferChannel::stop() {
2113 mSync.stop();
2114 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302115 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002116}
2117
Sungtak Lee99144332023-01-26 11:03:14 +00002118void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2119 sp<Surface> surface = mOutputSurface.lock()->surface;
2120 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002121 C2BlockPool::local_id_t outputPoolId;
2122 {
2123 Mutexed<BlockPools>::Locked pools(mBlockPools);
2124 outputPoolId = pools->outputPoolId;
2125 }
2126 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002127
2128 if (pushBlankBuffer) {
2129 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2130 if (anw) {
2131 pushBlankBuffersToNativeWindow(anw.get());
2132 }
2133 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002134 }
2135}
2136
Wonsik Kim936a89c2020-05-08 16:07:50 -07002137void CCodecBufferChannel::reset() {
2138 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002139 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002140 {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002141 mHasInputSurface = false;
2142 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2143 inputSurface->surface.reset();
2144 }
2145 {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002146 Mutexed<Input>::Locked input(mInput);
2147 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002148 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002149 }
2150 {
2151 Mutexed<Output>::Locked output(mOutput);
2152 output->buffers.reset();
2153 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002154 // reset the frames that are being tracked for onFrameRendered callbacks
2155 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002156}
2157
2158void CCodecBufferChannel::release() {
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302159 mInfoBuffers.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002160 mComponent.reset();
2161 mInputAllocator.reset();
2162 mOutputSurface.lock()->surface.clear();
2163 {
2164 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2165 blockPools->inputPool.reset();
2166 blockPools->outputPoolIntf.reset();
2167 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002168 setCrypto(nullptr);
2169 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002170}
2171
Pawin Vongmasa36653902018-11-15 00:10:25 -08002172void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2173 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002174 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002175 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002176 {
2177 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2178 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2179 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2180 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2181 watcher->onWorkDone(frameIndex);
2182 continue;
2183 }
2184 if (work->input.buffers.empty()
2185 || work->input.buffers.front() == nullptr
2186 || work->input.buffers.front()->data().linearBlocks().empty()) {
2187 ALOGD("[%s] no linear codec config data found", mName);
2188 watcher->onWorkDone(frameIndex);
2189 continue;
2190 }
2191 std::unique_ptr<C2Work> copy(new C2Work);
2192 copy->input.flags = C2FrameData::flags_t(
2193 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2194 copy->input.ordinal = work->input.ordinal;
2195 copy->input.ordinal.frameIndex = mFrameIndex++;
2196 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2197 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2198 }
2199 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2200 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2201 }
2202 copy->input.infoBuffers.insert(
2203 copy->input.infoBuffers.begin(),
2204 work->input.infoBuffers.begin(),
2205 work->input.infoBuffers.end());
2206 copy->worklets.emplace_back(new C2Worklet);
2207 configs.push_back(std::move(copy));
2208 watcher->onWorkDone(frameIndex);
2209 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002210 }
2211 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002212 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002213 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002214 Mutexed<Input>::Locked input(mInput);
2215 input->buffers->flush();
2216 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002217 }
2218 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002219 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002220 if (output->buffers) {
2221 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002222 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002223 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002224 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302225 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226}
2227
2228void CCodecBufferChannel::onWorkDone(
2229 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002230 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002232 feedInputBufferIfAvailable();
2233 }
2234}
2235
2236void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002237 uint64_t frameIndex, size_t arrayIndex) {
2238 std::shared_ptr<C2Buffer> buffer =
2239 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002240 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002241 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002242 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002243 if (input->lastFlushIndex >= frameIndex) {
2244 ALOGD("[%s] Ignoring stale input buffer done callback: "
2245 "last flush index = %lld, frameIndex = %lld",
2246 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2247 } else {
2248 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2249 if (!newInputSlotAvailable) {
2250 (void)input->extraBuffers.expireComponentBuffer(buffer);
2251 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002252 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002253 }
2254 if (newInputSlotAvailable) {
2255 feedInputBufferIfAvailable();
2256 }
2257}
2258
2259bool CCodecBufferChannel::handleWork(
2260 std::unique_ptr<C2Work> work,
2261 const sp<AMessage> &outputFormat,
2262 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002263 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002264 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002265 if (!output->buffers) {
2266 return false;
2267 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002268 }
2269
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002270 // Whether the output buffer should be reported to the client or not.
2271 bool notifyClient = false;
2272
2273 if (work->result == C2_OK){
2274 notifyClient = true;
2275 } else if (work->result == C2_NOT_FOUND) {
2276 ALOGD("[%s] flushed work; ignored.", mName);
2277 } else {
2278 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2279 // the config update.
2280 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2281 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2282 return false;
2283 }
2284
2285 if ((work->input.ordinal.frameIndex -
2286 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002287 // Discard frames from previous generation.
2288 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002289 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002290 }
2291
Wonsik Kimfca97a22024-08-30 20:20:42 +00002292 if (!mHasInputSurface && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002293 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002294 || !(work->worklets.front()->output.flags &
2295 C2FrameData::FLAG_INCOMPLETE))) {
2296 mPipelineWatcher.lock()->onWorkDone(
2297 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 }
2299
2300 // NOTE: MediaCodec usage supposedly have only one worklet
2301 if (work->worklets.size() != 1u) {
2302 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2303 mName, work->worklets.size());
2304 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2305 return false;
2306 }
2307
2308 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2309
2310 std::shared_ptr<C2Buffer> buffer;
2311 // NOTE: MediaCodec usage supposedly have only one output stream.
2312 if (worklet->output.buffers.size() > 1u) {
2313 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2314 mName, worklet->output.buffers.size());
2315 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2316 return false;
2317 } else if (worklet->output.buffers.size() == 1u) {
2318 buffer = worklet->output.buffers[0];
2319 if (!buffer) {
2320 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2321 }
2322 }
2323
Wonsik Kim3dedf682021-05-03 10:57:09 -07002324 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2325 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002326 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002327 while (!worklet->output.configUpdate.empty()) {
2328 std::unique_ptr<C2Param> param;
2329 worklet->output.configUpdate.back().swap(param);
2330 worklet->output.configUpdate.pop_back();
2331 switch (param->coreIndex().coreIndex()) {
2332 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2333 C2PortReorderBufferDepthTuning::output reorderDepth;
2334 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002335 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2336 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002337 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002338 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002339 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002340 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2341 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002342 }
2343 break;
2344 }
2345 case C2PortReorderKeySetting::CORE_INDEX: {
2346 C2PortReorderKeySetting::output reorderKey;
2347 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002348 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002349 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2350 mName, reorderKey.value);
2351 } else {
2352 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2353 }
2354 break;
2355 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002356 case C2PortActualDelayTuning::CORE_INDEX: {
2357 if (param->isGlobal()) {
2358 C2ActualPipelineDelayTuning pipelineDelay;
2359 if (pipelineDelay.updateFrom(*param)) {
2360 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2361 mName, pipelineDelay.value);
2362 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002363 (void)mPipelineWatcher.lock()->pipelineDelay(
2364 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002365 }
2366 }
2367 if (param->forInput()) {
2368 C2PortActualDelayTuning::input inputDelay;
2369 if (inputDelay.updateFrom(*param)) {
2370 ALOGV("[%s] onWorkDone: updating input delay %u",
2371 mName, inputDelay.value);
2372 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002373 (void)mPipelineWatcher.lock()->inputDelay(
2374 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002375 }
2376 }
2377 if (param->forOutput()) {
2378 C2PortActualDelayTuning::output outputDelay;
2379 if (outputDelay.updateFrom(*param)) {
2380 ALOGV("[%s] onWorkDone: updating output delay %u",
2381 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002382 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002383 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002384 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002385
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002386 }
2387 }
2388 break;
2389 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002390 case C2PortTunnelSystemTime::CORE_INDEX: {
2391 C2PortTunnelSystemTime::output frameRenderTime;
2392 if (frameRenderTime.updateFrom(*param)) {
2393 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2394 mName, (long long)frameRenderTime.value,
2395 (long long)worklet->output.ordinal.timestamp.peekll());
2396 mCCodecCallback->onOutputFramesRendered(
2397 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2398 }
2399 break;
2400 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002401 case C2StreamTunnelHoldRender::CORE_INDEX: {
2402 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2403 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2404 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2405 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2406 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2407 mCCodecCallback->onFirstTunnelFrameReady();
2408 break;
2409 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002410 default:
2411 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2412 mName, param->index());
2413 break;
2414 }
2415 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002416 if (newInputDelay || newPipelineDelay) {
2417 Mutexed<Input>::Locked input(mInput);
2418 size_t newNumSlots =
2419 newInputDelay.value_or(input->inputDelay) +
2420 newPipelineDelay.value_or(input->pipelineDelay) +
2421 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002422 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002423 if (input->buffers->isArrayMode()) {
2424 if (input->numSlots >= newNumSlots) {
2425 input->numExtraSlots = 0;
2426 } else {
2427 input->numExtraSlots = newNumSlots - input->numSlots;
2428 }
2429 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2430 mName, input->numExtraSlots);
2431 } else {
2432 input->numSlots = newNumSlots;
2433 }
2434 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002435 size_t numOutputSlots = 0;
2436 uint32_t reorderDepth = 0;
2437 bool outputBuffersChanged = false;
2438 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2439 Mutexed<Output>::Locked output(mOutput);
2440 if (!output->buffers) {
2441 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002442 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002443 numOutputSlots = output->numSlots;
2444 if (newReorderKey) {
2445 output->buffers->setReorderKey(newReorderKey.value());
2446 }
2447 if (newReorderDepth) {
2448 output->buffers->setReorderDepth(newReorderDepth.value());
2449 }
2450 reorderDepth = output->buffers->getReorderDepth();
2451 if (newOutputDelay) {
2452 output->outputDelay = newOutputDelay.value();
2453 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2454 if (output->numSlots < numOutputSlots) {
2455 output->numSlots = numOutputSlots;
2456 if (output->buffers->isArrayMode()) {
2457 OutputBuffersArray *array =
2458 (OutputBuffersArray *)output->buffers.get();
2459 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2460 mName, numOutputSlots);
2461 array->grow(numOutputSlots);
2462 outputBuffersChanged = true;
2463 }
2464 }
2465 }
2466 numOutputSlots = output->numSlots;
2467 }
2468 if (outputBuffersChanged) {
2469 mCCodecCallback->onOutputBuffersChanged();
2470 }
2471 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002472 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002473 {
2474 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2475 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002476 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002477 if (output->surface) {
2478 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2479 }
2480 }
2481 if (maxDequeueCount > 0) {
2482 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002483 }
2484 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002485
Pawin Vongmasa36653902018-11-15 00:10:25 -08002486 int32_t flags = 0;
2487 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002488 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002489 ALOGV("[%s] onWorkDone: output EOS", mName);
2490 }
2491
Pawin Vongmasa36653902018-11-15 00:10:25 -08002492 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2493 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2494 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2495 // shall correspond to the client input timesamp (in customOrdinal). By using the
2496 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2497 // produces multiple output.
2498 c2_cntr64_t timestamp =
2499 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2500 - work->input.ordinal.timestamp;
Wonsik Kimfca97a22024-08-30 20:20:42 +00002501 if (mHasInputSurface) {
Wonsik Kim95ba0162019-03-19 15:51:54 -07002502 // When using input surface we need to restore the original input timestamp.
2503 timestamp = work->input.ordinal.customOrdinal;
2504 }
My Name6bd9a7d2022-03-25 12:37:58 -07002505 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2506 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002507 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2508 mName,
2509 work->input.ordinal.customOrdinal.peekll(),
2510 work->input.ordinal.timestamp.peekll(),
2511 worklet->output.ordinal.timestamp.peekll(),
2512 timestamp.peekll());
2513
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002514 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002515 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002516 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002517 if (!output->buffers) {
2518 return false;
2519 }
2520 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002521 output->buffers->updateSkipCutBuffer(outputFormat);
2522 output->buffers->setFormat(outputFormat);
2523 }
2524 if (!notifyClient) {
2525 return false;
2526 }
2527 size_t index;
2528 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002529 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002530 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002531 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002532 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2533
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002534 // TRICKY: we want popped buffers reported in order, so sending
2535 // the callback while holding the lock here. This assumes that
2536 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2537 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002538 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002539 } else {
2540 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002541 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002542 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002543 return false;
2544 }
2545 }
2546
Wonsik Kimec585c32021-10-01 01:11:00 -07002547 bool drop = false;
2548 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2549 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2550 drop = true;
2551 }
2552
Marc Kassisec910342022-11-25 11:43:05 +01002553 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2554 // HAL, the flag is then removed in the corresponding output buffer.
2555 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2556 flags |= BUFFER_FLAG_DECODE_ONLY;
2557 }
2558
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002559 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002560 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002561 if (mOutputFormat != outputFormat) {
2562 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2563 mName, work->input.ordinal.frameIndex.peekull());
2564 mOutputFormat = outputFormat;
2565 } else {
2566 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2567 mName, work->input.ordinal.frameIndex.peekull());
2568 notifyClient = false;
2569 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002570 } else {
2571 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2572 mName, work->input.ordinal.frameIndex.peekull());
2573 notifyClient = false;
2574 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002575 }
2576
2577 if (buffer) {
2578 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2579 // TODO: properly translate these to metadata
2580 switch (info->coreIndex().coreIndex()) {
2581 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002582 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002583 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002584 }
2585 break;
2586 default:
2587 break;
2588 }
2589 }
2590 }
2591
2592 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002593 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002594 if (!output->buffers) {
2595 return false;
2596 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002597 output->buffers->pushToStash(
2598 buffer,
2599 notifyClient,
2600 timestamp.peek(),
2601 flags,
2602 outputFormat,
2603 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002604 }
2605 sendOutputBuffers();
2606 return true;
2607}
2608
2609void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002610 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002611 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002612 sp<MediaCodecBuffer> outBuffer;
2613 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002614
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002615 constexpr int kMaxReallocTry = 5;
2616 int reallocTryNum = 0;
2617
Pawin Vongmasa36653902018-11-15 00:10:25 -08002618 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002619 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002620 if (!output->buffers) {
2621 return;
2622 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002623 action = output->buffers->popFromStashAndRegister(
2624 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002625 if (action != OutputBuffers::REALLOCATE) {
2626 reallocTryNum = 0;
2627 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002628 switch (action) {
2629 case OutputBuffers::SKIP:
2630 return;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002631 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002632 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002633 // TRICKY: we want popped buffers reported in order, so sending
2634 // the callback while holding the lock here. This assumes that
2635 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2636 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002637 if (c2Buffer) {
2638 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2639 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2640 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2641 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2642 uint32_t flag = 0;
2643 std::vector<AccessUnitInfo> accessUnitInfos;
2644 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2645 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2646 bufferMetadata->m.values[nMeta];
2647 flag = convertFlags(bufferMetadataStruct.flags, false);
2648 accessUnitInfos.emplace_back(flag,
Arun Johnson9c6e91e2024-09-10 18:46:02 +00002649 bufferMetadataStruct.size,
2650 bufferMetadataStruct.timestamp);
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002651 }
2652 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2653 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2654 outBuffer->meta()->setObject("accessUnitInfo", obj);
2655 }
2656 }
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002657 mCallback->onOutputBufferAvailable(index, outBuffer);
2658 [[fallthrough]];
2659 }
2660 case OutputBuffers::DISCARD: {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002661 if (mHasInputSurface && android::media::codec::provider_->input_surface_throttle()) {
2662 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2663 --inputSurface->numProcessingBuffersBalance;
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002664 ALOGV("[%s] onWorkDone: numProcessingBuffersBalance = %lld",
2665 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
Wonsik Kimfca97a22024-08-30 20:20:42 +00002666 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002667 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002668 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002669 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002670 if (++reallocTryNum > kMaxReallocTry) {
2671 output.unlock();
2672 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2673 mName, kMaxReallocTry);
2674 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2675 return;
2676 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002677 if (!output->buffers->isArrayMode()) {
2678 output->buffers =
2679 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002680 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002681 static_cast<OutputBuffersArray*>(output->buffers.get())->
2682 realloc(c2Buffer);
2683 output.unlock();
2684 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002685 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002686 case OutputBuffers::RETRY:
2687 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2688 mName);
2689 return;
2690 default:
2691 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2692 "corrupted BufferAction value (%d) "
2693 "returned from popFromStashAndRegister.",
2694 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002695 return;
2696 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002697 }
2698}
2699
Sungtak Lee214ce612023-11-01 10:01:13 +00002700status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2701 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002702 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002703 int maxDequeueCount;
2704 sp<Surface> oldSurface;
2705 {
2706 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2707 maxDequeueCount = outputSurface->maxDequeueBuffers;
2708 oldSurface = outputSurface->surface;
2709 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002710 if (newSurface) {
2711 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002712 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002713 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002714 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002715 } else {
2716 ALOGE("[%s] setting output surface to null", mName);
2717 return INVALID_OPERATION;
2718 }
2719
2720 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2721 C2BlockPool::local_id_t outputPoolId;
2722 {
2723 Mutexed<BlockPools>::Locked pools(mBlockPools);
2724 outputPoolId = pools->outputPoolId;
2725 outputPoolIntf = pools->outputPoolIntf;
2726 }
2727
2728 if (outputPoolIntf) {
2729 if (mComponent->setOutputSurface(
2730 outputPoolId,
2731 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002732 generation,
2733 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002734 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2735 return INVALID_OPERATION;
2736 }
2737 }
2738
2739 {
2740 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2741 output->surface = newSurface;
2742 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002743 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002744 }
2745
Sungtak Lee99144332023-01-26 11:03:14 +00002746 if (oldSurface && pushBlankBuffer) {
2747 // When ReleaseSurface was set from MediaCodec,
2748 // pushing a blank buffer at the end might be necessary.
2749 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2750 if (anw) {
2751 pushBlankBuffersToNativeWindow(anw.get());
2752 }
2753 }
2754
Pawin Vongmasa36653902018-11-15 00:10:25 -08002755 return OK;
2756}
2757
Wonsik Kimab34ed62019-01-31 15:28:46 -08002758PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002759 // Otherwise, component may have stalled work due to input starvation up to
2760 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002761 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2762 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002763 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002764 size_t outputDelay = mOutput.lock()->outputDelay;
2765 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002766 Mutexed<Input>::Locked input(mInput);
2767 n = input->inputDelay + input->pipelineDelay + outputDelay;
2768 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002769 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002770}
2771
Pawin Vongmasa36653902018-11-15 00:10:25 -08002772void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2773 mMetaMode = mode;
2774}
2775
Wonsik Kim596187e2019-10-25 12:44:10 -07002776void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002777 if (mCrypto != nullptr) {
2778 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2779 mCrypto->unsetHeap(entry.second);
2780 }
2781 mHeapSeqNumMap.clear();
2782 if (mHeapSeqNum >= 0) {
2783 mCrypto->unsetHeap(mHeapSeqNum);
2784 mHeapSeqNum = -1;
2785 }
2786 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002787 mCrypto = crypto;
2788}
2789
2790void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2791 mDescrambler = descrambler;
2792}
2793
Songyue Han1e6769b2023-08-30 18:09:27 +00002794uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2795 if (isEncoder) {
2796 return getInputBuffersPixelFormat();
2797 } else {
2798 return getOutputBuffersPixelFormat();
2799 }
2800}
2801
2802uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2803 Mutexed<Input>::Locked input(mInput);
2804 if (input->buffers == nullptr) {
2805 return PIXEL_FORMAT_UNKNOWN;
2806 }
2807 return input->buffers->getPixelFormatIfApplicable();
2808}
2809
2810uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2811 Mutexed<Output>::Locked output(mOutput);
2812 if (output->buffers == nullptr) {
2813 return PIXEL_FORMAT_UNKNOWN;
2814 }
2815 return output->buffers->getPixelFormatIfApplicable();
2816}
2817
2818void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2819 if (isEncoder) {
2820 Mutexed<Input>::Locked input(mInput);
2821 if (input->buffers == nullptr) {
2822 return;
2823 }
2824 input->buffers->resetPixelFormatIfApplicable();
2825 } else {
2826 Mutexed<Output>::Locked output(mOutput);
2827 if (output->buffers == nullptr) {
2828 return;
2829 }
2830 output->buffers->resetPixelFormatIfApplicable();
2831 }
2832}
2833
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302834void CCodecBufferChannel::setInfoBuffer(const std::shared_ptr<C2InfoBuffer> &buffer) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002835 if (!mHasInputSurface) {
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002836 mInfoBuffers.push_back(buffer);
2837 } else {
2838 std::list<std::unique_ptr<C2Work>> items;
2839 std::unique_ptr<C2Work> work(new C2Work);
2840 work->input.infoBuffers.emplace_back(*buffer);
2841 work->worklets.emplace_back(new C2Worklet);
2842 items.push_back(std::move(work));
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002843 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302844}
2845
Pawin Vongmasa36653902018-11-15 00:10:25 -08002846status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2847 // C2_OK is always translated to OK.
2848 if (c2s == C2_OK) {
2849 return OK;
2850 }
2851
2852 // Operation-dependent translation
2853 // TODO: Add as necessary
2854 switch (c2op) {
2855 case C2_OPERATION_Component_start:
2856 switch (c2s) {
2857 case C2_NO_MEMORY:
2858 return NO_MEMORY;
2859 default:
2860 return UNKNOWN_ERROR;
2861 }
2862 default:
2863 break;
2864 }
2865
2866 // Backup operation-agnostic translation
2867 switch (c2s) {
2868 case C2_BAD_INDEX:
2869 return BAD_INDEX;
2870 case C2_BAD_VALUE:
2871 return BAD_VALUE;
2872 case C2_BLOCKING:
2873 return WOULD_BLOCK;
2874 case C2_DUPLICATE:
2875 return ALREADY_EXISTS;
2876 case C2_NO_INIT:
2877 return NO_INIT;
2878 case C2_NO_MEMORY:
2879 return NO_MEMORY;
2880 case C2_NOT_FOUND:
2881 return NAME_NOT_FOUND;
2882 case C2_TIMED_OUT:
2883 return TIMED_OUT;
2884 case C2_BAD_STATE:
2885 case C2_CANCELED:
2886 case C2_CANNOT_DO:
2887 case C2_CORRUPTED:
2888 case C2_OMITTED:
2889 case C2_REFUSED:
2890 return UNKNOWN_ERROR;
2891 default:
2892 return -static_cast<status_t>(c2s);
2893 }
2894}
2895
Pawin Vongmasa36653902018-11-15 00:10:25 -08002896} // namespace android